How to unsubscribe from valueChanges in Angular 4 reactive forms?

Viewed 8258

I am making a reactive form in Angular 4 and looking for valueChanges in the form like below:

this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
});

The above code works perfectly. But how to unsubscribe from the valueChanges on ngOnDestroy() as this.searchForm.valueChanges.unsubscribe() doesn't seem to work. Please help me solve this.

4 Answers

subscribe returns an object of type Subscription from which you can unsubscribe

this.subscription = this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
});

...

ngOnDestroy() {
   this.subscription.unsubscribe();
}

@Suren has the right answer, I would just like to add some code I use when I have many subscriptions.

...
this.subscriptions.push(this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
}));
...

private subscriptions: Subscription[] = [];

ngOnDestroy(): void {
    this.subscriptions.forEach((sub) => {
        sub.unsubscribe();
    })
}

This post has the right solution. In a few cases is not working because there could be multiple subscriptions.

You have to check all subscriptions and ensure that you are unsubscribing from all of them.

Related