HostBinding and HostListener in Angular

Both the decorators @HostBinding() and @HostListener() are used in custom directives. Let’s check some highlights of directives. Directives are useful to change the appearance, behavior, structure, and layout of the DOM elements. There are three types of Directives available in angular.

  • Component – Directive with a template
  • Structural – Directive that changes structure or layout of DOM
  • Attribute – directive that changes appearance or behaviour of DOM

Let’s see an example of a custom directive.

<h1 appBackground> This is a Heading </h1>
import { Directive, ElementRef, Renderer2, HostBinding } from '@angular/core';

@Directive({
  selector:'[appBackground]'
})
export class BackgroundDirective {
  constructor(private el: ElementRef, private re: Renderer2) {
    this.re.setStyle(this.el.nativeElement, 'background', 'lightgrey');
  }
}

HostBinding

Using @HostBinding decorator we can access and set any property of actual DOM element from the directive.

import { Directive, HostBinding } from '@angular/core';

@Directive({
  selector:'[appBackground]'
})
export class BackgroundDirective {
  @HostBinding('style.backgroundColor') bgColor: string;
  constructor() {
   this.bgColor = 'lightgrey';
  }
}

To access the property of the host element, we need to pass the property name to @HostBinding and need to define a typescript property for the same.

HostListener

Using @HostListener decorator we can listen and handle the events of the actual DOM element in the directive class.

import { Directive, HostBinding, HostListener } from '@angular/core';

@Directive({
  selector:'[appSize]'
})
export class SizeDirective {
  @HostBinding('style.fontSize') fontSize: string;
  @HostListener('mouseover') onHover = () => {
      this.fontSize = '40px';
  };
  @HostListener('mouseleave') onLeave = () => {
      this.fontSize = '';
  };
}

To access the event of the host element, we need to pass the required event name to @HostListener and we need to define an event handler for the same.

Leave a Reply

Your email address will not be published. Required fields are marked *