javascript / intermediate
Snippet
HostBinding and HostListener
These decorators allow a directive to interact with its host element without direct DOM manipulation. HostBinding links a property of the host to a class property, while HostListener attaches event listeners to the host.
snippet.js
1
2
3
4
5
6
7
8
@Directive({ selector: '[appActive]', standalone: true })export class ActiveDirective {@HostBinding('class.is-active') isActive = false;@HostListener('click') toggle() {this.isActive = !this.isActive;}}
angular
Breakdown
1
@HostBinding('class.is-active')
Dynamically adds or removes the 'is-active' CSS class on the host element.
2
@HostListener('click')
Listens for 'click' events on the host and executes the toggle method.