1
votes

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.

1
"it is too much code to copy paste here" - then cut it down to a minimal reproducible example, that's part of the work of asking a question here.jonrsharpe
It really takes that much code for a Minimal example its Angular were talking about here hahajo_wil
Have you read the docs? There's insert method that you can specify the index.developer033
@developer033 I am using that insert method, you can see this on line 83 of app.js in the plunker. It is inserting into the model fine, it is just that the rendered view does not reflect the state of the model. And by model I mean the FormGroup and associated FormArray.jo_wil
very interesting issue. push is working fine. did u checked angular git hub issue.CharanRoot

1 Answers

5
votes

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