Issue
this.typeCtrl.valueChanges.subscribe((value) => {
if (value === 'new') {
this.percent = '20';
} else {
this.percent = '10';
}
});
I have a subscribe with a valuechange of a formControl, should I unsubscribe or the form does it by default?
Solution
As said on comments by R. Richards, you should always unsubscribe everything before destroying some instance.
You mentioned there was no way to unsubscribe an AbstractControl and really that is not possible. To unsubscribe you need to save the reference when you subscribe.
I would recommend you have an array of subscriptions that you iterate over when destroying the instance unsubscribing everything. Following your example, it would look like this:
subscriptions = [];
...
const typeCtrlSubscription = this.typeCtrl.valueChanges.subscribe((value) => {
if (value === 'new') {
this.percent = '20';
} else {
this.percent = '10';
}
});
this.subscriptions.push(typeCtrlSubscription);
...
ngOnDestroy(): void {
this.subscriptions.forEach((subscription) => subscription.unsubscribe());
}
Answered By – Guilherme Afonso
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0