Mad Eddie
Mad Eddie

Reputation: 1195

Angular button doesn't work within FormArray

I am trying a simple form array a bit like a ToDo list however I am adding a button to each item within the list to allow it to be deleted (though didn't recreate this part within the example).

I am finding that the button for each item is not "clickable". I also noticed that the "ripple" effect doesn't work as it should on those buttons too.

I have managed to create a stackblitz to re-create it so any help would be appreciated

https://stackblitz.com/edit/angular6-material-components-demo-ck2jpe

To use just enter something in to the textbox, click ADD and then try to delete it from the list below where it appeared

Upvotes: 0

Views: 334

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71891

The issue is that you do not add a trackBy function to your *ngFor. This makes the entire list DOM to be recreated when you do a mousedown, so the click never gets triggered, because the element is destroyed.

See here for a working example:

trackBy(idx: number, item: { id: number }): number {
  return item.id;
}

template:

<ul formArrayName="items"
    *ngFor="let item of exampleForm.controls.items.value; let i = index;trackBy: trackBy">

For more information you can read my answer about this subject. Basically what happens is that the exampleForm.controls.items.value reference changes with every event that happens.


Another solution, could be to use the changeDetection: ChangeDetectionStrategy.OnPush in your component declaration. I recommend you to use both trackBy and the OnPush for the most performance improvement. Be aware though that this might require some refactoring in your current application code.

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
  changeDetection: ChangeDetectionStrategy.OnPush
})

stack

Upvotes: 3

Related Questions