skip to Main Content

When the user pressed Tab + Escape key then I wanted to call my function but I couldn’t capture this combination. If this combination is not possible then I want one combination with Escape key but those combination are not used in Windows, Ubuntu and Mac.

I tried like this:

@HostListener('window:keydown', ['$event'])
async onkeyDown($event: KeyboardEvent) {
  if($event.key === 'Tab' && $event.code === 'Escape') {
    console.log('Tab + Escape keys pressed');  
  }
} 

I want to capture Tab + Escape key combination.

2

Answers


  1. Instead of using 'window:keydown' use 'document:keydown'. Afterwards you can handle combinations of keys pressed on the keyboard. For example by using event.keyCode.
    Furthermore, you could directly listen on escape-key-presses with 'window:keydown.escape'.

    Login or Signup to reply.
  2. For shift and ctrl keys, HTML provide a convenient event.ctrlKey and event.shiftKey, making these easy to play with for key combination as you can check on any keystroke if these keys are pressed at the same time.

    For the tab key you don’t have such mechanic, but as you can still detect any keystroke, you can do something like this:

    // Handle tab key
    
    @HostListener('document:keydown.tab', ['$event'])
    async onTabKeyDown($event: KeyboardEvent) {
      this.tabPressed = true;
      console.log('Tab keydown');
      if (this.escapePressed && this.tabPressed) {
        // Both are pressed
      }
    }
    
    @HostListener('document:keyup.tab', ['$event'])
    async onTabKeyUp($event: KeyboardEvent) {
      this.tabPressed = false;
      console.log('Tab no longer pressed'); 
    }
    
    // Handle escape key
    
    @HostListener('document:keydown.escape', ['$event'])
    async onEscapeKeyDown($event: KeyboardEvent) {
      this.escapePressed = true;
      console.log('Escape keydown');
      if (this.escapePressed && this.tabPressed) {
        // Both are pressed
      }
    }
    
    @HostListener('document:keyup.escape', ['$event'])
    async onEscapeKeyUp($event: KeyboardEvent) {
      this.escapePressed = false;
      console.log('Escape no longer pressed');
    }
    

    Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search