HostListener to analyse combination key press

和自甴很熟 提交于 2021-02-16 04:24:54

问题


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

@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);
}

回答1:


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 keyup can be tricky because tab may unfocus the element. So by the time keyup fires, you may be on the next element, so keyup may actually fire on that element. So it depends on what you need. But keydown works for the current element.




回答2:


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

@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.



来源:https://stackoverflow.com/questions/44369704/hostlistener-to-analyse-combination-key-press

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!