0Pricing
Angular Academy · Lesson

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

  1. ngOnInit and Initialization
  2. ngOnChanges and Input Changes
  3. ngOnDestroy and Cleanup
  4. AfterView and AfterContent Hooks
← Back to Angular Academy