Host Listener In Angular

What is @HostListner in Angular:

@HostListener() Decorator in Angular allows us to handle events of the host element in the directive class.

There is Multiple Event we can Listen and manipulate Don Using @HostListener Here we will see some of the Examples.

To use @Hostlistener in a respective component first we need to import in component from @angular/core.

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

Now we can ready to use HostListner in the Component TypeScript file.

Here are Some Basic Examples of HostListner We can Use.

  1. Mouse Over Listener
    @HostListener('mouseover') onMouseOver() {
     // Here we will write the code what we want to do on this particular event or call the class to perform changes
      this.ChangeBgColor('red'); 
    }
  2. Click Listener
    @HostListener('click') onClick() {
      // Here we will write the code what we want to do on this particular event or call the class to perform changes
        window.alert('Host Element Clicked');
    }
  3. Mouse leave Listener
    @HostListener('mouseleave') onMouseLeave() {
    // Here we will write the code what we want to do on this particular event or call the class to perform changes
         this.ChangeBgColor('black');
    }
  4. Window Resize
    @HostListener('window:resize', ['$event'])
    onResize(event) {
    // Here we will write the code what we want to do on this particular event or call the class to perform changes
      event.target.innerWidth;
    }

     

This way we can achieve HostListener decorator in our TypeScript and Perform some Action.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories