Friday, July 16, 2021

Angular @HostListener Decorator With Examples

@HostListener decorator in Angular is used to declare a DOM event (like click, mouseenter) to listen for and define a handler method to execute when that event occurs. This decorator is quite useful to listen to events emitted by hostelement when creating a custom directive.

There are two options that you can pass with the @HostListener decorator-

  • eventName- The DOM event to listen for. It is of type string.
  • args- A set of arguments to pass to the handler method when the event occurs. It is of type string[].

For example

@HostListener('click', ['$event.target'])

Here 'click' is the event name.

['$event.target'] is the args parameter which will be passed to the handler method.

@HostListener Angular example

1. In this example we’ll create a custom directive that changes the background color of the host element when the mouseenter and mouseleave events happen.

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

@Directive({
  selector: '[appCustomdirective]'
})
export class CustomdirectiveDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) { }

  @HostListener('mouseenter') onMouseEnter() {
    this.highLight('yellow');
  }
  
  @HostListener('mouseleave') onMouseLeave() {
    this.highLight('');
  }

  private highLight(color : string){
    this.renderer.setStyle(this.el.nativeElement,'backgroundColor',color);
  }
}

As you can see using @HostListener we have decorated two handler methods onMouseEnter() and onMouseLeave() which are executed when 'mouseenter' and 'mouseleave' events occur in the host element.

Now let’s use this custom directive. Add the following in app.component.html. Here <span> is the host element which is using our custom directive as an attribute.

<p>This content is highlighted using a <span appCustomdirective>custom directive</span></p>

2. In this example we’ll create a custom directive that attaches a click listener to a button and counts clicks.

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

@Directive({
    selector: 'button[counting]'
})
export class CountClickDirective {
    numberOfClicks = 0;

    @HostListener('click', ['$event.target'])
    onClick(btn) {
      console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
    }
}

As you can see here onClick(btn) is the method which will be executed when the click event occurs in the host element. Also notice that a directive with 'button[counting]' selector, would be instantiated only on the <button counting> element.

To use this custom directive we’ll add a button element in app.component.html

<p>Get the count of button clicks</p>
<button counting>Increment</button>
Angular @HostListener Decorator

Reference: https://angular.io/api/core/HostListener

That's all for this topic Angular @HostListener Decorator With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Angular @HostBinding Decorator With Examples
  2. Angular @Output() Decorator With Examples
  3. How to Create a Custom Attribute Directive in Angular
  4. How to Create a Custom Structural Directive in Angular
  5. NgNonBindable Directive in Angular

You may also like-

  1. Navigate to a Route Programmatically in Angular
  2. Highlight Currently Selected Menu Item Angular Routing Example
  3. Angular Form setValue() and patchValue()
  4. Angular HttpClient - Set Response Type as Text
  5. Insertion Sort Program in Java
  6. Can we Start The Same Thread Twice in Java
  7. Spring Transaction Management Example - @Transactional Annotation and JDBC
  8. Check String Empty or Not in Python

No comments:

Post a Comment