When dealing with forms in angular you commonly have inside your component a formGroup representing your form. You may want to listen for changes to a specific form field, and would subscribe to the field’s valueChanges observable from the formGroup. The subscription to the form field changes is usually performed at the initialization of the component, often in the ngOnInit lifecycle hook.
@Component({
...
})
export class MyComponent {
formGroup: FormGroup;
ngOnInit() {
this.formGroup = new FormGroup({
firstName: new FormControl('', [Validators.required])
});
this.formGroup.get('firstName').valueChanges.subscribe( ....
}
}
Following Angular best practices, it is recommended to unsubscribe from long-lived observables in the ngOnDestroy lifecycle hook. The following code adds the unsubscription to the valueChanges.
@Component({
...
})
export class MyComponent {
formGroup: FormGroup;
private destroy$ = new Subject<void>();
ngOnInit() {
this.formGroup = new FormGroup({
firstName: new FormControl('', [Validators.required])
});
this.formGroup.get('firstName').valueChanges.pipe(takeUntil(this.destroy$)).subscribe( ....
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
However looking closely, is it really necessary to unsubscribe in this case ?
In this particular case, the valueChanges subscription is created when the FormGroup is initialized within the component and remains active as long as the formGroup and the component exist. Once the component is destroyed and the FormGroup is no longer needed, the valueChanges subscription is no longer active and no more value will be emitted. Ultimately, the garbage collector will take care of cleaning it up.
That being said I still suggest implementing the unsubscription using the takeUntil operator. By doing so, we enforce the best practices for unsubscribing from observables in our codebase.