What Are @HostBinding() and @HostListener() in Angular 8?

Priti Jha
2 min readJan 21, 2020

--

@HostListener() function decorator allows you to handle events of the host element in the directive class. makes it super easy to handle events raised in the host element inside the directive class.

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);
}
}

this.border = ‘5px solid yellow’;
}

changeBackgroundColor(color: string){
this.renderer.setElementStyle(this.ele.nativeElement, ‘color’, color);
}
}

--

--

Priti Jha
Priti Jha

Written by Priti Jha

Senior front-end developer writing about Angular 8 , Ionic Framework ,Javascript, HTML, Css and all front end technology.

Responses (2)