Home > other >  Event Listening for Key Combination not working
Event Listening for Key Combination not working

Time:09-13

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related