0Pricing
Angular Academy · Lesson

ngOnDestroy and Cleanup

Release resources when a component is removed.

ngOnDestroy and Cleanup is a free Angular Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Angular Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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");
  }
}

Unsubscribing from Observables

Manual subscriptions must be unsubscribed to avoid leaks. Store the Subscription and call unsubscribe in ngOnDestroy.

private sub!: Subscription;

ngOnInit() {
  this.sub = this.timer$.subscribe(t => this.tick = t);
}

ngOnDestroy() {
  this.sub.unsubscribe();
}

Managing Multiple Subscriptions

You can collect subscriptions in a single parent Subscription and unsubscribe all at once.

private subs = new Subscription();

ngOnInit() {
  this.subs.add(this.a$.subscribe());
  this.subs.add(this.b$.subscribe());
}

ngOnDestroy() {
  this.subs.unsubscribe();
}

The takeUntil Pattern

A popular RxJS pattern uses a destroy Subject with takeUntil so streams complete automatically when the component dies.

private destroy$ = new Subject<void>();

ngOnInit() {
  this.data$.pipe(takeUntil(this.destroy$))
    .subscribe(d => this.data = d);
}

ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}

Using takeUntilDestroyed

Modern Angular offers takeUntilDestroyed from @angular/core/rxjs-interop, which ties a stream to the component lifecycle without manual cleanup.

import { takeUntilDestroyed } from "@angular/core/rxjs-interop";

constructor() {
  this.data$.pipe(takeUntilDestroyed())
    .subscribe(d => this.data = d);
}

The async Pipe Alternative

Using the async pipe in the template avoids manual subscriptions entirely, since it unsubscribes automatically on destroy.

<p>{{ data$ | async }}</p>

Clearing Timers and Intervals

Native timers are not managed by Angular. Clear them in ngOnDestroy to stop callbacks firing after destruction.

private id!: number;

ngOnInit() {
  this.id = window.setInterval(() => this.tick(), 1000);
}

ngOnDestroy() {
  clearInterval(this.id);
}

Removing Event Listeners

If you add DOM listeners manually, remove them on destroy to prevent leaks and stale handlers.

private onScroll = () => this.handle();

ngOnInit() {
  window.addEventListener("scroll", this.onScroll);
}

ngOnDestroy() {
  window.removeEventListener("scroll", this.onScroll);
}

DestroyRef for Callbacks

You can inject DestroyRef and register an onDestroy callback, useful in services or non-component contexts.

constructor(private destroyRef: DestroyRef) {
  const id = setInterval(() => {}, 1000);
  this.destroyRef.onDestroy(() => clearInterval(id));
}

What Triggers ngOnDestroy

ngOnDestroy runs when a component is removed by routing, a structural directive like *ngIf, or when its parent is destroyed.

Quick Check

Test your understanding of OnDestroy.

Recap

The OnDestroy hook cleans up subscriptions, timers, and listeners. Use unsubscribe, the takeUntil pattern, takeUntilDestroyed, the async pipe, or DestroyRef to prevent memory leaks.

Frequently asked questions

Is the “ngOnDestroy and Cleanup” lesson free?

Yes — the full text of “ngOnDestroy and Cleanup” is free to read here on the web, and the Angular Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Angular Academy course, upgrade to CoddyKit PRO.

What will I learn in “ngOnDestroy and Cleanup”?

Release resources when a component is removed. You practise Angular Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Angular Academy?

No prior experience is required. Angular Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “ngOnDestroy and Cleanup” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Angular Academy lesson?

Yes. Every Angular Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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