DEV Community

Cover image for Angular Custom Directives - @HostBinding and @HostListener
manoj
manoj

Posted on • Edited on

Angular Custom Directives - @HostBinding and @HostListener

@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’);
}
Enter fullscreen mode Exit fullscreen mode

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 mouseexitevents 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;
Enter fullscreen mode Exit fullscreen mode

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);
 }
}
Enter fullscreen mode Exit fullscreen mode

Cheers!!!

Top comments (0)