DestroyRef

Lets you register cleanup callbacks tied to an injectable's destruction.

Since Angular 16+ Spec ↗

Syntax

const ref = inject(DestroyRef); ref.onDestroy(fn)

Parameters

NameTypeRequiredDescription
callback () => void No Function run when the enclosing scope is destroyed.

Returns

() => void — An unregister function for the callback.

Examples

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

@Component({ selector: 'app-x', standalone: true, template: '' })
export class XComponent {
  constructor() {
    const destroyRef = inject(DestroyRef);
    const id = setInterval(() => {}, 1000);
    destroyRef.onDestroy(() => clearInterval(id));
  }
}

Notes

DestroyRef provides a hook to clean up resources without implementing OnDestroy, useful inside services, functions, or constructors. It also powers takeUntilDestroyed for automatic RxJS unsubscription.