Sub topic 3
Using the directive in a standalone component
This chapter covers how a standalone component makes an attribute directive available to its template, how Angular decides which elements receive it, and the mistakes that cause a directive to do nothing. It assumes you know TypeScript classes and decorators, Angular components and templates, and the basics of standalone components and property and event binding. It also assumes you have written the HighlightDirective from the previous chapter, or something close to it.
The code uses Angular 19 or later, where standalone: true is the default. On Angular 14 to 18, add standalone: true to every @Directive and @Component shown here.
Declaring is not the same as applying
A @Directive class does nothing on its own. Angular runs it only when two things are both true:
- The directive is in scope for the template that contains the element.
- The element matches the directive's selector.
For a standalone component, scope comes from the component's own imports array. There is no shared module and no global registry. If the template uses a directive, the component must list it.
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';
}
}The component below brings it into scope and applies it.
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 {}To run it, bootstrap the component:
import { bootstrapApplication } from '@angular/platform-browser';
import { DemoComponent } from './demo.component';
bootstrapApplication(DemoComponent).catch((err) => console.error(err));Angular creates one HighlightDirective instance for the <p> element. The directive's constructor runs, and the paragraph gets a yellow background. The <p> is called the host element of that directive instance.
How matching works
At compile time, Angular reads each element in the template and compares it with the selector of every directive and component in scope. The comparison covers the element name, its static attributes, and the names of its bindings. Each match creates one directive instance for that element.
Because the match depends on the selector, selector design controls where a directive can be used. These are the common forms.
| Selector | Matches |
|---|---|
| `[appHighlight]` | Any element with the attribute `appHighlight` |
| `p[appHighlight]` | Only `<p>` elements with the attribute |
| `[appHighlight]:not(button)` | Any element with the attribute except `<button>` |
| `[appHighlight], [appMark]` | Elements with either attribute |
| `input[appHighlight][type=text]` | Only text inputs that carry the attribute |
An attribute selector matches in three template forms. <p appHighlight> and <p appHighlight="red"> match as static attributes. <p [appHighlight]="color"> matches as a property binding. The directive's class is the same in all three cases. What differs is whether Angular can pass a value to it, which depends on inputs. Inputs are covered in a later chapter.
Pick the narrowest selector that is still correct. A directive that calls focus() on its host has no meaning on a <div>. Writing input[appAutofocus], textarea[appAutofocus] lets the template compiler refuse the attribute on other elements. The elements are then not matched, though, so the compiler does not warn about the unmatched attribute. See the next section.
Failure mode: the silent no-op
Standalone scoping does not cascade. A component's imports apply only to its own template. A child component that appears in that template does not inherit them.
import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-child',
template: `<p appHighlight>Not highlighted</p>`,
})
export class ChildComponent {}
@Component({
selector: 'app-parent',
imports: [HighlightDirective, ChildComponent],
template: `
<p appHighlight>Highlighted</p>
<app-child />
`,
})
export class ParentComponent {}The first paragraph is highlighted. The paragraph inside ChildComponent is not, and Angular reports no error. To the child's template compiler, appHighlight is an ordinary HTML attribute with an empty value, and unknown plain attributes are legal HTML. The fix is to add HighlightDirective to ChildComponent's own imports.
When you write [appHighlight]="color" instead, a missing import is loud. Angular treats the bracket form as a property binding and checks that the property exists on the element:
NG8002: Can't bind to 'appHighlight' since it isn't a known property of 'p'.This difference matters when you debug. If a directive that is applied as a bare attribute does nothing, check the imports array of the component whose template contains the element, and then check the selector spelling. Do this before you look at the directive's code.
Importing several directives
Each standalone directive, component, and pipe goes into imports by its class name. For a feature that uses many directives, you can group them in a constant. Angular accepts arrays, including nested ones, in imports.
import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
import { HoverDirective } from './hover.directive';
export const DECORATION_DIRECTIVES = [HighlightDirective, HoverDirective] as const;
@Component({
selector: 'app-note',
imports: [DECORATION_DIRECTIVES],
template: `<p appHighlight appHover>Two directives on one element</p>`,
})
export class NoteComponent {}Keep these groups small and cohesive. A constant named SHARED that holds thirty unrelated items hides what each template depends on, and Angular cannot warn you about any single unused entry in it.
Angular 19 and later include an extended diagnostic that warns when an entry in imports is not used in the template (NG8113). Treat that warning as a prompt to delete the import. It keeps each component's dependency list accurate.
If you have an older component that is still declared in an NgModule, put the standalone directive in that module's imports array, not in declarations. A standalone directive cannot be declared in a module.
import { NgModule } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
import { LegacyWidgetComponent } from './legacy-widget.component';
@NgModule({
declarations: [LegacyWidgetComponent],
imports: [HighlightDirective],
})
export class LegacyWidgetModule {}Applying to elements, components, and more than one directive
An attribute directive can attach to any element that matches its selector, including the host element of a component.
import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-badge',
template: `<ng-content />`,
})
export class BadgeComponent {}
@Component({
selector: 'app-profile',
imports: [HighlightDirective, BadgeComponent],
template: `<app-badge appHighlight>New</app-badge>`,
})
export class ProfileComponent {}Here the directive's host is the <app-badge> element itself, not anything inside BadgeComponent's template. The directive and the component are separate instances that sit on one element. The directive can set styles on <app-badge> but cannot see inside the badge's template. BadgeComponent does not need to know about HighlightDirective, and the import goes in ProfileComponent, the component whose template contains the attribute.
Several directives can share an element, as in the earlier appHighlight appHover example. Each gets its own instance. Do not depend on the order in which they run. If two directives write the same style property, the result is hard to predict, so give each directive its own concern.
Directives also work inside control flow blocks such as @if and @for. Angular creates a directive instance each time the block creates the element, and destroys it when the element is removed.
import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-list',
imports: [HighlightDirective],
template: `
@for (item of items; track item) {
<li appHighlight>{{ item }}</li>
}
`,
})
export class ListComponent {
items = ['alpha', 'beta', 'gamma'];
}This renders three <li> elements and three separate HighlightDirective instances. One import covers all of them.
Choosing a prefix and checking the setup
The app prefix in appHighlight is a convention that prevents collisions with native attributes and with directives from libraries. Pick a prefix per project and apply it consistently. Never use ng, which belongs to Angular. The CLI's ng generate directive highlight command applies the project prefix from angular.json and creates a standalone directive for you.
When a directive does not seem to apply, check these in order:
- Is the class in the
importsarray of the component that owns this template, and not only in its parent? - Does the attribute spelling match the selector exactly, including capitalization? Selectors are case-sensitive, so
apphighlightdoes not matchappHighlight. - Does the element type match the selector?
p[appHighlight]ignores a<div appHighlight>. - Does the browser's element inspector show the attribute on the element? A directive that is applied through a plain attribute leaves the attribute in the DOM. A bound form such as
[appHighlight]does not add an attribute by itself.
Summary of the rules
- A directive runs only when it is in the
importsof the component that owns the template, and the element matches its selector. - Imports are not inherited by child components. Each component imports what its own template uses.
- A bare attribute with a missing import fails silently. A bound attribute with a missing import raises NG8002.
- The host element is the element that carries the attribute. For a component tag, that is the component's host element.
- Narrow selectors document intent and limit misuse.
Exercise
A teammate adds <p appHighlight>Hello</p> to the template of InfoComponent, which is rendered inside PageComponent. PageComponent imports HighlightDirective, and InfoComponent does not. The paragraph is not highlighted, and the console shows no error. Explain why, and give the fix.
Show answer
Standalone imports apply only to the template of the component that lists them. InfoComponent's template is compiled on its own, and it does not inherit PageComponent's imports. Because appHighlight is written as a plain attribute, Angular treats it as an ordinary HTML attribute and raises no error. The fix is to add HighlightDirective to the imports array of InfoComponent.
Exercise
You write a directive with the selector input[appAutofocus]. Which of these elements receive an instance of the directive: <input appAutofocus>, <textarea appAutofocus>, <input>, <input [appAutofocus]="true">? Assume the directive is imported and has no inputs.
Show answer
Only <input appAutofocus> matches. <textarea appAutofocus> fails the input part of the selector, and <input> has no attribute. <input [appAutofocus]="true"> matches the selector, since an attribute selector matches a bound property name too. But the directive declares no input named appAutofocus, so the compiler reports NG8002 because it cannot bind to that property.