Through the use of @HostBinding and @HostListener in custom Directives and Components, it is possible to interact directly with the host element, which is the DOM element to which your Custom Directive or Component is applied. Both of these features offer a declarative approach to binding to host properties and listening for host events, among other things.
@HostBinding(hostPropertyName) binds Directive or Component class properties to host element properties. The host element property updates when the class property changes.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('class.highlighted') // Bind to the 'highlighted' CSS class of the host
isHighlighted = false;@HostBinding('style.backgroundColor') // Bind to the 'backgroundColor' style of the host
backgroundColor: string | null = null;constructor() {
// You can control these properties based on logic
setTimeout(() => {
this.isHighlighted = true;
this.backgroundColor = 'lightblue';
}, 1000);setTimeout(() => {
this.backgroundColor = 'lightgreen';
}, 2000);
}
}
Apply the directive to an HTML element in your template:
<div appHighlight>This div will be highlighted and have a background color.</div>
Custom Directives and Components @HostListener
@HostListener(eventName, args?) lets you listen for host element events in your Directive or Component and execute a class method.'
import { Directive, HostListener, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appLogClicks]'
})
export class LogClicksDirective {
constructor(private el: ElementRef) {}@HostListener('click', ['$event'])
onClick(event: MouseEvent) {
console.log('Host element clicked!', this.el.nativeElement, event);
}@HostListener('mouseenter')
onMouseEnter() {
console.log('Mouse entered the host element.');
}
}
@HostListener('click', ['$event']): This tells Angular to listen for host element click events and call onClick with the $event object.
Apply the directive to an HTML element:
<button appLogClicks>Click Me to Log</button>
<div appLogClicks>Hover over me to log.</div>