Back to all posts

ngOnDestroy and DestroyRef in Angular


both ngOnDestroy and DestroyRef serve the purpose of executing cleanup logic before an Angular component or destroyed, but they do so in different ways.

Key Differences

  1. Implementation:
    • ngOnDestroy: This is a lifecycle hook method that be implemented in a component or directive class. it requires you to manully handle cleanup tasks, such as unsubscribing from observables.
    • DestroyRef: Introduced in Angular 16, this is an injectable class that allow you to register cleanup callbacks using the onDestory method. This can be done anywhere within the component’s context, not just in a specific lifecycle method.
  2. Flexibility:
    • ngOnDestroy: Tied to the component lifecycle, making it less flexible for reusable logic across different components.
    • DestroyRef: Offers greater flexibility as it can be injected and used to create reusable cleanup functions that can be shared across multiple components.
  3. Execution Order:
    • If both are used in the same component, ngOnDestroy will execute before any callbacks registered with DestroyRef.onDestroy().

Example Comparison

Using ngOnDestroy:

ngOnDestroy() {
    clearInterval(this.interval); // Cleanup logic
}

Using DestroyRef:

constructor(destroyRef: DestroyRef) {
    destroyRef.onDestroy(() => {
        clearInterval(this.interval); // Cleanup logic
    });
}