Sub topic 9
Injecting services and cleaning up
This chapter assumes you can write a standalone attribute directive with @Directive, read the host element through ElementRef, and bind host properties and events. It also assumes you know what a service is and have seen inject() used in a component. Here you will see how a directive gets services, how long a directive lives, and how to release anything it creates.
How a directive gets its dependencies
A directive is created by Angular, so it receives dependencies from Angular's injector tree. Call inject() in a field initializer or in the constructor. You have already used it for ElementRef and Renderer2. Services work the same way.
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ThemeService {
readonly mode = signal<'light' | 'dark'>('light');
toggle(): void {
this.mode.update((m) => (m === 'light' ? 'dark' : 'light'));
}
}import { Directive, inject } from '@angular/core';
import { ThemeService } from './theme.service';
@Directive({
selector: '[appThemed]',
host: {
'[class.dark]': 'theme.mode() === "dark"',
},
})
export class ThemedDirective {
readonly theme = inject(ThemeService);
}Every element that carries appThemed gets its own ThemedDirective instance. All the instances share one ThemeService, because it is provided in root. When the signal changes, the host binding re-evaluates and the dark class is added or removed. The directive stores no copy of the state.
inject() only works in an injection context. That context exists while Angular constructs the directive, which covers field initializers and the constructor. It does not exist inside a later event handler or a setTimeout callback. If you need a dependency there, inject it into a field and use the field.
Where the injector looks
A directive sits on an element, and each element has an element injector. When a directive asks for a token, Angular searches in this order:
- The providers of directives on the same element.
- The element injectors of the parent elements, moving up the template.
- The environment injector, which holds root and route-level providers.
This lets a directive talk to a parent directive or component:
import { Directive, inject } from '@angular/core';
import { ThemedDirective } from './themed.directive';
@Directive({ selector: '[appThemeAware]' })
export class ThemeAwareDirective {
readonly parentTheme = inject(ThemedDirective, { optional: true });
}The optional: true flag makes inject return null instead of throwing when no ancestor has ThemedDirective. Two other flags are common. self: true limits the search to the same element, and skipSelf: true starts at the parent.
Providing a service per element
A directive can declare providers. The service instance then belongs to that element and is visible to the element's own directives and its descendants.
import { Directive, Injectable, inject } from '@angular/core';
@Injectable()
export class ClickCounter {
count = 0;
}
@Directive({
selector: '[appCounted]',
providers: [ClickCounter],
host: { '(click)': 'counter.count = counter.count + 1' },
})
export class CountedDirective {
readonly counter = inject(ClickCounter);
}Each element with appCounted gets a fresh ClickCounter. Angular destroys that instance when the element goes away. A directive has providers but no viewProviders. That option exists only on components.
The lifetime of a directive
A directive instance lives exactly as long as its host element is part of the rendered view. It is created when the element is created. It is destroyed when the element is removed, for example when an @if block turns false, a list item disappears, or a route changes.
Angular removes the listeners it knows about, which are the ones you declared with host or @HostListener. It cannot know about anything you started yourself. Those leftovers are your responsibility:
- Timers from
setTimeoutandsetInterval. - Browser observers such as
ResizeObserver,IntersectionObserver, andMutationObserver. - Listeners added with
addEventListener. - RxJS subscriptions.
- Subscriptions to long-lived stores or to services that outlive the directive.
If you skip cleanup, a removed element's directive can stay in memory because the observer, timer, or subscription still references it. It may also keep running and calling emit or changing the DOM after the element is gone.
Cleaning up with DestroyRef
DestroyRef is the simplest tool. Inject it, and register a callback that runs when the directive is destroyed. You register the callback next to the code that creates the resource, so the two stay together.
import {
DestroyRef,
Directive,
ElementRef,
afterNextRender,
inject,
output,
} from '@angular/core';
@Directive({ selector: '[appResizeWatch]' })
export class ResizeWatchDirective {
private readonly el = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly destroyRef = inject(DestroyRef);
readonly widthChange = output<number>();
constructor() {
afterNextRender(() => {
const observer = new ResizeObserver((entries) => {
this.widthChange.emit(Math.round(entries[0].contentRect.width));
});
observer.observe(this.el.nativeElement);
this.destroyRef.onDestroy(() => observer.disconnect());
});
}
}Two details matter here. afterNextRender runs its callback only in the browser, after Angular has rendered. On the server there is no ResizeObserver, so the callback is skipped and the directive does not crash during server-side rendering. Second, onDestroy is called right after observe, so every observer that starts also has a matching disconnect.
In a template you use it like any other output:
<div appResizeWatch (widthChange)="width = $event">Resize me</div>DestroyRef.onDestroy also returns a function. Call it to unregister the callback early, which is useful if you release the resource yourself before the directive is destroyed.
Cleaning up RxJS with takeUntilDestroyed
For observables, takeUntilDestroyed from @angular/core/rxjs-interop completes the stream when the directive is destroyed. Called with no argument, it must run in an injection context, so use it in a field initializer or the constructor.
import { Directive, ElementRef, inject, input, output } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounce, fromEvent, map, timer } from 'rxjs';
@Directive({ selector: 'input[appDebounce]' })
export class DebounceDirective {
private readonly el = inject<ElementRef<HTMLInputElement>>(ElementRef);
readonly delay = input(300, { alias: 'appDebounce' });
readonly debounced = output<string>();
constructor() {
fromEvent(this.el.nativeElement, 'input')
.pipe(
debounce(() => timer(this.delay())),
map(() => this.el.nativeElement.value),
takeUntilDestroyed(),
)
.subscribe((value) => this.debounced.emit(value));
}
}The directive is used like this:
<input appDebounce="500" (debounced)="search($event)" />Look at debounce(() => timer(this.delay())). It could have been debounceTime(this.delay()), but that would be wrong. Signal inputs are not set yet while the constructor runs, so this.delay() would return the default of 300 and the value from the template would be ignored. Passing a function delays the read until an event arrives, by which time the input holds the bound value.
Choosing a cleanup tool
| Tool | Use it when | Notes |
|---|---|---|
| `host` or `@HostListener` | You listen to events on the host, `document`, or `window` | Angular adds and removes the listener for you |
| `DestroyRef.onDestroy` | You create a resource by hand, such as an observer or timer | Register the callback beside the creation code |
| `takeUntilDestroyed()` | You subscribe to an observable | Needs an injection context, or pass a `DestroyRef` |
| `ngOnDestroy` | You already implement lifecycle hooks and prefer the interface | Equivalent in effect, but separates cleanup from setup |
Prefer a declarative host listener over manual addEventListener whenever the target is the host, document, or window. The click-outside directive from earlier in this tutorial uses (document:click) for that reason, and it needs no cleanup code at all.
Getting the document and window safely
Do not reference the global document directly in a directive. Inject the DOCUMENT token from @angular/common. On the server it resolves to a server-side document instead of failing.
import { DOCUMENT } from '@angular/common';
import { Directive, inject } from '@angular/core';
@Directive({ selector: '[appTitleLogger]' })
export class TitleLoggerDirective {
private readonly doc = inject(DOCUMENT);
constructor() {
console.log('Page title:', this.doc.title);
}
}Use this.doc.defaultView to reach window. It is null when there is no window, so check it before use. Browser-only APIs such as ResizeObserver, matchMedia, and localStorage belong inside afterNextRender.
Common mistakes
- Reading inputs in the constructor. Inputs get their values after construction. Read them in
ngOnInit, in acomputed, in aneffect, or lazily inside callbacks. - Creating an observer and never disconnecting it. Each observer keeps a reference to your callback, which keeps the directive alive.
- Using
takeUntilDestroyed()outside an injection context. Angular throws an error. InjectDestroyRefand pass it in. - Emitting an output after destruction. An output that emits once the directive is destroyed raises an error. Stop the source first, which is the main reason to disconnect observers and cancel timers.
- Providing a service in a directive and expecting sharing. A directive's
providerscreate one instance per host element. If you need one instance for the whole app, useprovidedIn: 'root'.
Exercise
A directive declares readonly delay = input(300) and, in its constructor, calls interval(this.delay()).pipe(takeUntilDestroyed()).subscribe(...). The template uses [delay]="1000", yet the stream ticks every 300 ms. What is the cause, and how would you fix it so that the value 1000 is used?
Show answer
Signal inputs are not populated while the constructor runs, so this.delay() returns the default 300 at the moment interval is created. To fix it, read the input later. Either move the subscription to ngOnInit, where the bound value is available (and pass takeUntilDestroyed(this.destroyRef) because it is no longer in an injection context), or build the stream lazily, for example with timer-based operators that take a function so the input is read when the first event arrives.
Exercise
A directive creates an IntersectionObserver inside afterNextRender and never disconnects it. The host element is inside an @if block that toggles often. What happens, and what single line fixes it?
Show answer
Each time the block turns true a new directive and observer are created. When it turns false the old observer is not disconnected, so it still references the directive and the removed element, which keeps both in memory and lets the callback keep firing. Add this.destroyRef.onDestroy(() => observer.disconnect()); right after calling observer.observe(...), using an injected DestroyRef.