In angular i'm binding data with host listener, like below code
@HostListener('window:keyup', ['$event'])
onKeyUp(event: KeyboardEvent) {
if (event.keyCode === 13) {
this.onEnterClicked(event);
}
}
and in this code I want to replace 13
with something Keycode.ENTER.
but there is no class available which holds constants for each keys in angular and javascript.
so is there any class i'm missing? if not then why javascript or angular not defined constants at one place?
In angular i'm binding data with host listener, like below code
@HostListener('window:keyup', ['$event'])
onKeyUp(event: KeyboardEvent) {
if (event.keyCode === 13) {
this.onEnterClicked(event);
}
}
and in this code I want to replace 13
with something Keycode.ENTER.
but there is no class available which holds constants for each keys in angular and javascript.
so is there any class i'm missing? if not then why javascript or angular not defined constants at one place?
Share Improve this question asked Jul 14, 2018 at 4:36 Ravi SevtaRavi Sevta 3,0851 gold badge26 silver badges42 bronze badges 2 |4 Answers
Reset to default 8I think you want
if (event.key === KeyEventEnum.Enter) {
...
}
or
if (event.key === KeyEventEnum.Escape) {
...
}
or
if (event.key === KeyEventEnum.Shift) {
...
}
or
if (event.key === KeyEventEnum.Ctrl) {
...
}
instead of you are using like
if (event.key === "Enter") {
...
}
Angular doesn't have any constant or enum to hold all key code in one place but if you want any enum or constant then you please visit once to below link might be it help you. Its a angular package that you have to include it in your project.
https://github.com/nfriend/ts-keycode-enum
KeyCode is deprecated
To understand what would be typed we should use e.key
, ie shift+a
results in an uppercase A
.
To understand what physical button was pressed we should use e.code
, ie pressing left shift will give us ShiftLeft
.
Enums for both of these can be found the npm pacakge etsoo/shared, or in its Keyboard Enums source file.
Use event.key
instead of event.keyCode
, keyCode
returns 13
for enter and event.key
returns "Enter"
string
HostListener('window:keyup', ['$event'])
onKeyUp(event: KeyboardEvent) {
if (event.key === "Enter") {
this.onEnterClicked(event);
}
}
A NPM @etsoo/shared includes:
Keyboard.Keys
forKeyboardEvent.key
constantsKeyboard.Codes
for KeyboardEvent.code constants It may help.
event.key
, it returns string.event.keyCode
returns13
andevent.key
returns stringEnter
– Akhil Aravind Commented Jul 14, 2018 at 5:03Enter
at the place of13
. – Ravi Sevta Commented Jul 14, 2018 at 5:07