Sub topic 2
Declaring a Directive: @Directive and the Attribute Selector
This chapter covers the two pieces every attribute directive needs: the @Directive decorator and a selector that says which elements the directive attaches to. It also covers how Angular matches the selector at compile time, and the mistakes that make a directive silently do nothing.
What this chapter assumes
You should be comfortable with TypeScript classes and decorators, and with Angular components and templates. You should know how a standalone component lists dependencies in its imports array, and how property binding ([prop]="value") and event binding ((event)="handler()") work. The chapter uses inject() for dependency injection, which works in Angular 14 and later. The imports array on components needs Angular 14 or later as well, and standalone behavior by default needs Angular 19 or later (see below).
The smallest useful directive
An attribute directive is a class with no template of its own. Angular creates an instance of it for each element that matches its selector. The class can then change that element, called the host element.
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 file has four parts:
- The import.
Directiveis the decorator.ElementRefandinjectgive the class access to its host element. - The decorator.
@Directive({...})marks the class as a directive and carries the metadata Angular needs at compile time. - The selector.
'[appHighlight]'is a CSS-style selector. The square brackets mean "an element that has an attribute with this name". - The class. It receives its host element through
inject(ElementRef)and sets a style in the constructor. The next chapter coversElementRefin more detail, along with the saferRenderer2.
The class name ends in Directive and the file is named highlight.directive.ts. Both are conventions, not requirements. Angular does not care what the class is called, but the Angular style guide and the CLI follow them, so other developers expect them.
You can generate the same skeleton with the CLI:
ng generate directive highlightThe command creates highlight.directive.ts and a spec file. The selector comes out as [appHighlight], using the project's prefix, which is app by default.
What the @Directive metadata contains
The selector is the only property you must set. The other properties appear in later chapters, but this table shows where each one fits.
| Property | Purpose | Covered in |
|---|---|---|
| `selector` | Which elements the directive attaches to | This chapter |
| `standalone` | Whether the directive is imported directly rather than declared in an NgModule | This chapter |
| `host` | Host bindings and event listeners declared as metadata | Chapter on host events and bindings |
| `inputs` / `outputs` | Legacy array form of declaring inputs and outputs. The `input()` and `output()` functions are preferred. | Chapters on inputs and outputs |
| `exportAs` | Name that lets a template reference read the directive instance | Chapter on `exportAs` |
| `providers` | Services scoped to this directive instance | Chapter on injection |
| `hostDirectives` | Other directives applied to the same host | Chapter on composition |
Standalone by default
Since Angular 19, directives, components, and pipes are standalone unless you say otherwise. In Angular 14 through 18 you must write standalone: true yourself:
import { Directive } from '@angular/core';
@Directive({
selector: '[appHighlight]',
standalone: true,
})
export class HighlightDirective {}In Angular 19 and later, standalone: true is redundant but harmless. The tutorial's other code omits it, so it assumes version 19 or later. Only declare a directive in an NgModule's declarations array if you maintain a legacy codebase and the directive sets standalone: false.
Writing the attribute selector
Angular accepts a subset of CSS selector syntax. For attribute directives you almost always use an attribute selector, optionally narrowed by an element name.
| Selector | Matches |
|---|---|
| `[appHighlight]` | Any element that has the attribute `appHighlight` |
| `button[appHighlight]` | Only `<button>` elements with the attribute |
| `[appHighlight], [appMark]` | Elements with either attribute. The directive attaches once per element. |
| `input:not([readonly])[appHighlight]` | Inputs that have the attribute and are not read-only |
| `appHighlight` | An element named `<appHighlight>`. This is almost never what you want. |
Three details matter in practice.
Brackets make it an attribute selector. Writing selector: 'appHighlight' without brackets compiles without any error. It then matches a hypothetical <appHighlight> element, so your <p appHighlight> never gets the directive. This is one of the most common first mistakes.
Property bindings count as attributes for matching. The selector [appHighlight] matches all three of these:
<p appHighlight>Plain attribute</p>
<p appHighlight="lightblue">Attribute with a value</p>
<p [appHighlight]="color">Property binding</p>Matching looks only at the attribute name. In the first two forms the value is an ordinary string attribute. In the third, the value is bound at runtime. A directive input can use any of these forms, as the inputs chapter shows.
Matching is static. Angular compares selectors to template elements when it compiles the template. It never re-evaluates the match at runtime. You cannot make a directive attach or detach by changing a value. To enable or disable behavior, give the directive an input and branch inside the class. Angular does match a binding such as [attr.appHighlight] differently, so avoid it for selection.
Choosing a prefix
Pick a short prefix for your project and use it on every directive selector, for example app or a team name like acme. The prefix has two jobs. It avoids clashes with native HTML attributes, since a future HTML standard might add a highlight attribute. It also avoids clashes with third-party directives. Do not use the ng prefix, which belongs to the framework.
Use lowerCamelCase for the attribute name, such as appHighlight. Angular templates are case-sensitive, so appHighlight and apphighlight are different attributes. This differs from plain HTML, where attribute names ignore case.
Restricting by element
If a directive only makes sense on certain elements, put the element name in the selector. For example, a directive that marks buttons as primary:
import { Directive } from '@angular/core';
@Directive({
selector: 'button[appPrimary]',
host: {
class: 'btn-primary',
},
})
export class PrimaryButtonDirective {}Now <button appPrimary> gets the class, while <p appPrimary> does nothing. Narrow selectors prevent misuse and can document intent. They also have a cost: if you later need the directive on a custom component, you must widen the selector. Use a bare [appX] selector when the behavior is truly element-agnostic.
How a directive reaches the template
Declaring the class is not enough. The component that uses it must import it. The next listing shows the use site.
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 {}The imports array tells the compiler which directives, components, and pipes are in scope for this component's template. For each element in the template, the compiler checks every in-scope selector. When one matches, it records that the directive must be instantiated for that element.
Some consequences follow from this model:
- One instance per element. If the template has three
<p appHighlight>elements, Angular creates threeHighlightDirectiveobjects, each with its ownElementRefand its own state. - The lifetime matches the element. The instance is created when Angular creates the element and destroyed when the element is removed, for example by
@ifor@for. - Several directives can share an element.
<button appPrimary appTooltip>attaches both. The order in which their constructors run is not something to rely on. - A component is also a directive. If a component and your directive both match one element, both are instantiated. Each element has at most one component, and any number of attribute directives.
Common errors
The directive is not imported. A plain attribute such as <p appHighlight> is just an unknown attribute to HTML, so Angular raises no error and nothing happens. The symptom is "my directive does nothing". With a binding form, <p [appHighlight]="color">, the compiler reports an error like Can't bind to 'appHighlight' since it isn't a known property of 'p'. If you see that message, add the directive to the imports array.
The selector is missing its brackets. As described above, 'appHighlight' matches an element name. Check the selector first when a directive never runs.
The class lacks @Directive. A plain class that you list in imports is rejected by the compiler as not being a directive, component, or pipe. The decorator is what produces the compiled metadata.
The directive is not exported. If the class is declared in one file and imported in another, the declaration needs export. A missing export shows up as an ordinary TypeScript import error.
A template was added to a directive. @Directive has no template property. If you need to render markup, you want @Component. A component is a directive with a template, so the choice depends only on whether you need to render new markup.
Two directives share one selector. Both attach to every matching element, and both run. If they write the same style or property, the last one to write wins, which is hard to debug. Keep selectors unique within a project.
Choosing between a directive and a component
Use an attribute directive when you want to add behavior to an element that already exists and that someone else controls: its style, its classes, its event handling. Use a component when you own a piece of the template and want to render markup. A good test is whether the feature needs a template of its own. If it does not, and you want it to work on many different elements, write a directive.
Exercise
A teammate writes @Directive({ selector: 'appHighlight' }) and uses <p appHighlight>text</p>. The paragraph is never highlighted and the compiler reports no error. What is wrong, and how do you fix it?
Show answer
Without square brackets, the selector appHighlight is an element selector, so it matches only an element named <appHighlight>. The paragraph has an attribute, not that element name. Change the selector to '[appHighlight]'. Also confirm that the component using the directive lists it in its imports array.
Exercise
You want a directive appAutoTrim that attaches only to <input> elements that are not marked readonly. Write the selector. Then say what happens if someone writes <textarea appAutoTrim>.
Show answer
Use selector: 'input:not([readonly])[appAutoTrim]'. The <textarea appAutoTrim> element does not match, because the selector requires an input element. Angular treats appAutoTrim as an unknown plain attribute and attaches nothing, so no error appears. A binding such as [appAutoTrim]="x" would produce a "can't bind" compile error instead.