← Back to Angular, page 7

angular-0121 · Medium mid

What is DestroyRef, and how does it improve cleanup compared with ngOnDestroy?

DestroyRef is an injectable that lets any code register a callback to run when its context (component, directive, service or injector) is destroyed. It allows cleanup to be written next to the setup, in functions and utilities, without a class implementing ngOnDestroy.

Full answer

Before Angular 16, cleanup needed a class with ngOnDestroy. That forced setup code and teardown code to live in two places, and a reusable function could not clean up after itself.

DestroyRef solves this. You inject it, and call onDestroy(callback). The callback runs when the owner is destroyed. The method returns a function that unregisters the callback if you need to cancel it earlier.

What can provide a DestroyRef:

  • A component or directive: destroyed when the view is removed.
  • A service: destroyed with its injector (root services when the app is destroyed, component-level services with the component).
  • An environment injector, such as a route's injector.

Why it is better:

  1. Colocation: register the listener and its removal in the same function.
  2. Reusable helpers: a function like onWindowResize(callback) can inject DestroyRef and clean up on its own. Any component that calls it gets cleanup for free.
  3. Works in plain functions called from an injection context, without a base class.
  4. It powers takeUntilDestroyed(), toSignal, effects, and afterNextRender.

Rules:

  • inject(DestroyRef) needs an injection context (constructor, field initialiser, factory). Pass the ref along if you call a helper later, for example from an event handler.
  • If you need to know in a callback whether the owner is already destroyed, check destroyRef.destroyed (available in recent versions).
  • The order in which several callbacks run is not part of the documented behaviour, so do not depend on it.
  • ngOnDestroy still works. It is fine for classes that already use it, and you can mix both.

Use it for event listeners, intervals, observers (ResizeObserver, IntersectionObserver), WebSocket connections, and any manual subscription.

typescript
import { Component, DestroyRef, inject, signal } from '@angular/core';

export const listeners = { active: 0 };

// A reusable helper: setup and cleanup in one place, no class needed.
export function onWindowResize(callback: (width: number) => void): void {
  const destroyRef = inject(DestroyRef);
  const handler = () => callback(window.innerWidth);
  window.addEventListener('resize', handler);
  listeners.active++;

  destroyRef.onDestroy(() => {
    window.removeEventListener('resize', handler);
    listeners.active--;
  });
}

@Component({
  selector: 'app-width',
  template: `Width: {{ width() }}`,
})
export class WidthComponent {
  readonly width = signal(window.innerWidth);

  constructor() {
    onWindowResize((w) => this.width.set(w));
  }
}

Angular 20.3, type-checked. A Karma test checks that the resize listener is removed when the component is destroyed.

Key points

  • `DestroyRef.onDestroy(cb)` runs `cb` when the owner is destroyed. It returns an unregister function.
  • Works for components, directives, services and injectors.
  • Enables reusable cleanup helpers and powers `takeUntilDestroyed`.
  • Needs an injection context to inject. Do not rely on callback order.

Common mistakes

  • Calling `inject(DestroyRef)` inside an event handler, outside an injection context.
  • Registering a callback and forgetting that it may run after the work is already finished.
  • Depending on the order of several callbacks.

Follow-ups

  • How does `takeUntilDestroyed` use `DestroyRef`?
  • What is destroyed when a route is left?
  • How would you write a helper that listens to window resize?

Tips

  • Show a helper function that cleans itself up. It is the real benefit.
  • Mention the unregister function.
  • Say that `ngOnDestroy` still works.

Evaluation rubric

  • Explains what DestroyRef is and who provides it.
  • Gives benefits over ngOnDestroy.
  • Mentions injection context rules.