Angular HostListener是同一组件的多个实例

rei*_*ika 6 javascript angular

我有一个名为ListComponent的组件,我有以下代码.

  @HostListener("document:keydown", ["$event"])
  handleKeyEvent(event: KeyboardEvent) {
    switch(event.keyCode) {
      case 38: //up arrow
        this.selectPreviousItem();
        break;
      case 40: //down arrow
        this.selectNextItem();
        break;
    }
  }
Run Code Online (Sandbox Code Playgroud)

当我按向上箭头键或向下箭头键时,事件将触发页面上组件的所有实例.如何仅针对焦点元素触发事件?

Sac*_*aka 2

我认为最好创建一个指令并在要聚焦的元素中调用它。

@Directive({
    selector: 'focusItem', 
    })

  export class MyDirective {
    constructor() { }
    @HostListener('focus', ['$event.target'])
      onFocus(target) {
        console.log("Focus called 1");
      }
  }
Run Code Online (Sandbox Code Playgroud)

在元素中调用它

<input focusItem>  
Run Code Online (Sandbox Code Playgroud)