Sub topic 10
Modern cleanup with DestroyRef and takeUntilDestroyed
This chapter assumes you know how to write a standalone Angular component, how ngOnInit and ngOnDestroy work, and how to subscribe to an RxJS observable. You should also know what the inject() function does. The previous chapter showed the classic pattern of storing a Subscription and unsubscribing in ngOnDestroy. This chapter covers the newer tools that do the same job with less code and fewer ways to forget a step.
Why the classic pattern is easy to get wrong
The classic cleanup pattern needs three separate pieces: a field to hold the subscription, the subscribe call, and an ngOnDestroy method that unsubscribes. Each piece is a place for a mistake. A common one is adding a second subscription and forgetting to unsubscribe from it. Another is calling unsubscribe() on a field that was never assigned.
Angular gives you two tools to remove this bookkeeping:
DestroyRefis an injectable object that represents the lifetime of the thing it was injected into. You register callbacks on it, and Angular runs them when that thing is destroyed.takeUntilDestroyedis an RxJS operator in@angular/core/rxjs-interop. It completes an observable when aDestroyRefis destroyed.
DestroyRef
DestroyRef is provided by Angular for components, directives, pipes, services, and environment injectors. When you inject it, you get the reference that belongs to the current context. In a component, it is destroyed when the component is destroyed. In a root-provided service, it is destroyed when the application is destroyed.
Its main method is onDestroy(callback). The callback runs once, at destruction time. The method returns a function that unregisters the callback.
import { Component, DestroyRef, inject } from '@angular/core';
@Component({
selector: 'app-resize-logger',
standalone: true,
template: `<p>Open the console and resize the window.</p>`,
})
export class ResizeLoggerComponent {
constructor() {
const destroyRef = inject(DestroyRef);
const onResize = () => console.log('width:', window.innerWidth);
window.addEventListener('resize', onResize);
destroyRef.onDestroy(() => {
window.removeEventListener('resize', onResize);
console.log('resize listener removed');
});
}
}The setup and the teardown sit next to each other. With ngOnDestroy, the listener function would have to be stored in a field so the second method could reach it. Here a local variable is enough, because the cleanup callback closes over it.
This also means cleanup can live in a helper function, not just in a class. Any function that runs in an injection context can call inject(DestroyRef) and register its own teardown. The component does not need to know the helper exists.
import { DestroyRef, inject } from '@angular/core';
export function listenToWindow(
eventName: string,
handler: (event: Event) => void,
): void {
const destroyRef = inject(DestroyRef);
window.addEventListener(eventName, handler);
destroyRef.onDestroy(() => window.removeEventListener(eventName, handler));
}A component calls listenToWindow('resize', () => ...) in its constructor or in a field initializer, and the listener is removed automatically.
takeUntilDestroyed
takeUntilDestroyed is an RxJS operator that ends a stream when the current context is destroyed. It replaces the common pattern of a destroy$ subject with takeUntil(this.destroy$).
The operator can be used in two ways:
- With no argument, inside an injection context. It finds the
DestroyRefitself. - With a
DestroyRefargument, anywhere else, such as inngOnInit.
This is the form from the earlier ticker example. The DestroyRef is injected as a field, which is an injection context, and then passed to the operator later:
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
standalone: true,
template: `<p>Ticks: {{ ticks }}</p>`,
})
export class TickerComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef);
ticks = 0;
ngOnInit(): void {
interval(1000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.ticks++);
}
}When the component is destroyed, the operator completes the stream. The interval timer stops, and the subscription is closed. No ngOnDestroy method exists.
The no-argument form is shorter. It only works where inject() works, so you can use it in a constructor or a field initializer:
import { Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker-short',
standalone: true,
template: `<p>Ticks: {{ ticks }}</p>`,
})
export class TickerShortComponent {
ticks = 0;
constructor() {
interval(1000)
.pipe(takeUntilDestroyed())
.subscribe(() => this.ticks++);
}
}If you call takeUntilDestroyed() with no argument outside an injection context, Angular throws an error at the point of the call. That is a useful failure, because it shows the mistake the first time the code runs. The old takeUntil(this.destroy$) pattern gave no such warning when you forgot to complete the subject.
The comparison
| Aspect | `ngOnDestroy` plus `Subscription` | `takeUntilDestroyed` |
|---|---|---|
| Lines of code per subscription | A field, an assignment, and a teardown line | One operator in the pipe |
| Setup and teardown location | Two different methods | One place |
| Works outside classes with hooks | No | Yes, in any injection context |
| Handles non-RxJS cleanup | Yes | No, use `DestroyRef.onDestroy` |
| Stream completes on destroy | No, it is unsubscribed | Yes, `complete` is delivered |
The last row matters. With unsubscribe(), the subscriber receives nothing. With takeUntilDestroyed, the stream completes, so a complete callback or a finalize operator in the pipe runs. This is often what you want, because finalize can then release resources the stream owns.
Placement in the pipe
Put takeUntilDestroyed as the last operator before subscribe. If you place it earlier and a later operator such as switchMap creates an inner observable, that inner stream can outlive the component. Putting the operator last cuts the whole chain.
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject, switchMap, timer } from 'rxjs';
@Component({
selector: 'app-search-poller',
standalone: true,
template: `<button (click)="start()">Start</button>`,
})
export class SearchPollerComponent {
private readonly destroyRef = inject(DestroyRef);
private readonly trigger$ = new Subject<void>();
constructor() {
this.trigger$
.pipe(
switchMap(() => timer(0, 2000)),
takeUntilDestroyed(), // last, so the inner timer is also cut off
)
.subscribe((n) => console.log('poll', n));
}
start(): void {
this.trigger$.next();
}
}Common mistakes
- Calling it in
ngOnInitwith no argument.ngOnInitis not an injection context, so the call throws. Passthis.destroyRef, or move the subscription to the constructor. - Forgetting the operator on long-lived streams.
HttpClientrequests complete by themselves, so they do not need it. Streams frominterval,fromEvent,Subject, store selectors, and router events do not complete, so they do. - Using it for the
asyncpipe or signals. Theasyncpipe unsubscribes on its own. A signal made withtoSignalalso cleans up its subscription automatically, so you do not add the operator there. - Assuming it runs on route changes only. It runs when the context is destroyed, not when it is merely hidden. A component kept alive by a route reuse strategy keeps its subscriptions.
- Using it for non-observable resources. Timers made with
setTimeout, event listeners, and observers such asResizeObserverneeddestroyRef.onDestroy.
Choosing between the approaches
Use takeUntilDestroyed for any RxJS stream that does not end by itself. Use DestroyRef.onDestroy for everything else that needs releasing. Keep ngOnDestroy when the teardown logic is a single, tightly related block that reads better in one named method, or when you maintain code that must run on Angular versions before DestroyRef existed. Mixing the styles in one component is allowed, because Angular runs ngOnDestroy and the DestroyRef callbacks during the same destruction step.
Exercise
A component starts fromEvent(document, 'keydown') inside ngOnInit. A developer writes .pipe(takeUntilDestroyed()) there and the app throws an error when the component is created. What is wrong, and what are two ways to fix it?
Show answer
ngOnInit is not an injection context, so takeUntilDestroyed() with no argument cannot find a DestroyRef. Fix 1: inject DestroyRef as a field with private readonly destroyRef = inject(DestroyRef); and call takeUntilDestroyed(this.destroyRef) in ngOnInit. Fix 2: move the subscription into the constructor or a field initializer, where takeUntilDestroyed() with no argument works.
Exercise
A component adds a scroll listener with window.addEventListener in its constructor. Using DestroyRef, show the line that makes sure the listener is removed when the component is destroyed, assuming the handler is stored in a constant named onScroll and the reference is named destroyRef.
Show answer
destroyRef.onDestroy(() => window.removeEventListener('scroll', onScroll)); The same function reference that was passed to addEventListener must be passed to removeEventListener, so onScroll has to be a named constant and not an inline arrow function.