Web
Analytics
@HostBinder and @HostListner Example in angular 2|4|5|6|7 | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

@HostBinder and @HostListner Example in angular 2|4|5|6|7

@Hostbinder and @Hostlistner are used to define custom directives using @Hostbinding and javascript events using @HostListner. So let me demonstrate it with an simple example.

Step1: Create new custom directive by following terminal command

ng g d mydirective

Step2. Add Following code into newly created directive

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

@Directive({
  selector: '[appMydirective]'
})
export class MydirectiveDirective {
  // First Way to set background color and default value which is red in this case
  @HostBinding('style.backgroundColor') backcolorColor: string = 'red';
    constructor(private el: ElementRef, private renderer: Renderer) {
      // Second way to change stye of host element
      this.ChangeBgColor('aqua');
  }

 // Register click event on hostelement
  @HostListener('click') addcolor() {
    this.backcolorColor ='yellow';
  }
  ChangeBgColor(color: string) {
    // Change Font color and size
    this.renderer.setElementStyle(this.el.nativeElement, 'color', color);
    this.renderer.setElementStyle(this.el.nativeElement , 'font-size','24px');
}
}

Step 3:  Add Following code into app.component.html

<div style="text-align:center">
  <div appMydirective>
    <h3>{{title}}</h3>
</div>
<input type="button" value="Click Here" appMydirective>
 <div class="myclass" appMydirective>
   MyCLass Div
 </div>
 
</div>