Event Listening for Key Combination not working

Viewed 50

I am trying to implement several hotkeys into an application. I want to have key combination from alt+1 till alt+9.

The alt+1 combination is working like a charm (breakpoint reached), but alt+2 is not working (breakpoint not reached).

Can someone explain that?

@HostListener('document:keydown.alt.1', ['$event'])
  doThis(e: KeyboardEvent) {
    // action();
    e.preventDefault();
  }

@HostListener('document:keydown.alt.2', ['$event'])
  doThat(e: KeyboardEvent) {
    // action();
    e.preventDefault();
  }
2 Answers

So I am not able to reproduce the issue, couple of things to note:

  • Make sure you are actually focused on the page itself

  • check your console for any JS errors as that will stop most things from continuing to execute as expected.

  • As another option you can also try listening to the key events like so:

    @HostListener('document:keydown', ['$event']) onKeyDown(e) {
      if (e.altKey && e.key == 1) {
        console.log('alt and 1');
      } else if (e.altKey && e.key == 2) {
        console.log('alt and 2');
      }
    }
    

Stackblitz: https://stackblitz.com/edit/angular-uc7ssc?file=src/app/app.component.ts

Where you have one HostListener for the keydown event and we are filtering for the actions that we want.


Edit 2: I've made an updated stackblitz showing a possible way to handle multiple key strokes (https://stackblitz.com/edit/angular-7lrjat?file=src/app/app.component.ts). The big picture idea here is that we create a Stack a simple data structure that follows the FILO principle (First in Last Out, think of stacking plates. The first plate is the last one you can access) and we create a timeout function to let the user have a chance to quickly input their keys before we execute the code.

You could also avoid that timeout, if you'd like, and modify the code a bit by checking to make sure that the second key is a number or not. By the way, that is what the built in method isFinite does. Now in TypeScript they haven't set it up to where it can accept a string as an input, thus the preceding + in order to cast the string value of lastKey.key.

I hope this helps!

event.preventDefault();, probably, should go before custom behavior, not after

Related