@HostBinding
and @HostListener
are two decorators in Angular that can be really useful in custom directives. @HostBinding
lets you set properties on the element or component that hosts the directive, and @HostListener
lets you listen for events on the host element or component.
Letβs take the real time scenario: when mouse over the host element, only the color of the host element should change. In addition, when the mouse is gone, the color of the host element should change to its previous or else default color. So to do this, we need to handle events raised on the host element in the directive class. In Angular, you do this using @HostListener()
.
To understand @HostListener()
in a better way, consider another simple scenario: on the click of the host element, you want to show an alert window. To do this in the directive class, add @HostListener()
and pass the event βclickβ to it. Also, associate a function to raise an alert as shown in the listing below:
@HostListener(βclickβ) onClick() {
window.alert(βHost Element Clickedβ);
}
Letβs go back to our requirement change the color to red only when the mouse is hovering, and when itβs gone, the color of the host element should change to black.
To do this, you need to handle the mouseenter
and mouseexit
events of the host element in the directive class.
@HostBinding()
function decorator allows you to set the properties of the host element from the directive class.
Letβs say you want to change the style properties such as height, width, color, margin, border,
etc., or any other internal properties of the host element in the directive class. Here, youβd need to use the @HostBinding()
decorator function to access these properties on the host element and assign a value to it in directive class.
@HostBinding(βstyle.borderβ) border: string;
Complete Example:-
import {Directive, ElementRef, Renderer, HostListener, HostBinding} from β@angular/coreβ;
@Directive({
selector: β[appChbgcolor]β
})
export class ChangeBgColorDirective {
constructor(private ele: ElementRef, private renderer: Renderer){
//this.ChangeBgColor(βredβ);
}
@HostBinding(βstyle.borderβ) border: string;
@HostListener(βmouseoverβ) onMouseOver() {
this.changeBackgroundColor(βredβ);
this.border = β5px solid greenβ;
}
@HostListener(βclickβ) onClick() {
window.alert(βElement clicked!β);
}
@HostListener(βmouseleaveβ) onMouseLeave() {
this.changeBackgroundColor(βgreenβ);
this.border = β5px solid yellowβ;
}
changeBackgroundColor(color: string){
this.renderer.setElementStyle(this.ele.nativeElement, βcolorβ,
color);
}
}
Cheers!!!
Top comments (0)