Say there is an
enum ArrowKey{
Up = "ArrowUp",
Right = "ArrowRight",
Down = "ArrowDown",
Left = "ArrowLeft"
}
Now when receiving a KeyboardEvent
with e.key
"ArrowUp" how is it easily checked that this string value exists in the enum? And how to pick out the right enum value afterwards?
The following function will return enum value corresponding to pressed arrow key or null if this key is not defined inside that enum.
getEnumValue(event): ArrowKey | null {
const pressedKey = event.key;
const keyEnum = Object.keys(ArrowKey).find(key => ArrowKey[key] === pressedKey);
return ArrowKey[keyEnum] || null;
}
demo: https://stackblitz.com/edit/angular-dmqwyf?embed=1&file=app/app.component.html
EDIT: one-line equivalent (ES 2017)
getEnumValue(event): ArrowKey | null {
return Object.values(ArrowKey).includes(event.key) ? event.key : null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With