Custom Attribute Directive With Event Handler
* A Custom Attribute Directives can listen into an event and act
accordingly which extends custom directive features.
Implementing Event Handler
* Continuing with last
example we have discussed (Part-16), text will be highlighted and
bold based on an event fires with help of HostListener from angular/core
library.
* HostListener is a decorator,
which defines a DOM element with event to run when the event occurs.
For more details
visit: https://angular.io/api/core/HostListener
* @HostListener() takes 2 arguments:.
1. eventName
2. args?
app.component.html
<div>
<div appElementHighlighter>This tutorial elaborates custom directive</div>
<br />
<p appElementHighlighter>This is SKMDotNet Tutorial.</p>
</div>
app.component.ts
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appElementHighlighter]'
})
export class ElementHighlighterDirective {
constructor(private er: ElementRef) { }
@HostListener('mouseenter') onMouseEnter() {
this.takeEffect('yellow');
};
@HostListener('mouseleave') onMouseLeave() {
this.takeEffect(null);
};
private takeEffect(colorType: string) {
this.er.nativeElement.style.backgroundColor = colorType;
this.er.nativeElement.style.fontWeight = 'bold';
}
}