How do I detect any key press on Angular 2 (e.g. not necessarily in an input box)
Currently I managed to do this using the following code:
import {Component, HostListener} from "@angular/core";
@Component(<any>{
selector: 'foo',
template: `<h1>Foo</h1>`,
})
export class FooComponent {
@HostListener('document:keypress', ['$event'])
keypress(e: KeyboardEvent) {
console.log("Key Up! " + e.key);
}
}
The above code manages to work fine for most characters e.g. alphanumeric, punctuation, symbols, etc
The issue is that this method does not run when pressing keys such as SHIFT, CTRL, F1...F12, Tab, ALT etc.
The KeyDown event is triggered when the user presses a Key. 2. The KeyUp event is triggered when the user releases a Key. 3. The KeyPress event is triggered when the user presses & releases a Key.
For this, you have to import HostListener in your component ts file. import { HostListener } from '@angular/core'; then use below function anywhere in your component ts file. @HostListener('document:keyup', ['$event']) handleDeleteKeyboardEvent(event: KeyboardEvent) { if(event.
The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .
The ng-keypress directive tells AngularJS what to do when the keyboard is used on the specific HTML element. The ng-keypress directive from AngularJS will not override the element's original onkeypress event, both will be executed.
You have to use ('document:keydown')
instead of ('document:keypress')
to get shift, ctrl...
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