Sub topic 1
What Attribute Directives Are and When to Use Them
Prerequisites
Assume you know TypeScript classes and decorators, Angular components and templates, standalone components, and basic property and event binding.
Attribute directives
An attribute directive is a class that adds behavior or presentation to an existing element or component. Its selector looks like an HTML attribute, such as [appHighlight]. The directive does not own a template. It works with the host element, which is the element where the directive appears.
Use an attribute directive when the behavior should be reusable across different elements. Examples include highlighting, adding keyboard behavior, tracking focus, or showing validation state.
A component owns a template. A structural directive changes which elements exist. An attribute directive changes an existing host without replacing its template.
Declaring a directive: `@Directive` and the attribute selector
The @Directive decorator supplies the directive metadata. The selector [appHighlight] matches an element containing an appHighlight attribute.
import { Directive } from '@angular/core';
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {}The class is now a directive, but it has no behavior yet. You can add behavior by injecting services, reading inputs, listening for host events, or binding host properties.
Using the directive in a standalone component
A standalone component must import a standalone directive before its template can use the directive. Add the directive to the component's imports array, then place its selector on an element.
import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-demo',
imports: [HighlightDirective],
template: `
<p appHighlight>This paragraph uses the directive.</p>
`,
})
export class DemoComponent {}Angular creates one HighlightDirective instance for that paragraph. The paragraph remains responsible for its content, while the directive can add reusable behavior to it.
Exercise
Should a directive or a component implement reusable behavior that changes an existing paragraph without supplying new markup?
Show answer
Use an attribute directive, because it enhances the existing host element and does not own a template.