HostListener Decorator

Overview

@HostListener, allows you to easily listen for events on the host element of a directive or component. In this article, we will dive deep into the world of @HostListener, understanding its usage and providing code examples to illustrate its power.

What is @HostListener?

The @HostListener decorator is a feature of Angular that enables you to listen for events on the host element where a directive or component is applied. It allows you to respond to user interactions or changes in the host element's state and execute custom logic accordingly.

By using @HostListener, you can make your directives and components more interactive and responsive, enhancing the overall user experience of your application.

Basic Usage of @HostListener

To use the @HostListener decorator, you will need to import it from @angular/core. Here's a basic example of how it works:

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

@Directive({
  selector: '[appMyDirective]'
})
export class MyDirective {
  @HostListener('mouseenter') onMouseEnter() {
    // Your custom logic when the host element is hovered
  }

  @HostListener('click', ['$event']) onClick(event: MouseEvent) {
    // Your custom logic when the host element is clicked
  }
}

In this example, we have created a custom directive called appMyDirective. We have added two @HostListener decorators to it:

  1. The first listens for the mouseenter event, and when triggered, it executes the onMouseEnter function, allowing you to define custom logic for when the host element is hovered.
  2. The second listens for the click event and passes the event object to the onClick function. This enables you to access the event properties and execute custom logic when the host element is clicked.

Using @HostListener with Custom Directives

The power of @HostListener becomes evident when you use it with custom directives. Let's create a custom attribute directive that highlights an element when hovered over:

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

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

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.removeStyle(this.el.nativeElement, 'background-color');
  }
}

In this example, we have created the HighlightDirective. It uses @HostListener to respond to mouseenter and mouseleave events on the host element. When the mouse enters, the background color of the element turns yellow, and when it leaves, the background color is removed.

Using @HostListener with Components

You can also use @HostListener in components. Here's an example of a simple component that listens for windows resize events:

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

@Component({
  selector: 'app-resize-listener',
  template: '<p>Window width: {{ windowWidth }}</p>'
})
export class ResizeListenerComponent {
  windowWidth: number;

  @HostListener('window:resize', ['$event'])
  onResize(event: Event): void {
    this.windowWidth = window.innerWidth;
  }
}

In this example, the ResizeListenerComponent listens for the window:resize event using @HostListener. When the window is resized, the onResize function is called, and it updates the windowWidth property with the current window width.