An attribute directive is an Angular class that changes the appearance or behavior of one existing HTML element without changing document structure. Apply it as an attribute selected with CSS-selector syntax; use structural directives when the layout itself must change. section 14.0 section 14.8
Custom attribute directives provide a focused extension point for element behavior:
- Define a class with the @Directive decorator and a selector such as [pa-attr]. section 14.2
- Receive the host element through ElementRef, then inspect or modify its browser DOM representation. section 14.2
- Add @Input properties for data, ngOnChanges for input updates, @Output for custom events, and @HostBinding or @HostListener for host bindings and events. section 14.0
- Export directive functionality for template variables with the exportAs property. section 14.0
Applying a class-changing directive
A directive with selector [pa-attr] matches any element carrying the pa-attr attribute. Its constructor receives ElementRef and adds the table-success and fw-bold classes through nativeElement.classList. A data-bound version can instead receive a class through @Input("pa-attr") and replace the previous class when the input changes. section 14.2 section 29.5
Table 14.1. Putting attribute directives in context
|
Question
|
Answer
|
|
What are they?
|
Attribute directives are classes that can modify the behavior or appearance of the element they are applied to. The style and class bindings described in chapter 10 are examples of attribute directives.
|
|
Why are they useful?
|
The built-in directives cover the most common tasks required in web application development but don’t deal with every situation. Custom directives allow application-specific features to be defined.
|
|
How are they used?
|
Attribute directives are classes to which the
@Directive decorator has been applied. They are enabled in the
directives property of the component responsible for a template and applied using a CSS selector.
|
|
Are there any pitfalls or limitations?
|
The main pitfall when creating a custom directive is the temptation to write code to perform tasks that can be better handled using directive features such as input and output properties and host element bindings.
|
|
Are there any alternatives?
|
Angular supports two other types of directive—structural directives and components—that may be more suitable for a given task. You can sometimes combine the built-in directives to create a specific effect if you prefer to avoid writing custom code, although the result can be brittle and lead to complex HTML that is hard to read and maintain.
|
Use the context table to compare what attribute directives are, why built-in directives are insufficient for every application, how selectors apply them, and where custom-directive pitfalls begin. section 14.0
