Map<String, String> host
read-only

Specify the events, actions, properties and attributes related to the host element.

Host Listeners

Specifies which DOM events a directive listens to via a set of '(event)' to statement key-value pairs:

  • event: the DOM event that the directive listens to
  • statement: the statement to execute when the event occurs

If the evaluation of the statement returns false, then preventDefault is applied on the DOM event.

To listen to global events, a target must be added to the event name. The target can be window, document or body.

When writing a directive event binding, you can also refer to the $event local variable.

The following example declares a directive that attaches a click listener to the button and counts clicks.

@Directive(
  selector: 'button[counting]',
  host: const {
    '(click)': 'onClick($event.target)'
  })
class CountClicks {
  var numberOfClicks = 0;
 
  void onClick(btn) {
    print("Button $btn, number of clicks: ${numberOfClicks++}.");
  }
}
 
@Component(
  selector: 'app',
  template: `<button counting>Increment</button>`,
  directives: const [CountClicks])
class App {}

Host Property Bindings

Specifies which DOM properties a directive updates.

Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive.

The following example creates a directive that sets the valid and invalid classes on the DOM element that has ngModel directive on it.

@Directive(
  selector: '[ngModel]',
  host: {
    '[class.valid]': 'valid',
    '[class.invalid]': 'invalid'
  }
)
class NgModelStatus {
  NgModel control;
 
  NgModelStatus(this.control);
  get valid => control.valid;
  get invalid => control.invalid;
}
 
@Component({
  selector: 'app',
  template: `<input [(ngModel)]="prop">`,
  directives: [FORM_DIRECTIVES, NgModelStatus]
})
class App {
  prop;
}
 
bootstrap(App);

Attributes

Specifies static attributes that should be propagated to a host element.

Example

In this example using my-button directive (ex.: <div my-button></div>) on a host element (here: <div> ) will ensure that this element will get the "button" role.

@Directive(
  selector: '[my-button]',
  host: const {
    'role': 'button'
  })
class MyButton {}