takeUntilDestroyed()

RxJS operator that completes a stream when the context is destroyed.

Since Angular 16+ Spec ↗

Syntax

takeUntilDestroyed<T>(destroyRef?): MonoTypeOperatorFunction<T>

Parameters

NameTypeRequiredDescription
destroyRef DestroyRef No Optional; required when used outside an injection context.

Returns

OperatorFunction — Operator that auto-unsubscribes on destroy.

Examples

import { Component, inject, DestroyRef } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';

@Component({ selector: 'app-x', standalone: true, template: '' })
export class XComponent {
  private destroyRef = inject(DestroyRef);
  ngOnInit() {
    interval(1000)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(console.log);
  }
}

Notes

When called in an injection context (constructor/field initializer) the DestroyRef is inferred and the argument is optional; elsewhere (e.g. ngOnInit) pass an injected DestroyRef. Eliminates manual takeUntil/Subject unsubscription boilerplate.