0

I have a context menu in my Angular app, and I want to trigger a callback whenever a key is pressed while that context menu is open. I added the following code inside the constructor of my context menu:

window.addEventListener('keydown', function() {
  console.log('keys pressed');
});

If I open the context menu, hover the cursor over it, and press a key, it successfully triggers this callback. However, if I move the mouse off the menu, it no longer triggers it when I press a key. Moreover, even if I move the mouse back over the menu, it still doesn't respond. I want it to respond when I press a key no matter where the cursor is, as long as the context menu is open.

Any ideas?

RNdev
  • 953
  • 1
  • 8
  • 26
  • 1
    Would it be possible to create a minimal verifiable code example? Maybe a [Sample StackBlitz](https://stackblitz.com/fork/angular) to work with? – SiddAjmera Dec 08 '19 at 02:02

2 Answers2

0

Try this

   @HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {
      console.log('keys pressed');
   }
A.khalifa
  • 2,366
  • 3
  • 27
  • 40
0

You need keyDown and click event to properly listen context menu events. the complete code can be founded here in this StackBlitz Link

Your component code is..

contextmenu:boolean = false;
styleSelect: boolean = false;

clickMe(){
   this.contextmenu = !this.contextmenu;
   this.styleSelect === true ? this.styleSelect= false : '';
   document.addEventListener('keydown', this.scroll, false );
}

scroll = (e): void => {
     if (e.target.tagName === 'LI' ) {document.removeEventListener('mousedown', this.scroll); }
     if (this.contextmenu === true) {
        this.contextmenu = false;
        this.styleSelect = true;
        document.removeEventListener('keydown', this.scroll);
     }
 }

 close(){
   this.contextmenu = false;
 }
Developer
  • 3,309
  • 2
  • 19
  • 23