How to Use ngOnDestroy in Angular
The ngOnDestroy lifecycle hook in Angular is essential for cleaning up resources when components are destroyed to prevent memory leaks and ensure optimal application performance. As the creator of CoreUI with over 11 years of Angular development experience, I implement ngOnDestroy in every component that has subscriptions, timers, or event listeners. This hook is called just before Angular destroys the component, making it the perfect place for cleanup operations.
Implement the OnDestroy interface and ngOnDestroy method to clean up subscriptions, timers, and event listeners before component destruction.
import { Component, OnInit, OnDestroy } from '@angular/core'
import { Subscription, interval } from 'rxjs'
import { DataService } from './data.service'
@Component({
selector: 'app-user-dashboard',
template: `
<div>
<h2>{{ title }}</h2>
<p>Data updates: {{ updateCount }}</p>
<div *ngFor="let item of data">{{ item.name }}</div>
</div>
`
})
export class UserDashboardComponent implements OnInit, OnDestroy {
title = 'User Dashboard'
data: any[] = []
updateCount = 0
private subscriptions = new Subscription()
private intervalId: number
constructor(private dataService: DataService) {}
ngOnInit(): void {
// Subscribe to data updates
const dataSub = this.dataService.getData().subscribe(data => {
this.data = data
})
this.subscriptions.add(dataSub)
// Set up polling
const pollingSub = interval(5000).subscribe(() => {
this.updateCount++
this.dataService.refreshData()
})
this.subscriptions.add(pollingSub)
// Set up timer
this.intervalId = window.setInterval(() => {
console.log('Component is active')
}, 10000)
// Add global event listener
window.addEventListener('resize', this.handleResize)
}
ngOnDestroy(): void {
// Unsubscribe from all observables
this.subscriptions.unsubscribe()
// Clear timers
if (this.intervalId) {
clearInterval(this.intervalId)
}
// Remove global event listeners
window.removeEventListener('resize', this.handleResize)
console.log('Component cleanup completed')
}
private handleResize = (): void => {
console.log('Window resized')
}
}
The ngOnDestroy method is called automatically when Angular removes the component from the DOM. Always implement the OnDestroy interface for type safety. Use a single Subscription instance to collect multiple subscriptions and unsubscribe from all at once. Clear any timers created with setTimeout or setInterval. Remove global event listeners added to window or document. This cleanup prevents memory leaks, especially important in single-page applications where components are frequently created and destroyed.
Best Practice Note:
In CoreUI components, we religiously implement ngOnDestroy for every component with external resources. This practice ensures our enterprise-grade components remain performant even in large applications with hundreds of component instances, preventing the memory leaks that can degrade user experience over time.



