javascript / intermediate
Snippet
Dynamic Attribute Binding with HostBinding
HostBinding allows you to link a component or directive property directly to an attribute, class, or style of the host element. Combined with HostListener, it enables interactive UI logic without manual DOM manipulation.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
@Directive({ selector: '[appHighlight]' })export class HighlightDirective {@HostBinding('style.backgroundColor') bgColor = 'transparent';@HostListener('mouseenter') onEnter() {this.bgColor = 'yellow';}@HostListener('mouseleave') onLeave() {this.bgColor = 'transparent';}}
angular
Breakdown
1
@HostBinding('style.backgroundColor')
Binds the class property 'bgColor' to the background-color CSS style of the host element.
2
@HostListener('mouseenter')
Listens for the mouseenter event on the host and triggers the following method.