HostListener

"@HostListener" is a decorator in Angular that allows you to listen for events on the directive or component host element. The host element is the element to the directive or component is attached. The "@HostListener" decorator is often used in Angular to handle DOM events or custom events on the host element.

Here's an example of how you can use "@HostListener" in an Angular component.

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

@Component({
  selector: 'app-my-component',
  template: '<div>Hover over me</div>',
})
export class MyComponent {
  @HostListener('mouseenter') onMouseEnter() {
    // This method is called when the mouse enters the host element
    console.log('Mouse entered');
  }

  @HostListener('mouseleave') onMouseLeave() {
    // This method is called when the mouse leaves the host element
    console.log('Mouse left');
  }
}

In this example:

- "@HostListener('mouseenter')" is applied to the "onMouseEnter" method. This means that when the mouse enters the host element, the onMouseEnter method will be called.
- "@HostListener('mouseleave')" is applied to the "onMouseLeave" method. This means that when the mouse leaves the host element, the onMouseLeave method will be called.

The @HostListener decorator supports various events like 'click', 'keyup', 'window:resize', custom events, etc.

@HostListener('click', ['$event'])
onClick(event: MouseEvent) {
  // This method is called when a click event occurs on the host element
  console.log('Clicked', event);
}

@HostListener('window:resize', ['$event'])
onResize(event: Event) {
  // This method is called when the window is resized
  console.log('Window resized', event);
}

In the examples above, the "@HostListener" decorator is applied to methods that handle specific events on the host element. It provides a convenient way to bind event listeners to the host element in Angular components or directives.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....