Building custom attribute directive
Using the Angular CLI, run the following command, where special is the name of the directive:
ng generate directive directives/special --skip-tests=true
Angular creates the directive class and specifies the CSS selector, appUnless, that identifies the directive in a template.
Import ElementRef
from @angular/core
. ElementRef
grants direct access to the host DOM element through its nativeElement
property.
Add ElementRef
in the directive’s constructor()
to inject a reference to the host DOM element, the element to which you apply appSpecial
.
Add logic to the HighlightDirective
class that sets the background to pink.
@Directive({
selector: '[appSpecial]',
standalone: true
})
export class SpecialDirective {
constructor(private el: ElementRef) {
this.el.nativeElement.style.color = 'deeppink';
}
}
<mat-card-title appSpecial>{{cardTitle}}</mat-card-title>
Handling user events
Let’s apply the color deeppink when an element is hovered.
Add two event handlers that respond when the mouse enters or leaves, each with the @HostListener()
decorator.
@HostListener()
declares a DOM event to listen for, and provides a handler method to run when that event occurs. Angular invokes the supplied handler method when the host element emits the specified event, and updates the bound element with the result.
@Directive({
selector: '[appSpecial]',
standalone: true
})
export class SpecialDirective {
private readonly el = inject(ElementRef);
@HostListener('mouseenter') onMouseEnter(): void {
this.applySpecialColor('deeppink');
}
@HostListener('mouseleave') onMouseLeave(): void {
this.applySpecialColor('');
}
private applySpecialColor(color: string): void {
this.el.nativeElement.style.color = color;
}
}