What is the purpose of ngOnDestroy in Angular?
๐ก Concept Name
ngOnDestroy is a lifecycle hook in Angular used to perform cleanup operations like unsubscribing from observables, detaching event handlers, or clearing timers before a component or directive is destroyed.
๐ Quick Intro
When a component is removed from the DOM, Angular calls ngOnDestroy()
. It's your chance to clean up memory-leaking resources like subscriptions, custom services, or any ongoing tasks the component started.
๐ง Analogy / Short Story
Imagine finishing a camping trip. Before leaving, you put out the fire, pack your tent, and dispose of trash. Similarly, ngOnDestroy
ensures you clean up everything before a component leaves.
๐ง Technical Explanation
- ๐น Called right before Angular destroys the component or directive instance.
- ๐น Used for unsubscribing from RxJS subscriptions.
- ๐น Clears timers or intervals to prevent leaks.
- ๐น Detaches event listeners or removes DOM nodes manually added.
- ๐น Helps avoid memory leaks in long-running SPAs.
๐ฏ Purpose & Use Case
- โ Cleanup subscriptions from observables.
- โ Remove global event listeners (e.g., window resize).
- โ Stop background timers or intervals.
- โ Clear dynamically created DOM elements.
๐ป Real Code Example
import { Component, OnDestroy } from '@angular/core';
import { Subscription, interval } from 'rxjs';
@Component({
selector: 'app-timer',
template: '<p>Check the console for timer output</p>'
})
export class TimerComponent implements OnDestroy {
private subscription: Subscription;
constructor() {
this.subscription = interval(1000).subscribe(val => console.log('Tick:', val));
}
ngOnDestroy() {
console.log('Component destroyed. Cleaning up...');
this.subscription.unsubscribe();
}
}

โ Interview Q&A
Q1: What does ngOnDestroy do?
A: It performs cleanup operations before a component is destroyed.
Q2: Why is it important to unsubscribe in ngOnDestroy?
A: To avoid memory leaks and ensure efficient resource use.
Q3: Can you access component properties in ngOnDestroy?
A: Yes, you can access instance variables for cleanup.
Q4: Is ngOnDestroy called automatically?
A: Yes, by Angular when the component is destroyed.
Q5: What happens if you forget to unsubscribe?
A: Observables continue running and may cause memory leaks.
๐ก Bonus Insight
For managing multiple subscriptions, use a Subject
with takeUntil()
in combination with ngOnDestroy
for a cleaner teardown pattern in Angular components.
๐ PDF Download
Need a handy summary for your notes? Download this topic as a PDF!