Table of contents
In this blog I am going to explain the different use cases of
- HostBinding
- HostListener
1. HostBinding
Let me justify my statement with an example
highlight.directive.ts
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor') backgroundColor : string = 'yellow';
@HostBinding('style.cursor') cursor : string = 'pointer';
app.component.html
<div class="container">
<div class="col-xs-6">
<p appHighlight>Make me YELLOW!!</p>
</div>
</div>
Result:
In the example above, the variable
backgroundColor : string = 'blue';
binds to the html attribute('style.backgroundColor')
. For this to work you have to place the directive selectorselector: '[appHighlight]'
inside the html element<p appHighlight>
.
2.HostListener
Host Listener is an angular way of reacting to events with the help of directives.
I will show the way of reacting to events without directives in web application and then show the use of Host Listener.
without Host Listener
app.component.html
<div class="container">
<div class="col-xs-6">
<p (mouseenter) = "onMouseEnter()">Make me YELLOW!!</p>
</div>
</div>
highlight.component.ts
export class HighlightComponent {
onMouseEnter(){
// Logic goes here
}
with HostListener
app.component.html
<div class="container">
<div class="col-xs-6">
<p appHighlight>Make me YELLOW!!</p>
</div>
</div>
highlight.directive.ts
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor') backgroundColor : string = 'yellow';
@HostBinding('style.cursor') cursor : string = 'pointer';
@HostListener('mouseenter') mouseEnter(eventData : Event){
this.backgroundColor = 'blue';
}
@HostListener('mouseleave') mouseLeave(eventData : Event){
this.backgroundColor = 'yellow';
}
}
If you note carefully in the above example, I have defined the logic for mouse enter and mouse leave simply by adding a directive selector and without disturbing much of the HTML element. Similarly you can add any number of logics for your html template using directives. It makes the code more readable and more loosely coupled.
Directives helps in segregate the html attributes logic with the use of these decorators. Also with the help of directives and its tools like hostListener and hostBinding, you can minimise the complexity of your html template files.