简体   繁体   中英

HostListener works incorrectly in case user press Shift button in Angular

In Angular 6, I write a function to detect if the Ctrl button is pressed:

  @HostListener('document:keydown.control')
  onKeydownHandler() {
    console.log('key down control');
  }

Each time I press Ctrl button, the log is written in the console. However, if I press Ctrl+Shift button, this log is not written. Even after I release the Shift button, the log is not written anymore.

Do you have any idea of what happens?

You need to simply decorate it some more.

  @HostListener('document:keydown.control')
  @HostListener('document:keydown.shift.control')
  @HostListener('document:keydown.control.shift')
  onKeydownHandler() {
    console.log('key down control');
  }

keydown.control , keydown.shift.control and keydown.control.shift are treated as separate, different events.

You can listen to ctrl+shift event by using following binding. Not that it will only work if you press control first and then shift.

@HostListener('document:keydown.control.shift')
  onKeydownHandler(e) {
    console.log('key down control', e);
  }

If you want to handle other just add as many decorators as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM