You manage component lifecycle hooks—especially ngOnDestroy()—to perform resource cleanup such as:
Unsubscribing from observables
Clearing intervals/timeouts
Detaching event listeners
Releasing memory-heavy objects
Best Lifecycle Hook for Cleanup: ngOnDestroy()
Example: Unsubscribing from a Subscription
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-example',
template: `...`
})
export class ExampleComponent implements OnDestroy {
private dataSubscription: Subscription;
constructor(private dataService: SomeService) {
this.dataSubscription = this.dataService.getData()
.subscribe(data => console.log(data));
}
ngOnDestroy() {
if (this.dataSubscription) {
this.dataSubscription.unsubscribe();
}
console.log('Component destroyed and resources cleaned up.');
}
}