Angular Academy · Lesson

ngOnDestroy and Cleanup

Release resources when a component is removed.

Lesson 3 of 413 steps

ngOnDestroy and Cleanup is a free Angular Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Angular Academy learning path, and your progress syncs across the web and the CoddyKit app. The Angular Academy course includes 4 lessons in total.

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.

Free to start

Learn HTML with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
38
Lessons
144

Frequently Asked Questions

Is the “ngOnDestroy and Cleanup” lesson free?

Yes — any 3 lessons of the Angular Academy learning path, including “ngOnDestroy and Cleanup”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Angular Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

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