Sub topic 2
Declaring a directive: @Directive and the attribute selector
This chapter assumes you know TypeScript classes and decorators, Angular components and templates, and standalone components with the imports array. It shows how to declare a directive class and how its selector decides which elements the directive attaches to.
The @Directive decorator
A directive is a TypeScript class marked with the @Directive decorator. The decorator tells Angular to treat the class as a directive and tells it where to apply the class. The decorator looks like @Component, but it has no template. A directive adds behavior to an element that already exists.
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';
}
}This is the smallest useful attribute directive. It has three parts:
@Directive({ ... })registers the class with Angular.selector: '[appHighlight]'tells Angular to create an instance of the class for every element that has theappHighlightattribute.- The class body holds the behavior. Here it injects
ElementRef, a wrapper around the host element, and sets a background color. The host element is the element the directive is attached to. Later chapters coverElementRefand safer ways to change the host.
Angular creates one instance of the class for each matching element. If a template has ten elements with appHighlight, there are ten HighlightDirective instances.
How the attribute selector works
The selector is a CSS-style string that Angular matches against elements in templates. Square brackets mean "match elements that have this attribute".
| Selector | Matches |
|---|---|
| `[appHighlight]` | Any element with the `appHighlight` attribute |
| `button[appHighlight]` | Only `<button>` elements with the attribute |
| `[appHighlight]:not(a)` | Any element with the attribute except `<a>` |
| `.card[appHighlight]` | Elements with the `card` class and the attribute |
Narrowing the selector to an element type prevents misuse. A directive that only makes sense on buttons should not attach to a <div>.
Matching happens at compile time, so Angular decides which directives apply when it compiles the template. It does not search the DOM at runtime. A selector that matches nothing fails silently, so a typo in the attribute name gives no error.
Naming and prefixes
Attribute selectors share a namespace with every native HTML attribute and every directive from third-party libraries. A selector named [highlight] could collide with a library's directive or a future HTML attribute. Use a short prefix, written in camelCase. The Angular CLI uses app by default, so the selector is appHighlight.
The convention is a file named name.directive.ts, a class named NameDirective, and a selector [appName]. Following it makes directives easy to find and recognize.
Standalone by default
In current Angular versions, directives are standalone by default. A standalone directive does not belong to an NgModule. A template that wants to use it lists the class in its imports array, which the next chapter covers. In older versions (before Angular 19), you had to write standalone: true in the decorator yourself. If you maintain older code, add that flag. Without it, Angular expects the directive to be declared in a module.
A directive without a selector
The selector property is optional. A directive without one cannot be used in a template. It can only serve as an abstract base class that other directives extend, or as a directive that other code applies through hostDirectives, which a later chapter covers. For a directive that users write in templates, always set a selector.
Checklist for declaring a directive
- Import
Directivefrom@angular/core. - Decorate a class with
@Directiveand give it an attribute selector with a prefix. - Name the class and the file following the
NameDirectiveandname.directive.tsconvention. - Narrow the selector with an element name if the directive only suits certain elements.
- Keep the constructor and fields small. Inject what you need with
inject().
Exercise
A teammate writes @Directive({ selector: 'appTooltip' }) and applies it as <span appTooltip> in a template, but nothing happens. What is wrong, and what selector should they use if the directive should only apply to <button> elements?
Show answer
The selector has no square brackets, so Angular treats it as an element selector that matches <appTooltip> tags, not as an attribute selector. The attribute selector is [appTooltip]. To restrict it to buttons, use button[appTooltip].