Understanding the @HostListener Decorator in Angular

Posted by


What is @HostListener decorator in Angular?

The @HostListener decorator in Angular is used to listen for events on the host element in a directive. It allows you to specify a function that should be called when a particular event occurs on the host element.

When creating a custom directive in Angular, you can use the @HostListener decorator to listen for events such as click, mouseover, keydown, etc. This is useful for adding custom functionality to elements based on user interactions.

Here’s an example of how the @HostListener decorator is used in Angular:

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

  @Directive({
    selector: '[appCustomDirective]'
  })
  export class CustomDirective {
    @HostListener('click', ['$event'])
    onClick(event: MouseEvent) {
      // Do something when the host element is clicked
    }
  }
  
  

In this example, we have a custom directive called appCustomDirective and we have used the @HostListener decorator to listen for the click event on the host element. When the host element is clicked, the onClick function will be called, and we can perform any custom logic inside this function.

The @HostListener decorator provides a convenient way to add event listeners to the host element of a directive without having to manually add event listeners in the component’s code.

This decorator is commonly used in Angular applications to create custom directives that enhance the behavior of HTML elements based on user interactions.