What if your app could clean up its mess all by itself when you leave a page?
Why ngOnDestroy for cleanup in Angular? - Purpose & Use Cases
Imagine you create a component that listens to user actions or data streams. When you leave that component, you forget to stop those listeners or subscriptions.
Without proper cleanup, your app keeps running old listeners in the background. This wastes memory, slows down your app, and can cause strange bugs that are hard to find.
Angular's ngOnDestroy lets you run cleanup code automatically when a component is removed. This stops listeners and frees resources, keeping your app fast and bug-free.
componentDidLeave() { /* forgot to unsubscribe from data stream */ }ngOnDestroy() { this.subscription.unsubscribe(); }You can build smooth, efficient apps that clean up after themselves without extra effort.
Think of a chat app where each chat window listens for new messages. When you close a chat, ngOnDestroy stops the message listener so your app stays quick and responsive.
Manual cleanup is easy to forget and causes bugs.
ngOnDestroy runs cleanup code automatically.
This keeps your Angular app fast and reliable.
Practice
ngOnDestroy lifecycle hook in Angular?Solution
Step 1: Understand the role of ngOnDestroy
ThengOnDestroyhook is called when Angular removes a component or directive from the view.Step 2: Identify its main use
It is used to clean up resources like timers, subscriptions, or event listeners to avoid memory leaks.Final Answer:
To run cleanup code when a component or directive is removed -> Option CQuick Check:
ngOnDestroy = cleanup [OK]
- Confusing ngOnDestroy with ngOnInit
- Thinking it initializes data
- Assuming it handles user events
ngOnDestroy in an Angular component?Solution
Step 1: Recall Angular lifecycle hook syntax
Angular lifecycle hooks are methods inside the component class with exact names likengOnDestroy().Step 2: Check method declaration style
The correct syntax is a method, not an arrow function or standalone function, and must be named exactlyngOnDestroy.Final Answer:
ngOnDestroy() { console.log('Component destroyed'); } -> Option DQuick Check:
ngOnDestroy method syntax = ngOnDestroy() { console.log('Component destroyed'); } [OK]
- Using arrow functions for lifecycle hooks
- Naming method incorrectly
- Defining lifecycle hook outside class
export class TimerComponent implements OnDestroy {
intervalId = setInterval(() => console.log('tick'), 1000);
ngOnDestroy() {
clearInterval(this.intervalId);
console.log('Timer stopped');
}
}What will happen when this component is removed from the view?
Solution
Step 1: Understand what ngOnDestroy does here
When the component is removed, Angular callsngOnDestroy, which clears the interval timer.Step 2: Effect of clearing the interval
Clearing the interval stops the repeated 'tick' logs, and the message 'Timer stopped' is logged once.Final Answer:
The interval stops and logs 'Timer stopped' once -> Option AQuick Check:
ngOnDestroy clears timer = The interval stops and logs 'Timer stopped' once [OK]
- Thinking interval keeps running after destroy
- Assuming ngOnDestroy is not called
- Confusing clearInterval usage
export class DataComponent implements OnDestroy {
subscription = this.dataService.getData().subscribe();
ngOnDestroy() {
this.subscription.unsubscribe;
}
}What is the problem with this code?
Solution
Step 1: Check how unsubscribe is used
The code usesthis.subscription.unsubscribe;without parentheses, so the method is not actually called.Step 2: Correct usage of unsubscribe
It should bethis.subscription.unsubscribe();to properly stop the subscription and avoid memory leaks.Final Answer:
The unsubscribe method is not called correctly -> Option AQuick Check:
Call unsubscribe() with parentheses [OK]
- Forgetting parentheses on unsubscribe
- Assuming unsubscribe is a property
- Ignoring ngOnDestroy lifecycle
export class MultiCleanupComponent implements OnDestroy {
sub1 = this.service1.getData().subscribe();
sub2 = this.service2.getData().subscribe();
constructor() {
window.addEventListener('resize', this.onResize);
}
onResize() {
console.log('Window resized');
}
ngOnDestroy() {
// What should be done here?
}
}Which is the best way to clean up all resources in
ngOnDestroy?Solution
Step 1: Identify all resources to clean
The component has two subscriptions and an event listener on the window.Step 2: Proper cleanup in ngOnDestroy
To avoid memory leaks, unsubscribe both subscriptions and remove the event listener usingremoveEventListener.Final Answer:
Call this.sub1.unsubscribe(); this.sub2.unsubscribe(); window.removeEventListener('resize', this.onResize); -> Option BQuick Check:
Unsubscribe and remove listeners in ngOnDestroy [OK]
- Forgetting to remove event listeners
- Only unsubscribing some observables
- Assuming Angular cleans up automatically
Ready to prove it?
Pass the test and this pattern moves unknown
