70. Host Bindings and Host Listeners
While related to directives, HostBinding and HostListener can also be used directly within a Component class to manage properties and events on the component's host element (<app-my-component>).
1. @HostBinding (Modifying Host Properties)
Used to programmatically add classes, attributes, or styles to the component's custom tag itself.
Example: Setting an attribute on the host element for CSS selection.
typescript @Component({ selector: 'app-selectable-item', template: '...' }) export class SelectableItemComponent { isActive: boolean = false;
// Bind the 'class.active' property of the host element @HostBinding('class.active') get activeClass() { return this.isActive; }
// Bind an attribute value @HostBinding('attr.role') role = 'button';
toggleActive() { this.isActive = !this.isActive; } }
If isActive is true, the host element becomes <app-selectable-item class="active">.
2. @HostListener (Listening to Host Events)
Used to listen for events that happen on the host element, useful for interactions like drag-and-drop or global keyboard shortcuts.
Example: Listening for a global keydown event.
typescript @Component({ /* ... */ }) export class ShortcutComponent {
// Listen for the 'keydown' event anywhere on the window @HostListener('window:keydown', ['$event']) handleKeydown(event: KeyboardEvent) { if (event.key === 'Escape') { console.log('Escape key pressed globally!'); // Close a modal, for example } } }
Host listeners are an extremely useful tool for creating reusable UI logic related to mouse, keyboard, or focus management.