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.
You must unsubscribe to prevent memory leaks and to avoid unexpected side-effects in your application.
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.
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.
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();
})
}
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With