HostListener to parse keystrokes

I am trying to track when the user presses the Shift + Tab key combination using the keyboard, but I cannot fire this 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);
}

      

+3


source to share


1 answer


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 this keyup

can be tricky because it tab

can defocus the element. So by the time it keyup

fires, you might be on the next item, so you keyup

might actually fire that item. So it depends on what you need. But keydown

works for the current item.

+6


source







All Articles