Search code examples
angulartypescriptangular4-forms

How to unsubscribe from valueChanges in Angular 4 reactive forms?


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.


Solution

  • 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();
    }