Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect any key press in Angular 2?

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.

like image 293
Yahya Uddin Avatar asked Jul 01 '16 00:07

Yahya Uddin


People also ask

What is KeyUp and KeyDown in angular?

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.

How can I listen for keypress event on the whole page?

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.

How does onkeypress work?

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 .

What is keypress in Angular?

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.


1 Answers

You have to use ('document:keydown') instead of ('document:keypress') to get shift, ctrl...

like image 151
Kayo Lima Avatar answered Oct 23 '22 11:10

Kayo Lima