Problem Statement
When do you create a custom attribute directive and what does it look like?
Explanation
Create an attribute directive when multiple components need the same DOM behavior (e.g., highlight on hover). The directive gets the host element via ElementRef/Renderer2 and responds to HostListener events. Use @Input to pass configuration.
Code Solution
SolutionRead Only
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
@Input() appHighlight = 'yellow';
constructor(private el: ElementRef, private r: Renderer2) {}
@HostListener('mouseenter') on() { this.r.setStyle(this.el.nativeElement,'background',this.appHighlight); }
@HostListener('mouseleave') off() { this.r.removeStyle(this.el.nativeElement,'background'); }
}