liveBook · Manning

@HostBinding

As explained in Pro Angular 16

A host binding is an Angular binding that connects a directive or component value to a property, attribute, class, or style of its host element.

@HostBinding connects a directive property to a property, attribute, class, style, or textContent value on the host element. It lets Angular manage host updates without direct DOM manipulation through ElementRef. section 14.5

Use host bindings when a directive needs to reflect its state through the element it decorates:

  • Bind a directive input to the host class, such as changing a product row between table-success and table-warning. section 14.5
  • Bind a directive property to an input element’s value, then update that property when the host emits an input event. section 14.6
  • Prefer host bindings over direct DOM APIs when Angular property or event bindings express the same behavior; Angular supplies the environment-specific implementation. section 14.5

Synchronize a custom input binding

A directive can expose a paModel input while binding fieldValue to the host input’s value. ngOnChanges copies model changes into fieldValue; @HostListener("input", ["$event.target.value"]) updates fieldValue and emits paModelChange. The template can then use [(paModel)]="newProduct.name".

How Pro Angular 16 covers it

How deep it goes
Explains decorator usage, class and value bindings, two-way synchronization, and the limitation that event handling requires @HostListener.
Examples
Demonstrates product-row classes and a custom paModel input whose value follows and updates a component property.
What it assumes
Assumes familiarity with attribute directives, Angular inputs and outputs, and basic property and event binding.
What you can do after
Build it from scratch by binding directive properties to host classes or values and pairing them with host event listeners.
How it connects
Ties host bindings to attribute directives, property binding, input properties, output properties, @HostListener, and two-way binding.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.