HostListener: HostListenerFactory

export HostListener : HostListenerFactory

exported from angular2/core defined in angular2/src/core/metadata.ts (line 1358)

Declares a host listener.

Angular will invoke the decorated method when the host element emits the specified event.

If the decorated method returns false, then preventDefault is applied on the DOM event.

Example

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

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;

  @HostListener('click', ['$event.target'])
  onClick(btn) {
    console.log("button", btn, "number of clicks:", this.numberOfClicks++);
  }
}

@Component({
  selector: 'app',
  template: `<button counting>Increment</button>`,
  directives: [CountClicks]
})
class App {}

bootstrap(App);