Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 405
starlight Avatar asked Nov 13 '17 10:11

starlight


People also ask

Do I need to unsubscribe from form Valuechanges?

You must unsubscribe to prevent memory leaks and to avoid unexpected side-effects in your application.

When should we use reactive forms in angular?

2. Predictability. Reactive form is predictable because it access synchronously to the data model. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed in a synchronous way.

What is meant by reactive form in angular?

Reactive forms are a form of dynamic form validation, where inputs and values are provided as streams of input values that can be accessed synchronously. Reactive forms make it easy to test because you are assured that your data is consistent and predictable.


3 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();
}
like image 190
Suren Srapyan Avatar answered Nov 11 '22 03:11

Suren Srapyan


@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();
    })
}
like image 45
Venomy Avatar answered Nov 11 '22 01:11

Venomy


I created Subscription disposer class

import { OnDestroy } from '@angular/core';
import { Subject } from 'rxjs/Subject';

export class SubscriptionDisposer implements OnDestroy {
  protected ngUnsubscribe: Subject<void> = new Subject<void>();
  constructor() {
  }
   ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}

then you need to extend your component class by SubscriptionDisposer Your code will look like

this.searchForm.valueChanges
.takeUntil(this.ngUnsubscribe)
.subscribe((value) => {
   console.log(value);
});
like image 22
Vitalii Polulikh Avatar answered Nov 11 '22 03:11

Vitalii Polulikh