Sub topic 10
Modern cleanup with DestroyRef and takeUntilDestroyed
This chapter assumes you know how to write a basic Angular component, how ngOnInit and ngOnDestroy work, and how to subscribe to an RxJS observable. It shows a shorter way to release resources when a component is destroyed.
The problem with manual cleanup
The classic pattern needs three parts: a field to hold the Subscription, code in ngOnInit to fill it, and an ngOnDestroy method that calls unsubscribe().
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription, interval } from 'rxjs';
@Component({
selector: 'app-clock',
standalone: true,
template: `<p>Seconds: {{ seconds }}</p>`,
})
export class ClockComponent implements OnInit, OnDestroy {
seconds = 0;
private subscription?: Subscription;
ngOnInit(): void {
this.subscription = interval(1000).subscribe(() => this.seconds++);
}
ngOnDestroy(): void {
this.subscription?.unsubscribe();
}
}This works. The weakness is that the setup and the cleanup live in different places. If you add a second subscription and forget to unsubscribe from it, the timer keeps running after the component is gone.
DestroyRef
DestroyRef is an injectable token that represents the end of the current lifetime. In a component, that lifetime is the component's. You can register callbacks on it with onDestroy(), and Angular runs them when the component is destroyed.
import { Component, DestroyRef, inject } from '@angular/core';
@Component({
selector: 'app-listener',
standalone: true,
template: `<p>Listening for resize events</p>`,
})
export class ListenerComponent {
constructor() {
const destroyRef = inject(DestroyRef);
const onResize = () => console.log('resized');
window.addEventListener('resize', onResize);
destroyRef.onDestroy(() => window.removeEventListener('resize', onResize));
}
}Here the listener and its removal sit next to each other. onDestroy() also returns a function that unregisters the callback, in case you need to cancel it early.
takeUntilDestroyed
takeUntilDestroyed is an RxJS operator from @angular/core/rxjs-interop. It completes an observable when the DestroyRef it is given is destroyed. You pass it to pipe(), so no ngOnDestroy method is needed.
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++);
}
}The destroyRef argument is required here because ngOnInit runs outside an injection context. An injection context is code that Angular runs while it creates a class, such as a constructor or a field initializer. Only there can inject() be called, and only there can takeUntilDestroyed() find the DestroyRef on its own.
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++);
}
}Choosing between the approaches
| Situation | Use |
|---|---|
| Subscribing in the constructor or a field initializer | `takeUntilDestroyed()` with no argument |
| Subscribing in `ngOnInit` or an event handler | `takeUntilDestroyed(destroyRef)` |
| Removing a listener or clearing a timer | `destroyRef.onDestroy(...)` |
| Cleanup that needs several ordered steps | `ngOnDestroy` |
Exercise
A component starts interval(500).pipe(takeUntilDestroyed()).subscribe(...) inside ngOnInit and throws an injection context error. Give two ways to fix it.
Show answer
First, pass a DestroyRef: inject it as a field with private readonly destroyRef = inject(DestroyRef); and call takeUntilDestroyed(this.destroyRef). Second, move the subscription into the constructor (or a field initializer), which is an injection context, so the no-argument form works.