Sub topic 12
Common pitfalls and best practices
This chapter assumes you can write a standalone attribute directive. That means a @Directive with an attribute selector, the host metadata property, signal inputs and outputs, and inject(). The mistakes below are the ones that most often break directives in real applications.
Choose the safest way to change the host
A directive's job is to change an element it did not create. Angular gives you several ways to do that. They differ in safety and in how well they work with server-side rendering (SSR).
Prefer declarative host bindings. They are checked by Angular, they work on the server, and they undo themselves when the state changes.
Pitfall 1: Writing to the DOM directly
Code such as this.el.nativeElement.style.backgroundColor = 'yellow' works in a browser. It has three problems:
- It runs once and never reverts, so the style stays after the state changes.
- It bypasses the renderer, which breaks in non-browser platforms such as SSR.
- Setting
innerHTMLwith user-controlled text opens an XSS hole. Angular's built-in sanitization does not apply to code that writes tonativeElementitself.
Use a host binding instead:
import { Directive, input } from '@angular/core';
@Directive({
selector: '[appBadge]',
host: {
'[class.badge]': 'true',
'[attr.title]': 'label() || null',
},
})
export class BadgeDirective {
label = input('', { alias: 'appBadge' });
}Binding null removes the attribute, so an empty label leaves no empty title on the element.
Pitfall 2: Touching browser globals
window, document, and localStorage do not exist on the server. Reading them in a constructor crashes SSR. Inject DOCUMENT instead of using the global. For measurements that need a real layout, such as getBoundingClientRect(), wait until the browser has rendered, for example in a callback passed to afterNextRender.
Pitfall 3: Leaking listeners
host listeners are removed for you when the element is destroyed. Listeners you add by hand are not. If you register one on document, remove it when the directive is destroyed:
import { DestroyRef, Directive, Renderer2, inject, output } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Directive({ selector: '[appEscapeKey]' })
export class EscapeKeyDirective {
private document = inject(DOCUMENT);
private renderer = inject(Renderer2);
private destroyRef = inject(DestroyRef);
escape = output<KeyboardEvent>();
constructor() {
const unlisten = this.renderer.listen(this.document, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') {
this.escape.emit(event);
}
});
this.destroyRef.onDestroy(unlisten);
}
}Renderer2.listen returns a function that removes the listener. DestroyRef.onDestroy runs it when the directive is destroyed. Use the same pattern for timers (clearTimeout) and observers (disconnect()).
Pitfall 4: Selector and naming mistakes
- No prefix. A selector like
[highlight]can collide with a native attribute or a third-party library. Use an app-specific prefix such asapp, and use your library's prefix for shared code. - Wrong case. The selector
[appHighlight]is camelCase. In the template you writeappHighlight, notapp-highlight. - Class name. End the class name with
Directive, as inHighlightDirective. - Forgotten import. In a standalone component, a directive that is not in
importsdoes nothing. Angular does not always warn about an unknown attribute, so the element simply stays unchanged. If a directive seems to do nothing, checkimportsfirst. - Input alias collision. When an input shares the selector name, as in
input('', { alias: 'appHighlight' }), the bare attribute<p appHighlight>sets the input to an empty string. Treat an empty value as "use the default", as the earliercolor() || "yellow"example did.
Other best practices
| Practice | Reason |
|---|---|
| Keep one directive to one behavior | Small directives compose through `hostDirectives` |
| Use signal `input()` and `output()` | They fit host bindings and need no lifecycle hooks |
| Avoid reading inputs in the constructor | Input values are not set yet. Use a host binding or an `effect` |
| Accept a type, not any | Typed inputs catch template mistakes at build time |
| Test with a host component | It exercises the real template, selector, and bindings |
Exercise
A directive's constructor runs document.body.addEventListener('scroll', this.onScroll). Name two problems with this code and give a fix for each.
Show answer
First, it uses the global document, which does not exist during SSR, so inject DOCUMENT instead. Second, the listener is never removed, so it leaks after the directive is destroyed. Register it with Renderer2.listen and pass the returned function to DestroyRef.onDestroy, or declare it as a host listener so Angular removes it automatically.
Exercise
You add [appTooltip] to an element in a standalone component, but nothing happens and there is no error. What do you check first?
Show answer
Check that TooltipDirective is listed in the component's imports array. Without the import, Angular does not apply the directive to the element.