HostListener

把一个事件绑定到一个宿主监听器,并提供配置元数据。 当宿主元素发出特定的事件时,Angular 就会执行所提供的处理器方法,并使用其结果更新所绑定到的元素。 如果该事件处理器返回 false,则在所绑定的元素上执行 preventDefault

Binds a CSS event to a host listener and supplies configuration metadata. Angular invokes the supplied handler method when the host element emits the specified event, and updates the bound element with the result. If the handler method returns false, applies preventDefault on the bound element.

选项说明
eventName

要监听的事件。

The CSS event to listen for.

args

当该事件发生时传给处理器方法的一组参数。

A set of arguments to pass to the handler method when the event occurs.

选项

要监听的事件。

The CSS event to listen for.

eventName: string
      
      eventName: string
    

当该事件发生时传给处理器方法的一组参数。

A set of arguments to pass to the handler method when the event occurs.

args: string[]
      
      args: string[]
    

使用说明

下面的例子声明了一个指令,它会为按钮附加一个 click 监听器,并统计点击次数。

The following example declares a directive that attaches a click listener to a 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>', }) class App {}
      
      
  1. @Directive({selector: 'button[counting]'})
  2. class CountClicks {
  3. numberOfClicks = 0;
  4.  
  5. @HostListener('click', ['$event.target'])
  6. onClick(btn) {
  7. console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
  8. }
  9. }
  10.  
  11. @Component({
  12. selector: 'app',
  13. template: '<button counting>Increment</button>',
  14. })
  15. class App {}