‘HostListener‘ and ‘HostBinding‘ are decorators in Angular that allow you to manipulate or react to events and properties on the host element of a directive or component. They make it easy to bind host element properties and events in a declarative way, without any direct manipulation of DOM elements.
1. **HostListener**: The ‘HostListener‘ is a decorator that listens for an event on the host element of a component or directive. When the event occurs, it calls the specified method with the event data. It’s a great way to handle events without directly manipulating the DOM.
Here’s an example:
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appCustomClick]'
})
export class CustomClickDirective {
@HostListener('click', ['$event'])
onClick(event) {
alert('You clicked the element at position: (' + event.clientX + ', ' + event.clientY + ')');
}
}
In this example, the ‘@HostListener‘ listens for the ‘click‘ event and calls the ‘onClick‘ method with the event object when the event is triggered.
2. **HostBinding**: The ‘HostBinding‘ is a decorator that allows you to bind a host element’s property to a property of your component or directive class. This helps in setting the host element’s properties directly from the directive or component without any direct manipulation of the DOM.
Here’s an example:
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor') bgColor: string;
@HostListener('mouseenter')
onMouseEnter() {
this.bgColor = 'yellow';
}
@HostListener('mouseleave')
onMouseLeave() {
this.bgColor = null;
}
}
In this example, the ‘@HostBinding‘ decorator binds the host element’s ‘style.backgroundColor‘ property to the ‘bgColor‘ property of the directive. The ‘@HostListener‘ decorators listen for ‘mouseenter‘ and ‘mouseleave‘ events and update the ‘bgColor‘ property accordingly which then updates host element’s background color.
In summary, ‘HostListener‘ and ‘HostBinding‘ provide a clean and declarative way to interact with the host element of a directive or component in Angular, which can otherwise involve manual DOM manipulation.