What does ngOnDestroy() do? When is it called?
In Angular, ngOnDestroy() is a lifecycle hook that is called before a component or directive is destroyed.
Key points
- What it does:
- Lets you clean up resources created by the component: timers, subscriptions to events (
Observable), DOM handlers, third-party libraries. - Prevents memory leaks and unexpected errors after the component is removed.
- When it is called:
- Once, before the component is removed from the DOM.
- After all view checks and updates (
AfterViewChecked) are complete.
Example:
ts
export class MyComponent implements OnDestroy {
subscription: Subscription;
ngOnInit() {
this.subscription = this.dataService.getData().subscribe();
}
ngOnDestroy() {
this.subscription.unsubscribe(); // clean up the subscription
console.log('Component destroyed');
}
}In other words, ngOnDestroy is a hook for wrapping up the component's work and releasing all resources before it is removed from the DOM.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.