host Property

We know that @Component decorator functions take object, and this object contains a lot of properties. So in this article we will learn about host properties which is Inherited from Directive decorator .

The host property is used to bind properties, attributes, and events to that particular class component, using a set of key-value pairs.

host: {
    [key: string]: string;
}

Angular automatically checks host property bindings during change detection. If a binding changes, Angular updates the directive's host element.

When the key is a property of the host element, the property value is the propagated to the specified DOM property.

When the key is a static attribute in the DOM, the attribute value is propagated to the specified property in the host element.

For event handling:

  • The key is the DOM event that the directive listens to. To listen to global events, add the target to the event name. The target can be window, document or body.
  • The value is the statement to execute when the event occurs. If the statement evalueates to false, then preventDefault is applied on the DOM event. A handler method can refer to the $event local variable.

The official guidance is to prefer HostListener/HostBinding from the Angular style guide

HostListener/HostBinding decorators versus host metadata

Style 06-03

Consider preferring the @HostListener and @HostBinding to the host property of the @Directive and @Component decorators.

Do be consistent in your choice.

Why? The property associated with @HostBinding or the method associated with @HostListener can be modified only in a single place—in the directive's class. If you use the host metadata property, you must modify both the property declaration inside the controller, and the metadata associated with the directive.

However, the angular/material project official guidance is to prefer host from the Angular/Material style guide

Host bindings

Prefer using the host object in the directive configuration instead of @HostBinding and @HostListener. We do this because TypeScript preserves the type information of methods with decorators, and when one of the arguments for the method is a native Event type, this preserved type information can lead to runtime errors in non-browser environments (e.g., server-side pre-rendering).

We will see @HostBinding and @HostListener in subsequent chapters