Performance: ngOnDestroy for cleanup
This affects the interaction responsiveness and memory usage by properly cleaning up resources when components are destroyed.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-example', template: '' }) export class ExampleComponent implements OnDestroy { subscription: Subscription = someObservable.subscribe(); timerId = setInterval(() => console.log('tick'), 1000); ngOnDestroy() { this.subscription.unsubscribe(); clearInterval(this.timerId); } }
import { Component } from '@angular/core'; @Component({ selector: 'app-example', template: '' }) export class ExampleComponent { subscription = someObservable.subscribe(); timerId = setInterval(() => console.log('tick'), 1000); // No ngOnDestroy implemented }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No cleanup in ngOnDestroy | No direct DOM ops but leaves event listeners active | Triggers extra reflows indirectly due to background tasks | Increases paint cost due to unnecessary JS work | [X] Bad |
| Proper cleanup in ngOnDestroy | Removes event listeners and timers | No extra reflows triggered | Minimal paint cost, efficient rendering | [OK] Good |
ngOnDestroy lifecycle hook in Angular?ngOnDestroy hook is called when Angular removes a component or directive from the view.ngOnDestroy in an Angular component?ngOnDestroy().ngOnDestroy.export class TimerComponent implements OnDestroy {
intervalId = setInterval(() => console.log('tick'), 1000);
ngOnDestroy() {
clearInterval(this.intervalId);
console.log('Timer stopped');
}
}ngOnDestroy, which clears the interval timer.export class DataComponent implements OnDestroy {
subscription = this.dataService.getData().subscribe();
ngOnDestroy() {
this.subscription.unsubscribe;
}
}this.subscription.unsubscribe; without parentheses, so the method is not actually called.this.subscription.unsubscribe(); to properly stop the subscription and avoid memory leaks.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?
}
}ngOnDestroy?removeEventListener.Pass the test and this pattern moves unknown