ngOnDestroy helps you clean up when a component or directive is removed. It stops memory leaks and unwanted tasks.
ngOnDestroy for cleanup in Angular
import { OnDestroy } from '@angular/core'; export class MyComponent implements OnDestroy { ngOnDestroy() { // cleanup code here } }
ngOnDestroy is a lifecycle method Angular calls automatically before destroying the component.
Implement the OnDestroy interface to get type checking and clarity.
import { OnDestroy } from '@angular/core'; export class TimerComponent implements OnDestroy { intervalId: any; startTimer() { this.intervalId = setInterval(() => { console.log('Tick'); }, 1000); } ngOnDestroy() { clearInterval(this.intervalId); } }
import { OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; export class DataComponent implements OnDestroy { dataSub: Subscription; ngOnInit() { this.dataSub = someObservable.subscribe(data => { console.log(data); }); } ngOnDestroy() { this.dataSub.unsubscribe(); } }
This component starts a timer that logs a message every second. When the component is destroyed, ngOnDestroy stops the timer and logs a final message.
import { Component, OnDestroy } from '@angular/core'; @Component({ selector: 'app-cleanup-example', template: `<p>Check the console for timer messages.</p>` }) export class CleanupExampleComponent implements OnDestroy { intervalId: any; constructor() { this.intervalId = setInterval(() => { console.log('Timer running...'); }, 1000); } ngOnDestroy() { clearInterval(this.intervalId); console.log('Timer stopped on destroy'); } }
Always clean up subscriptions and timers in ngOnDestroy to keep your app fast and bug-free.
If you forget cleanup, your app might slow down or behave strangely over time.
ngOnDestroy runs cleanup code when a component or directive is removed.
Use it to stop timers, unsubscribe from observables, and remove event listeners.
This helps prevent memory leaks and keeps your app healthy.
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
