Angular OnDestroy
Angular @OnDestroy is a lifecycle hook used to perform cleanup work just before a component or directive is destroyed.
What is @OnDestroy?
The ngOnDestroy() lifecycle hook is called once just before Angular destroys a component, directive, or service instance that is no longer required.
It is commonly used to clean up subscriptions, timers, event listeners, resources, and other ongoing activities.
Simple Definition
ngOnDestroy() is the place where cleanup logic is performed before a component is removed from the UI.
Where @OnDestroy Fits in Angular Lifecycle
Basic Syntax
To use this lifecycle hook, implement the OnDestroy interface and define the ngOnDestroy() method.
import { Component, OnDestroy } from '@angular/core';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html'
})
export class DashboardComponent implements OnDestroy {
ngOnDestroy(): void {
console.log('Component destroyed');
}
}
Important
Angular automatically calls ngOnDestroy() before destroying the component.
Why Use @OnDestroy?
Clear Timers
Stop intervals or timeouts created by the component.
clearInterval()
Unsubscribe
Clean up active subscriptions when required.
unsubscribe()
Remove Events
Remove manually registered event listeners.
removeEventListener()
Release Resources
Release resources created during component execution.
cleanup()
1. Simple OnDestroy Example
The following example shows a cleanup message when the component is about to be destroyed.
import { Component, OnDestroy } from '@angular/core';
@Component({
selector: 'app-course',
templateUrl: './course.component.html'
})
export class CourseComponent implements OnDestroy {
ngOnDestroy(): void {
console.log(
'Course component is being destroyed'
);
}
}
How it works
When Angular removes the course component from the view, ngOnDestroy() is automatically executed.
2. Cleaning Up a Timer
If a component creates a timer, the timer should be cleared when the component is destroyed.
import { Component, OnDestroy } from '@angular/core';
@Component({
selector: 'app-clock',
templateUrl: './clock.component.html'
})
export class ClockComponent implements OnDestroy {
timerId: any;
constructor() {
this.timerId = setInterval(() => {
console.log('Timer running...');
}, 1000);
}
ngOnDestroy(): void {
clearInterval(this.timerId);
console.log('Timer cleared');
}
}
While the component is active: Timer running...
Before the component is removed: Timer cleared
3. Cleaning Up a Subscription
A component may subscribe to an Observable. The subscription can be cleaned up when the component is destroyed.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html'
})
export class CourseListComponent
implements OnInit, OnDestroy {
courseSubscription!: Subscription;
ngOnInit(): void {
this.courseSubscription =
this.courseService.getCourses()
.subscribe(data => {
console.log(data);
});
}
ngOnDestroy(): void {
this.courseSubscription?.unsubscribe();
console.log(
'Course subscription cleaned up'
);
}
}
Important Point
Cleanup is important when a subscription or other ongoing resource should no longer remain active after the component leaves the UI.
4. Removing Event Listeners
When an event listener is manually registered, it should also be removed when the component is destroyed.
export class DashboardComponent
implements OnInit, OnDestroy {
handleResize = () => {
console.log(window.innerWidth);
};
ngOnInit(): void {
window.addEventListener(
'resize',
this.handleResize
);
}
ngOnDestroy(): void {
window.removeEventListener(
'resize',
this.handleResize
);
}
}
5. OnDestroy with Conditional Rendering
A component can be created and destroyed depending on application state. The OnDestroy hook runs when Angular removes the component.
<app-course
*ngIf="showCourse">
</app-course>
<button (click)="showCourse = !showCourse">
Toggle Course
</button>
showCourse = true;
How it works
When showCourse becomes false, Angular removes the component and calls its ngOnDestroy() method.
6. Using OnInit and OnDestroy Together
A common pattern is to start a resource in ngOnInit() and clean it up in ngOnDestroy().
timerId: any;
ngOnInit(): void {
this.timerId = setInterval(() => {
console.log('Working...');
}, 1000);
}
ngOnDestroy(): void {
clearInterval(this.timerId);
console.log('Cleanup completed');
}
@OnInit vs @OnDestroy
| ngOnInit() | ngOnDestroy() |
|---|---|
| Used for component initialization. | Used for component cleanup. |
| Runs during component initialization. | Runs before component destruction. |
| Can start timers, subscriptions, or data loading. | Can stop timers and clean up subscriptions. |
| Prepares resources for component execution. | Releases resources no longer required. |
Complete CIIT Training Institute Example
Suppose CIIT Training Institute has a live course dashboard. When the dashboard opens, it starts a timer. When the dashboard is closed or removed, the timer should be cleared using ngOnDestroy().
import {
Component,
OnInit,
OnDestroy
} from '@angular/core';
@Component({
selector: 'app-live-dashboard',
templateUrl: './live-dashboard.component.html'
})
export class LiveDashboardComponent
implements OnInit, OnDestroy {
timerId: any;
status = '';
ngOnInit(): void {
this.status =
'Live Dashboard Active';
this.timerId = setInterval(() => {
console.log(
'Checking live training status...'
);
}, 5000);
}
ngOnDestroy(): void {
clearInterval(this.timerId);
console.log(
'Live Dashboard Cleanup Completed'
);
}
}
<div>
<h2>
CIIT Training Institute
</h2>
<p>
{{ status }}
</p>
</div>
CIIT Training Institute
Live Dashboard Active
When the component is destroyed, the timer is cleared automatically through ngOnDestroy().
Important Points About @OnDestroy
- ngOnDestroy() is called before Angular destroys a component.
- It is mainly used for cleanup operations.
- Timers can be stopped during component destruction.
- Subscriptions can be cleaned up when they are no longer needed.
- Manually registered event listeners should be removed.
- Cleanup helps prevent unnecessary ongoing work after a component is removed.
@OnDestroy Best Practices
- Keep cleanup logic inside ngOnDestroy().
- Clear timers created by the component.
- Clean up subscriptions when required.
- Remove manually attached browser event listeners.
- Release resources that are no longer required.
- Keep cleanup code simple and easy to maintain.
Summary
Angular @OnDestroy provides the ngOnDestroy() lifecycle method for performing cleanup work before a component or directive is destroyed.
It is commonly used to clear timers, clean up subscriptions, remove event listeners, and release resources created while the component was active.