What are the HostListener decorators and the HostBinding decorator doing in this directive?

@Directive({
    selector: ‘[appCallout]’
})
export class CalloutDirective {
    @HostBinding(‘style.font-weight’) fontWeight = ‘normal’;
    @HostListener(‘mouseenter’)
    onMouseEnter() {
        this.fontWeight = ‘bold’;
    }
    @HostListener(‘mouseleave’)
    onMouseLeave(){
        this.fontWeight = ‘normal’;
    }
}
  •  They are setting the CalloutDirective.fontWeight field based on whether or not the mouse is over the DOM element. The HostListener then sets the font-weight CSS property to the fontWeight value.
  •  They are setting up the directive to check the DOM element that it is on. If it has event bindings added for mouse enter and leave it will use this code. Otherwise nothing will happen.
  •  This is an incorrect use of HostListener and HostBinding. The HostListener and HostBinding decorators do not do anything on directives; they work only when used on components.
  •  If the DOM element that this directive is placed on has the CSS property font-weight set on it, the mouseenter and mouseleave events will get raised.

Leave a Reply

Your email address will not be published. Required fields are marked *