Angular › Lifecycle Hooks
What does ngOnDestroy do, and why is it important for cleaning up resources like subscriptions?
IntermediateAnswer
ngOnDestroy runs right before Angular removes a component from the page, giving you a chance to clean up anything that would otherwise keep running unnecessarily, such as unsubscribing from an observable or clearing a timer, preventing memory leaks in a long running application.
import { OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
export class TimerComponent implements OnDestroy {
private subscription: Subscription;
constructor() {
this.subscription = interval(1000).subscribe(() => console.log('tick'));
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}Real-world example A live clock component correctly stops its timer when the user navigates away from the page, because it unsubscribes inside ngOnDestroy, avoiding a hidden timer that keeps running forever in the background.