Add to the beginning of Reactive Forms Array Angular
Asked Answered
D

1

1

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.

Dispel answered 8/6, 2017 at 21:15 Comment(8)
"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.Stopped
It really takes that much code for a Minimal example its Angular were talking about here hahaDispel
Have you read the docs? There's insert method that you can specify the index.Priming
@Priming 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.Dispel
very interesting issue. push is working fine. did u checked angular git hub issue.Riggall
Wait... what's this question about? It isn't clear at all. What do you mean in this: "...the form view does not reflect the forms state..."?Priming
@Jonnysai yea I saw that push was working but my actual use case need the ability to append to the front of the list and so I needed insert to work and it was going crazyDispel
This question lacking a minimal reproducible example and thus could do with being placed On Hold.Knur
U
5

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

Uncertain answered 9/6, 2017 at 7:28 Comment(2)
Thank you this solved the issue, I did not know about the trackByDispel
You are welcome, glad I could help! :) Yes, trackBy is usually (only) needed when we are dealing with primitive types, which this is not though. But apparently Angular has trouble keeping the track of index when you are inserting the value in the beginning of the array instead of just pushing a new value in the end of the array (which works without trackBy). This is actually quite interesting :)Uncertain

© 2022 - 2024 — McMap. All rights reserved.