Issue
In my application, I need to identify if the user pressed any of the number keys (either main keyboard or numpad) as well as if shift/ctrl/alt keys are pressed at the same time.
I need this because the pressed key represents the number in the array (from 0 to 9) which should trigger an action with this number. So my logic is simple:
@HostListener('document:keydown', ['$event'])
handleKeydownEvent(event: KeyboardEvent) {
let index = Number(event.key);
if (isNaN(index)) {
// skip, for now
}else{
doAction(index);
}
}
I like this because of its readability and transparency.
It seems that things are simple when I additionally need to handle 'Alt' or 'Ctrl'. In these cases, event.key still represents a numeric key value of the key pressed (like '1' or '2') (and I can check event.ctrlKey/event.altKey.
But things are getting more complicated when I need to consider the 'Shift' key. In this case, event.key does not represent a numeric key. Instead, it represents other characters such as '!' or '@'.
I guess I could convert this into key code by building a map, but I'd need to handle keyboard layouts as in some cases Shift+2 will end up to be a '@', in other - '"' (Russian layout vs English).
What is the proper and simple way to detect the code of the key pressed when the 'Shift' button is pressed?
Thanks!
Solution
Options:
- Uisng event.which: It returns numeric value but it is deprecated.
- Your idea of creating map is cool. To create the map, instead of using "event.key", use "event.code".
EVENT.CODE is your life saver.
Answered By - Kapil Sharma
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.