Sub topic 12
Common Pitfalls and Best Practices for Attribute Directives
This chapter assumes you can already write a standalone attribute directive. That means you know @Directive, the host metadata property, signal input() and output(), ElementRef, Renderer2, and hostDirectives. Here you will review the mistakes that most often cause bugs, memory leaks, security holes, and server-side rendering (SSR) failures. For each one you get a fix, followed by a checklist you can apply in code review.
Choosing the Right Tool First
An attribute directive changes an existing element. It has no template. If you find yourself wanting to add or remove elements, you need a structural directive or a component. If you want to reuse behavior across several components, hostDirectives can compose it.
Start at the top of the diagram and take the first option that fits. Host bindings are declarative and work on the server, so they come before anything imperative.
Pitfall 1: Writing to the DOM Directly
The simplest way to change an element is this.el.nativeElement.style.backgroundColor = 'yellow'. It works in a browser, but it has three problems.
- It bypasses Angular's renderer, so it breaks in environments where the element is not a real browser element, such as SSR and some web worker setups.
- It is not tied to state. Nothing resets the style when an input changes.
- Setting
innerHTMLorouterHTMLskips Angular's sanitization and opens the door to cross-site scripting (XSS).
Prefer a host binding. Use Renderer2 only when no binding can express what you need.
import { Directive, input } from '@angular/core';
@Directive({
selector: '[appBadge]',
host: {
'[class.badge]': 'true',
'[attr.data-count]': 'count()',
},
})
export class BadgeDirective {
count = input(0, { alias: 'appBadge' });
}This directive has no ElementRef and no DOM calls. When count changes, Angular updates the attribute during change detection.
Pitfall 2: Browser-Only Code Running During SSR
During SSR, your directive's constructor runs on the server. There is no real layout there, no window, and focus() does nothing useful. Calls like getBoundingClientRect() return zeros or fail, depending on the server DOM implementation.
Two rules prevent most problems:
- Inject
DOCUMENTinstead of using the globaldocument. - Put browser-only work in
afterNextRender, which runs only in the browser, after Angular has rendered.
import { Directive, ElementRef, afterNextRender, inject } from '@angular/core';
@Directive({
selector: '[appAutofocus]',
})
export class AutofocusDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
constructor() {
afterNextRender(() => {
this.el.nativeElement.focus();
});
}
}afterNextRender must be called in an injection context, and a constructor or field initializer is one. If you call it from a method, pass an injector in the options.
Pitfall 3: Leaking Listeners and Subscriptions
Host listeners declared in host metadata are removed for you when the directive is destroyed. Anything you attach yourself is your responsibility. This covers addEventListener, RxJS subscriptions, timers, ResizeObserver, and MutationObserver.
Renderer2.listen returns a function that removes the listener. Register it with DestroyRef.
import { DestroyRef, Directive, Renderer2, inject, signal } from '@angular/core';
@Directive({
selector: '[appWindowWidth]',
exportAs: 'windowWidth',
})
export class WindowWidthDirective {
private renderer = inject(Renderer2);
width = signal(0);
constructor() {
const unlisten = this.renderer.listen('window', 'resize', () => {
this.width.set(window.innerWidth);
});
inject(DestroyRef).onDestroy(unlisten);
}
}The string 'window' is a global target that the renderer resolves, so the call is safe to make on the server. The callback only runs when a resize event fires, which does not happen during SSR. If you read window.innerWidth outside the callback, you are back in pitfall 2.
A related cost: (document:click) and (window:resize) host listeners are attached once per directive instance. A list of 500 rows, each with a appClickOutside directive, adds 500 document listeners. Each event also triggers change detection. When you expect many instances, attach one listener from a shared service and let directives register with it.
Pitfall 4: Reading Inputs Too Early
A signal input has no real value until Angular sets it. In the constructor you see only the default.
import { Directive, effect, input } from '@angular/core';
@Directive({
selector: '[appTrace]',
})
export class TraceDirective {
label = input('default');
constructor() {
console.log(this.label()); // always 'default', even for appTrace="custom"
effect(() => {
console.log(this.label()); // runs after inputs are set, and again on change
});
}
}If you need a derived value, use computed(). If you need a side effect, use effect(). A bare read in the constructor is a bug waiting to happen.
The empty-string trap
When a directive's input shares its selector name, using the attribute with no value gives an empty string, not undefined.
<p appHighlight>No value, so the input is ''</p>
<p appHighlight="lightblue">Value is 'lightblue'</p>That is why the highlight directive in this tutorial uses color() || "yellow". The nullish operator ?? would keep '' and produce an invalid color. Use || for text defaults where an empty string means "not set". Use ?? only when '' is a legitimate value.
Pitfall 5: A Forgotten Import Fails Silently
In a standalone component, the directive only applies if it is in the imports array. What happens when you forget depends on how you wrote the attribute.
| Template usage | Directive not imported |
|---|---|
| `<p appHighlight>` | Nothing happens. No error. |
| `<p appHighlight="red">` | Nothing happens. No error. |
| `<p [appHighlight]="color">` | Compile error: can't bind to `appHighlight` since it isn't a known property of `p`. |
The first two rows are the dangerous ones. A plain attribute is valid HTML, so Angular cannot tell it from a typo. If a directive does nothing, check the imports array first, then check that the selector spelling matches exactly. Attribute selectors are case-sensitive in Angular templates.
Pitfall 6: Weak Selectors
Selector problems show up as collisions or as unexpected matches.
- No prefix. A selector like
[highlight]can clash with a library or a future HTML attribute. Use an app-specific prefix such asappor your company's, and enforce it with the@angular-eslint/directive-selectorrule. - Missing brackets.
selector: 'appHighlight'matches an element named<appHighlight>, not an attribute. The directive then never applies to your<p>. - Too broad.
selector: 'input'applies the directive to every input in any template that imports it. Narrow it with an attribute, for exampleinput[appTrim]. - Input names that shadow native attributes. An input alias of
title,hidden, ordisabledon a directive overlaps with a real property of the element. Pick names that do not collide.
import { Directive } from '@angular/core';
@Directive({
selector: 'input[appTrim]',
host: {
'(blur)': 'trim($event.target)',
},
})
export class TrimDirective {
trim(input: HTMLInputElement) {
input.value = input.value.trim();
}
}This directive matches only <input> elements that carry appTrim. Putting it on a <div> does nothing, and a template type check can warn you about related mistakes.
Pitfall 7: Style and Class Conflicts
Several sources can set the same style on one element. Angular resolves them in a fixed order of precedence:
- Template bindings, such as
[style.color]="x"on the element. - Host bindings from directives.
- Host bindings from the component.
- Static attributes.
A binding that evaluates to null or undefined is skipped, and the next source takes over. That is why the highlight directive returns null when inactive, because it lets the element's own style show through. Returning an empty string or 'transparent' would override it instead.
If two directives on the same element both bind style.backgroundColor, the result depends on directive order and is hard to reason about. Give each directive its own property, or use CSS classes and let your stylesheet decide.
Pitfall 8: Testing Gaps
Directive tests fail in a few predictable ways.
- Forgetting
fixture.detectChanges(). Host bindings update during change detection. A test that dispatches an event and checks the style immediately sees the old value. - Testing the directive class in isolation. A directive is wired to an element and a template. Test it through a small host component, as in the earlier testing chapter.
- Not covering both branches. Test the state after
mouseenterand aftermouseleave, and the default value when no input is provided.
Best Practices Checklist
| Area | Do | Avoid | Column | Column |
|---|---|---|---|---|
| Changing the element | Host bindings first, `Renderer2` second | Direct `nativeElement` writes, `innerHTML` | ||
| Events | `host` metadata listeners | Manual `addEventListener` without cleanup | ||
| Cleanup | `DestroyRef.onDestroy` for anything you create | Leaving observers and timers running | ||
| SSR | `DOCUMENT`, `afterNextRender` | Global `window` and `document` in constructors | ||
| Inputs | `computed` and `effect` for derived values | Reading inputs in the constructor | ||
| Defaults | ` | ` for empty-string defaults | `??` when `''` means unset | |
| Naming | Prefixed camelCase attribute selector, narrowed by element if needed | Bare names, missing brackets | ||
| Styling | Classes, or one directive per style property | Two directives setting the same style | ||
| Structure | One responsibility per directive, composed with `hostDirectives` | A single directive that does everything | ||
| Tests | Host component, `detectChanges`, both states | Instantiating the class by hand |
Keep each directive small. A directive that highlights, tracks clicks, and fetches data is three directives. Small directives are easier to test, and hostDirectives lets a component combine them when needed.
Exercise
A teammate writes <p appHighlight="lightblue">Hi</p> in a standalone component, and the paragraph never changes color on hover. There are no console errors. Name two likely causes and how you would check each one.
Show answer
First, the component's imports array may not include HighlightDirective. A plain attribute is valid HTML, so Angular raises no error when no directive matches. Check the imports array. Second, the selector may not match, for example because the directive's selector has a typo or different casing than appHighlight. Compare the selector string in the @Directive decorator with the template attribute. A third possibility is that the host listeners are missing, which you can confirm by opening the directive and checking its host metadata.
Exercise
A directive needs to call this.el.nativeElement.focus() and also listen for window resize events. Where should each piece of code run so that the directive works with SSR and does not leak?
Show answer
Put the focus() call inside afterNextRender in the constructor, because it runs only in the browser after rendering. Register the resize listener with Renderer2.listen('window', 'resize', handler), then pass the returned unlisten function to inject(DestroyRef).onDestroy(...) so the listener is removed when the directive is destroyed.