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.
- 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'); }
- 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'); }
- 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'); }
- 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.