填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

HostListener

一個裝飾器,用於宣告要監聽的 DOM 事件,並提供在該事件發生時要執行的處理器方法。

Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.

檢視"說明"...

選項說明
eventName?

要監聽的事件。

The DOM event to listen for.

args?

當該事件發生時傳給處理器方法的一組引數。

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

說明

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.

Further information available in the Usage Notes...

選項

要監聽的事件。

The DOM event to listen for.

      
      eventName?: string
    

當該事件發生時傳給處理器方法的一組引數。

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

      
      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 {}
    

The following example registers another DOM event handler that listens for key-press events.

      
      import { HostListener, Component } from "@angular/core";

@Component({
  selector: 'app',
  template: `<h1>Hello, you have pressed keys {{counter}} number of times!</h1> Press any key to
increment the counter.
  <button (click)="resetCounter()">Reset Counter</button>`
})
class AppComponent {
  counter = 0;
  @HostListener('window:keydown', ['$event'])
  handleKeyDown(event: KeyboardEvent) {
    this.counter++;
  }
  resetCounter() {
    this.counter = 0;
  }
}