Deleting rows while generating dynamic form fields deleting always the last index

Viewed 206

I have created a dynamic form field application where one can add or delete rows dynamically . Everything works fine but when i try to delete rows when they are >=3 , always the last row is being deleted .

I tried debugging the app , it receiveds the right index for deleting , but still it deletes the last row always .

As in the below image it can be seen there are 3 rows , i am trying trying to delete the row with index 1 , but still the row with index 2 gets deleted .

Any guidance appreciated . thanks in advance

1 Answers

You are on the right track with TrackBy (pun inteded!)

In some cases returning the index from it is sufficient enough, sometimes not, like in this case. Therefore it's recommended to actually track something that is completely unique for each item, as we know that indexes do change in ngFor.

As you currently do not have anything that is unique enough, we can add an additional field, so when you push a new item to formarray, we can add for example a Date field that will always be unique. Of course when submitting the form, you need to filter out the Date, but that is not too big of an issue.

So I recommend the following:

newDynamics(): FormGroup {
  return this.fb.group({
    field: '',
    operator: '',
    value:'',
    andOr:'',
    date: new Date() // add an unique identifier
  })
}

and then the trackby:

trackByFn(index, item) {
  return item.date; // always unique!
}

YOUR STACKBLITZ

Any unique identifier will do, for example you can push an id for each formgroup. The above is just one option.

Related