Reputation: 10278
I want to be able to get the value of a numbered key on a onKeypress event that is done with shift. I'm trying to make a web app that links different actions with the keys 123...9 and also shift-123...9. The problem is that when I get the keypress event with shift, I only can get the shift-value and if shift is true.
e.g. shift-1
shiftKey: true
key: "!"
I want to find a way to get the value 1 from "!". I'm worried also about other keyboards that might have different characters other than "!" when shift-1 is pressed. Like AZERTY keyboard.
http://mentalfloss.com/article/52483/6-non-qwerty-keyboard-layouts
How can I get the original value of a shift-keypress event as though shift was not pressed?
update to comment response:
@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
let keyNumber = Number.parseInt(event.key);
if (keyNumber !== NaN && keyNumber !== 0) {
if (event.shiftKey === false && keyNumber <= this.documents.length) {
// use number to access some array
this.currentDocument = this.documents[--keyNumber];
} else if (keyNumber <= this.currentDocument.toc.length) { // I'll see if they go past 10..
// PROBLEM HERE trying to get number to also access an array
this.routeToFragment(this.currentDocument.toc[--keyNumber].slug); // this is NaN until I can convert "!@#$%..("
}
}
}
Upvotes: 1
Views: 434
Reputation: 462
Keyboard events have the code
property as part of their event object - this will return the key that's pressed, ignoring any modifier keys.
Example:
document.addEventListener('keypress', (event) => {
console.log({ code: event.code })
})
/*
[press shift + 1] => // { code: 'Digit1' }
[press shift + /] => // { code: 'Slash' }
*/
Upvotes: 1