I am using the following method to detect keypresses on a page. My plan is to detect when the Escape key is pressed and run a method if so. For the moment I am just attempting to log which key is pressed. However the Escape key is never detected.
@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
console.log(event);
let x = event.keyCode;
if (x === 27) {
console.log('Escape!');
}
}
Angular makes this easy with the @HostListener decorator. This is a function decorator that accepts an event name as an argument. When that event gets fired on the host element it calls the associated function.
Try it with a
keydown
orkeyup
event to capture theEsc
key. In essence, you can replacedocument:keypress
withdocument:keydown.escape
:It worked for me using the following code:
or in shorter way:
keydown and keyup seem to work: http://embed.plnkr.co/VLajGbWhbaUhCy3xss8l/
Modern approach