Sub topic 9
Injecting services and cleaning up
This chapter assumes you can write a standalone attribute directive with @Directive, read its host with ElementRef, and use host bindings. Here you will give a directive access to services and make sure it leaves nothing behind when Angular destroys it.
Injecting services with inject()
A directive is created by Angular's dependency injection (DI) system, so it can request any service the same way a component does. Call inject() in a field initializer or in the constructor. Both run in an injection context, which is the only place inject() works.
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ThemeService {
readonly accent = signal('goldenrod');
}import { Directive, inject } from '@angular/core';
import { ThemeService } from './theme.service';
@Directive({
selector: '[appThemed]',
host: {
'[style.color]': 'theme.accent()',
},
})
export class ThemedDirective {
protected theme = inject(ThemeService);
}The host binding reads a signal, so the element's color updates whenever accent changes. Services provided in root are shared. If a component lists the service in its own providers, the directive on that component's elements receives the component-scoped instance instead.
Directives can also inject other directives and components on the same element or from an ancestor. Pass { optional: true } when the other party may be missing, as in inject(FormGroupDirective, { optional: true }).
What Angular cleans up for you
Angular removes listeners declared in host or with @HostListener when the directive is destroyed. This includes document: and window: listeners, such as the (document:click) listener from the click-outside example. Prefer these over calling addEventListener yourself.
What you must clean up
Anything you start outside Angular's templates stays alive after the element is removed. Typical cases are:
- timers from
setIntervalorsetTimeout - RxJS subscriptions
- listeners added with
addEventListener - observers such as
ResizeObserver
A directive that leaks these keeps running against a detached element and holds it in memory.
Registering cleanup with DestroyRef
DestroyRef is injectable and lets you register a callback that runs when the directive is destroyed. You register it next to the code that creates the resource, so the two stay together.
import { DestroyRef, Directive, ElementRef, Renderer2, inject } from '@angular/core';
@Directive({
selector: '[appBlink]',
})
export class BlinkDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
private renderer = inject(Renderer2);
private destroyRef = inject(DestroyRef);
constructor() {
let visible = true;
const id = setInterval(() => {
visible = !visible;
this.renderer.setStyle(this.el.nativeElement, 'opacity', visible ? '1' : '0.3');
}, 500);
this.destroyRef.onDestroy(() => clearInterval(id));
}
}Renderer2.listen() returns a function that removes the listener. Pass that function to onDestroy and you have the same pattern for DOM events you attach manually:
const stopListening = this.renderer.listen(this.el.nativeElement, 'focus', () => {
// react to focus
});
this.destroyRef.onDestroy(stopListening);You can also implement ngOnDestroy(). It works, but it splits setup and teardown into two places and needs a field to hold each handle.
Unsubscribing from RxJS streams
For observables, use takeUntilDestroyed() from @angular/core/rxjs-interop. Called in an injection context, it finds the DestroyRef itself.
import { Directive, ElementRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Directive({
selector: '[appTicker]',
})
export class TickerDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
constructor() {
interval(1000)
.pipe(takeUntilDestroyed())
.subscribe((n) => {
this.el.nativeElement.textContent = `Seconds: ${n}`;
});
}
}If you subscribe outside the constructor or a field initializer, such as inside a method, there is no injection context. Store inject(DestroyRef) in a field and call takeUntilDestroyed(this.destroyRef).
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Calling `inject()` inside a method or callback | Runtime error: no injection context | Call it in a field initializer or the constructor and keep the result |
| Starting a timer with no cleanup | Timer runs after the element is gone | Register `clearInterval` with `onDestroy` |
| Using `addEventListener` on `document` | Listener leaks | Use a `document:` host listener or `Renderer2.listen` |
| Subscribing without `takeUntilDestroyed` | Subscription outlives the directive | Add the operator to the pipe |
Exercise
A directive calls setTimeout in its constructor to add a CSS class after two seconds. The host element may be removed before then. How do you avoid acting on a destroyed directive?
Show answer
Inject DestroyRef, store the timer id returned by setTimeout, and register this.destroyRef.onDestroy(() => clearTimeout(id)). If the directive is destroyed first, the timeout is cancelled and the class is never added.