angular: Bug (?) - ReactiveForms > FormArray, trackBy index > removeAt & subscriptions

Hi Angular,

I think i found a [x] bug, but I’m not sure.

I have a large Reactive Form, with a FormArray… and I trackBy index. Each FormGroup in the array has subscriptions like:

  // get the rides so we can iterate over them
  get myRides(): FormArray {
    return this.ridesForm.get('rides') as FormArray;
  };
  trackByFn(index, item) {
    return index; // or item.id
  }
 // each ride that is added has subscriptions
  subscribeChanges(ride: FormGroup){

    ride['dateSub$'] = ride.get('date').valueChanges.subscribe(val => {
     });
    
    ride['distanceSub$'] = ride.get('distance').valueChanges.subscribe(val => {
    });

    ride['startCountSub$'] = ride.get('start_count').valueChanges.subscribe(val => {
    });

    ride['endCountSub$'] = ride.get('end_count').valueChanges.subscribe(val => {
    });
  }

now… you can also delete FormGroup’s using:

  // deletes a single ride
  public deleteRide(ride: FormGroup, i: number): void{
        this.unsubscribeChanges(ride);
       this.myRides.removeAt(i)
}
  unsubscribeChanges(ride: FormGroup){
    ride['dateSub$'].unsubscribe();
    ride['distanceSub$'].unsubscribe();
    ride['startCountSub$'].unsubscribe();
    ride['endCountSub$'].unsubscribe();
  }

but it seems that the tracking of objects goes wrong… So let’s delete a FormGroup at index 3 of 6 FormGroups…The subscriptions on the index of your removed FormGroup - and below that - do not fire anymore. As if their binding is still on a ‘old’ index.

Is it not allowed to put your Subs$ on a FormGroup? Or is there a bug in the tracking / refreshing of FormGroup’s in the array?

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Comments: 18 (2 by maintainers)

Most upvoted comments

I am experiencing this issue as well using Angular v13. Here is my minimalistic reproduction which only involves a trackBy function and FormArray.removeAt(): https://stackblitz.com/edit/angular-ivy-bqwaqd?file=src/app/app.component.html

Is there a way we delete specific FormArray withou changing the initial index of active FormArray? For example, formGoupname were 0,1,2,3 when we delete 2 it should be 0,1,3 instead of 0,1,2

@jotatoledo https://stackblitz.com/edit/angular-l4v8pr

reproduction steps are inside demo. Don’t know if it is my own stupidity? I had expected track trackby index would give Angular all it needed to track the objects and manage the subscriptions properly (?)