Sub topic 1
What Attribute Directives Are and When to Use Them
Prerequisites
This chapter assumes you know the following:
- TypeScript basics, including classes and decorators.
- Angular components and templates.
- Standalone components and the
importsarray. - Basic template syntax: property binding and event binding.
You do not need to have written a directive before. This chapter builds the mental model that the rest of the tutorial uses.
The three kinds of directives
A directive is a class that Angular attaches to an element in a template. Angular gives you three kinds.
| Kind | What it does | Has its own template | Typical example |
|---|---|---|---|
| Component | Renders a view and owns an element | Yes | `<app-user-card>` |
| Structural directive | Adds or removes elements from the DOM | No | `@if`, `@for`, `*ngIf` |
| Attribute directive | Changes how an existing element looks or behaves | No | `ngClass`, `ngStyle`, custom directives |
Every component is technically a directive with a template. Structural directives change the shape of the DOM tree. Attribute directives leave the tree alone and adjust the element they sit on.
An attribute directive is written as an attribute in the markup. The element it sits on is called the host element. The directive can read the host, change its styles, listen to its events, and send events back to the surrounding template.
When to use an attribute directive
Choose an attribute directive when the behavior is attached to an element that already exists and does not need its own markup. Good cases include:
- Visual changes, such as highlighting an element on hover.
- Behavior shared across many elements, such as trimming whitespace on inputs or auto-focusing a field.
- Reacting to events on the host, such as detecting a click outside a menu.
- Adding accessibility attributes, such as
roleoraria-*values, in one place.
Choose a different tool in these cases:
- If the feature needs its own template, write a component.
- If the feature must create or remove elements, write a structural directive.
- If the logic only transforms a value for display, write a pipe.
The main benefit is reuse without a wrapper. You can put the same directive on a <p>, a <button>, or a component, and the element's own template and styles stay untouched.
A first look
Here is the smallest useful attribute directive. It gives its host element a yellow background.
import { Directive, ElementRef, inject } from '@angular/core';
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
constructor() {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}Three parts matter here:
@Directivemarks the class as a directive.- The selector
[appHighlight]is an attribute selector. The directive attaches to any element that has anappHighlightattribute. inject(ElementRef)gives the directive a reference to the host element. Angular creates one directive instance for each matching element.
A standalone component applies the directive by listing it in imports and adding the attribute in its template.
import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-demo',
imports: [HighlightDirective],
template: `<p appHighlight>This paragraph is highlighted.</p>`,
})
export class DemoComponent {}If you leave the directive out of imports, Angular treats appHighlight as a plain HTML attribute. It does not report an error for unknown attributes, so the paragraph silently stays unstyled. When a directive seems to do nothing, check imports first.
What comes next
The first example writes to the DOM directly in the constructor. That works for a demonstration, but later chapters show safer approaches. They cover Renderer2, host bindings, and host event listeners. They also add inputs so each element can configure the directive, and outputs so the directive can talk back.
Exercise
You need a feature that wraps any button in a tooltip box containing extra markup, and the box must be created only when the user hovers. Which kind of directive or construct fits best, and why?
Show answer
A component or a structural directive fits, not an attribute directive. An attribute directive only changes an existing host element and has no template, so it cannot create new markup. A structural directive can add the tooltip element on hover, and a component can own the tooltip's template.
Exercise
You wrote an attribute directive with the selector [appHighlight] and added appHighlight to a <p> in a standalone component's template. The paragraph is not highlighted and the console shows no error. What is the most likely cause?
Show answer
The directive is missing from the component's imports array. Angular then treats appHighlight as an ordinary HTML attribute and does nothing with it.