typescript HostListener 分析组合按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44369704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:36:24  来源:igfitidea点击:

HostListener to analyse combination key press

angulartypescript

提问by Mithun Sudheendran

I am trying to trace when a user presses a Shift+Tab combination key using keyboard, but I am not able to fire that event

我试图在用户使用键盘按下 Shift+Tab 组合键时进行跟踪,但我无法触发该事件

@HostListener('keyup', ['$event'])
@HostListener('keydown', ['$event'])

onkeyup(event) {
  if (event.keyCode == 16 && event.keyCode == 9) {
    this.isShift = true;
    console.log("On Keyup " + event.keyCode);
  }
}

onkeydown(event) {
  console.log("On KeyDown" + event.keyCode);
}

回答by Frank Modica

It works when I do this:

当我这样做时它有效:

@Directive({
  selector: '[test-directive]'
})
export class TestDirective {
  @HostListener('keydown', ['$event']) onKeyDown(e) {
    if (e.shiftKey && e.keyCode == 9) {
      console.log('shift and tab');
    }
  }
}

<input type="text" test-directive />

Note that keyupcan be tricky because tabmay unfocus the element. So by the time keyupfires, you may be on the next element, so keyupmay actually fire on that element. So it depends on what you need. But keydownworks for the current element.

请注意,这keyup可能很棘手,因为tab可能会使元素失去焦点。因此,到keyup触发时,您可能会在下一个元素上,因此keyup实际上可能会触发该元素。所以这取决于你需要什么。但keydown适用于当前元素。

回答by Aziz Yokubjonov

Although the solution by Frank Modica works, using Angular's key event filtering and pseudo-eventswould be a more readable and cleaner solution:

尽管 Frank Modica 的解决方案有效,但使用Angular 的关键事件过滤和伪事件将是一个更具可读性和更清晰的解决方案:

@Directive({
    selector: '[keyHandler]'
})
export class KeyHandlerDirective {

    @HostListener('keydown.shift.tab', ['$event'])
    onKeyDown(e) {
        // optionally use preventDefault() if your combination
        // triggers other events (moving focus in case of Shift+Tab)
        // e.preventDefault();
        console.log('shift and tab');
    }
}

// in template:
<input type="text" keyHandler />

More examples of how pseudo-events work can be found here.

可以在此处找到有关伪事件如何工作的更多示例。