Angular @HostBinding() and @HostListener() Example

Angular custom directives can take inputs using @HostBinding and add event listeners to elements using @HostListener.

In this tutorial, we will create a custom directive example from scratch which will take user inputs from a directive element and use them in event listeners.

Let’s create a new Directive in the Angular application to demonstrate an element Highlighter directive which will include color input by a user and mouse events to highlight the background of a div.

Create Directive [appHighlight]

To create a new directive we will use the generate command of ng cli. Run the following command in the terminal window to creates a directive in directives folder :

$ ng generate directive directives/highlighter

Above command will create a new directive HighlighterDirective in the file src\app\directives\highlighter.directive.ts

To use a directive we also need to import it in the app.module.ts file’s declaration array but NG CLI command will automatically add it as shown below:

Add Directive Element

Now we will add a <p/> tag element with some random text in the component template HTML with two properties:

[appHighlighter] : This property will act as the Directive selector added to the element as well as take a color name or Hexacode, which will be the background color changed on the mouseenter event.
[defaultColor] : This property takes the color which will be added by default to the element.
Finally, the element with our directive will look like this:

Update Directive with @HostBinding and @HostListener

Let’s add @HostBinding and @HostListener decorators and check what actually they do in a directive?

What is @HostBinding in Angular?

The host is actually the element on which we have added the directive attribute selector. By using the @HostBinding we can control the properties on the host element, on which we have applied the directive selector.

We will use this decorator to set the background color on the directive by controlling the style attribute from the directive class itself.

What is @HostListener in Angular?

The @HostListener decorator enable event binding to the host element which we will use inside our directive class to bind mouseenter and mouseleave event listeners.

Moving to our directive class, add @input decorators to get values to form properties we bind to the <p> element. Also, add @HostBinding for getting control over style attribute to change backgroundColor.

On class initialization, set the background color of the host, which is the <p> element here with the default color using the ngOnInit() component hook.

To control mouse behavior on the element, add event listeners as shown below:

That’s it now our complete HighlighterDirective class will finally have the following code!

Conclusion: Here we discussed how to control the element behavior by adding a custom directive using @HostBinding and @HostListener interfaces.


Leave a Reply

Notify of