Angular 2 @HostBinding vs @HostListener




Asked on June 21, 2017
What is difference between @HostBinding and @HostListener in Angular 2?



Replied on July 04, 2017
@HostBinding 
When there is parent-child component, it is used bind CSS property and animation trigger to host element such as

@HostBinding('@roundAntiClockTrigger') roundAntiClockTrigger = 'in'; 
@HostBinding('style.display')   display = 'block';
@HostBinding('style.position')  position = 'absolute'; 


@HostListener 
It listens event. We can use it in creating custom directives.

@Directive({ 
     selector: '[defColOnEvent]' 
})
export class DefaultColorOnEventDirective {
   constructor(private elRef: ElementRef) { 
   }
   @HostListener('mouseover') onMouseOver() {
     this.changeColor('red');
   }
   @HostListener('mouseleave') onMouseLeave() {
     this.changeColor('black');
   }
   private changeColor(color: string) {
     this.elRef.nativeElement.style.color = color;
   }  


Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us