62. Custom Directives (Structural and Attribute)
We've used built-in directives like NgIf and NgClass. Now we learn to create our own to abstract common DOM manipulation or UI logic.
1. Custom Attribute Directives
Attribute directives change the appearance or behavior of an existing element.
Example: Highlight Directive
typescript // highlight.directive.ts import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({ selector: '[appHighlight]' // Selector used in HTML:
}) export class HighlightDirective {
// Input property to set the color dynamically @Input('appHighlight') highlightColor: string = 'yellow';
constructor(private el: ElementRef) { }
// Use HostListener to listen to events on the host element @HostListener('mouseenter') onMouseEnter() { this.highlight(this.highlightColor); }
@HostListener('mouseleave') onMouseLeave() { this.highlight(''); }
private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } }
Usage:
html
Hover over this text.
2. Custom Structural Directives
Structural directives (*) modify the DOM structure, requiring interaction with TemplateRef and ViewContainerRef.
We will dedicate the next lesson to building a custom structural directive (*NgIf-like) as it is significantly more complex.