Add to the the beginning of Reactive Forms Array A

2019-09-16 14:02发布

问题:

Please see the relevant plunker

https://plnkr.co/edit/f0BxpinhuqVz8o6IIFaL?p=preview

// stack overflow makes you put code if a plunker is linked but it is too much code to copy paste here it would just look messy so I a am putting this comment instead.

If you run this and then click the add button a new entry is added to the array, but the form view does not reflect the forms state, instead the first entry is duplicated and the last entry is gone.

If anyone has any ideas or guides as to what I am doing wrong I would be very grateful as I have been pretty stuck on a seemingly easy task.

I tried to follow the official Angular Reactive Forms guide as close as possible to build this example.

Thanks

回答1:

Seems like Angular has trouble tracking the index of your objects in your formArray. This can be solved by using trackBy. Add it to your iteration with function:

<div *ngFor="let detail of detailArray.controls; let i=index; trackBy:trackByFn" [formGroupName]="i">

and in component:

trackByFn(index: any, item: any) {
  return index;
} 

Your PLUNKER