How do you build a custom attribute directive?
Model answer
Use @Directive with a selector in square brackets, such as [appHighlight]. Inject ElementRef to reach the host element, and use host bindings or listeners to react: in the decorator's host option, 'mouseenter' can call a method that changes the background colour.
Inputs let you configure it: [appHighlight]="'yellow'". Directives are good for reusable behaviour such as autofocus, click-outside, or tooltips, without changing the component.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- What is a directive? What are the types?
- What is the difference between ngClass and ngStyle, and how do they compare with class and style bindings?
- What is a pipe? Name some built-in pipes.
- How do you create a custom pipe? What is the difference between pure and impure pipes?
- What does the async pipe do, and why is it recommended?
- What is the difference between providedIn root and providing a service in a component?