Hostbinding And Hostlistener Angular Angular

Jun 12th, 2020 - written by Kimserey with .

When creating directives, we sometime face situation where we need to change properties from the element or component hosting the directive. Those can changes can be made using HostBindsing decorator. In today’s post we will look at how we can use HostBinding and HostListener to change properties of the host element.

HostBinding and HostListener

@HostBinding is a decorator providing a way to bind a DOM property to a data property within the directive. For example, when we use

1
@HostBinding('style.cursor') cursor = "cursor";

the style cursor: pointer will be applied to the host element.

It’s also possible to specify weither attribute should be set or not by providing a boolean value.

1
2
@HostBinding('disabled') disabled = true;
@HostBinding('class.bg-primary') backgroundColor = true;

Similarly @HostListener is a decorator providing a way to bind a DOM event to a callback function within the directive. For example, when we use

1
2
3
4
@HostListener('click', ['$event'])
click(e) {
    console.log('Element clicked', e);
};

click will be invoked when the host element is clicked on. We are able to define the arguments to be passed to the callback by adding them as a second argument to @HostListener.

Example

Now that we know what @HostBinding and @HostListener are, we can create a small sample directive which when placed on a element, will change the cursor to pointer, apply a primary background when hovered, and write to the console when clicked on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Directive({
  selector: '[appTest]',
})
export class TestDirective {
    @HostBinding('style.cursor') cursor = "pointer";
    @HostBinding('class.bg-primary') backgroundColor = false;

    @HostListener('mouseenter')
    mouseover() {
      this.backgroundColor = true;
    };

    @HostListener('mouseleave')
    mouseleave() {
      this.backgroundColor = false;
    };

    @HostListener('click', ['$event'])
    click(e) {
        console.log('Element clicked', e);
    };
}

and we can use the directive on a <div> host for example:

1
<div appTest> Hello world </div>

And that’s it, this concludes today’s post!

Conclusion

In today’s post we saw how we could use @HostBinding and @HostListener to update properties on the host or handle event on the host using data binding properties from within the directive. Those two decorators are extremely useful when making shared directives that modify the visual aspect of the elements they are placed on. I hope you liked this post and I see you on the next one!

External Sources

Designed, built and maintained by Kimserey Lam.