Coupling

Tight coupling of our attribute directives with the browser platform context and underlying Document Object Model (DOM) is not always best practice, but it is useful and relatively easy. Tight coupling is caused by accessing and modifying the elements in the DOM using it's standardized APIs. We can reduce this coupling using the host decorators provided by Angular.

HostBinding

The @HostBinding decorator enables us to easily add and remove properties on the host element (the element upon which the attribute directive is applied). Of course, we can also modify the value of existing properties on the host element as well. When we refer to property values, we're talking about the properties of an HTMLElement in the Web API.

For example, we can toggle a class that is applied to an element in the DOM using a HostBinding decorator as follows:

@HostBinding('class.btn-grow') btnGrow = false

In our directive class we can programmatically modify the boolean value of the btnGrow property in the class. When true, the btn-grow class is applied to the host element, and when false, the btn-grow class is removed.

HostListener

The @HostListener decorator enables us to invoke a method in our directive's class when a specified event occurs on the host element. Note that we omit the "on" portion of the event if you are familiar with the more traditional HTML syntax of specifying event listeners. For example, in HTML we might add an event listener for the "click" event via the "onclick" attribute. In Angular, we just specify the event name; in this case, the "click" event.