Cookies concent notice

This site uses cookies from Google to deliver its services and to analyze traffic.
Learn more
Skip to main content
This site is no longer updated.Head to Angular.devHome
/

This is the archived documentation for Angular v17. Please visit angular.dev to see this page for the current version of Angular.

HostBinding

Decorator that marks a DOM property or an element class, style or attribute as a host-binding property and supplies configuration metadata. Angular automatically checks host bindings during change detection, and if a binding changes it updates the host element of the directive.

OptionDescription
hostPropertyName?

The DOM property that is bound to a data property. This field also accepts:

  • classes, prefixed by class.
  • styles, prefixed by style.
  • attributes, prefixed by attr.

Options

The DOM property that is bound to a data property. This field also accepts:

  • classes, prefixed by class.
  • styles, prefixed by style.
  • attributes, prefixed by attr.
      
      hostPropertyName?: string
    

Usage notes

The following example creates a directive that sets the valid and invalid class, a style color, and an id on the DOM element that has an ngModel directive on it.

      
      @Directive({selector: '[ngModel]'})
class NgModelStatus {
  constructor(public control: NgModel) {}
  // class bindings
  @HostBinding('class.valid') get valid() { return this.control.valid; }
  @HostBinding('class.invalid') get invalid() { return this.control.invalid; }

  // style binding
  @HostBinding('style.color') get color() { return this.control.valid ? 'green': 'red'; }

  // style binding also supports a style unit extension
  @HostBinding('style.width.px') @Input() width: number = 500;

  // attribute binding
  @HostBinding('attr.aria-required')
  @Input() required: boolean = false;

  // property binding
  @HostBinding('id') get id() { return this.control.value?.length ? 'odd':  'even'; }

@Component({
  selector: 'app',
  template: `<input [(ngModel)]="prop">`,
})
class App {
  prop;
}