Reputation: 28951
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.
Upvotes: 8
Views: 5654
Reputation: 740
You have to use ('document:keydown')
instead of ('document:keypress')
to get shift, ctrl...
Upvotes: 9