In this article, we are going to learn and implement HostListner and HostBinding in Angular 8 using a custom directive.
HostListener and HostBinding are two decorators which are used in angular to interact with the host element on which the directive is applied.
The @HostListener decorative listens to the events which are raised on the actual host element while the @HostBinding decorative provides the capabilities to modify properties on the host element.
Let us start the implementation. I have already created a default project named hostlistner-demo using the Angular CLI.
We will create a custom directive which changes the color of the host element and applies a border when it is hovered upon.
Create a Custom Directive
Let us first create a custom directive named customdemo using Angular CLI using the below command.
Inject the ElementRef and Renderer services
Now in order to access the host element on which are customdemo directive will be applied we will need to inject ElementRef and Renderer into our directive.
Also Read: Complete Angular Routing Part 1
The ElementRef service will provide us with a reference of the actual host element while Renderer will help in rendering the element with any modified changes. Both these services lie in the ‘@angular/core’ module which needs to be included as well.
Create the Hostlistener & Hostbinding
Now the Hostlistner directive maps an actual event on the host element with a handler in the directive. In our case we want to handle two events, the mouseenter and mouseleave.
The Hostbinding decorative as described above maps to a property of the host. Let us create two of these ones for the backgroundColor and one for the border.
Note: We can also bind the properties like classes, attributes etc using the Hostbinding.
Use the code below. The string variable bgColor can now update the background color and the borderColor can update the border of the host element.
The two methods customMouseEnterEventHandler() and customMouseLeaveEventHandler() listnes to the mouseenter and mouseleave events on the host on which the appCustomDemo directive will be applied
Let us now add a simple div in the app.component.html file with some text and apply our custom directive.
Note: The name of the directive to apply is the one mentioned in the selector property inside the square brackets.