ngOnDestroy and Cleanup
Release resources when a component is removed.
Why Cleanup Matters
When a component is removed from the DOM, any lingering subscriptions, timers, or event listeners can cause memory leaks. The OnDestroy hook is where you clean them up.
Implementing OnDestroy
Implement OnDestroy and add a ngOnDestroy method. Angular calls it just before the component is destroyed.
import { Component, OnDestroy } from "@angular/core";
@Component({ selector: "app-demo", template: "" })
export class DemoComponent implements OnDestroy {
ngOnDestroy(): void {
console.log("cleaning up");
}
}All lessons in this course
- ngOnInit and Initialization
- ngOnChanges and Input Changes
- ngOnDestroy and Cleanup
- AfterView and AfterContent Hooks