Angular Form value changes subscription destroys automatically, when form control is removed?

264 Views Asked by At

I have a Form Array (generated based on Array of JSON response), where form controls are added/removed dynamically (for each object form control added to form array). I have a scenario like there can be 2 dependent fields, So I have subscribed to valueChanges. My question is, do I need to manually unsubscribe it or will it be unsubscribed automatically when I remove that form control/group from form array?

1

There are 1 best solutions below

0
maxime1992 On

When in doubt, try it out.

export class App {
  f = new FormArray<any>([]);

  constructor() {
    this.f.push(new FormControl(null));

    const sub = this.f.controls[0].valueChanges
      .pipe(finalize(() => console.log('subscription ended!')))
      .subscribe();

    this.f.removeAt(0);
  }
}

You'll see that the finalize is never triggered, meaning that your subscription is still active.

Now, if you add sub.unsubscribe(); before the line with removeAt, you'll see that the finalize is triggered, meaning that the subscription is closed as expected.

Here's a live demo.