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

I'm looking for a way to bind a function to my whole page (when a user presses a key, I want it to trigger a function in my component.ts)

It was easy in AngularJS with a ng-keypress but it does not work with (keypress)="handleInput($event)".

I tried it with a div wrapper on the whole page but it doesn't seem to work. it only works when the focus is on it.

<div (keypress)="handleInput($event)" tabindex="1">

This question is related to typescript angular keypress key-bindings

The answer is


yurzui's answer didn't work for me, it might be a different RC version, or it might be a mistake on my part. Either way, here's how I did it with my component in Angular2 RC4 (which is now quite outdated).

@Component({
    ...
    host: {
        '(document:keydown)': 'handleKeyboardEvents($event)'
    }
})
export class MyComponent {
    ...
    handleKeyboardEvents(event: KeyboardEvent) {
        this.key = event.which || event.keyCode;
    }
}

I think this does the best job

https://angular.io/api/platform-browser/EventManager

for instance in app.component

constructor(private eventManager: EventManager) {
    const removeGlobalEventListener = this.eventManager.addGlobalEventListener(
      'document',
      'keypress',
      (ev) => {
        console.log('ev', ev);
      }
    );
  }

Just to add to this in 2019 w Angular 8,

instead of keypress I had to use keydown

@HostListener('document:keypress', ['$event'])

to

@HostListener('document:keydown', ['$event'])

Working Stacklitz


If you want to perform any event on any specific keyboard button press, in that case, you can use @HostListener. 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.key === 'Delete')
    {
      // remove something...
    }
  }

Be aware "document:keypress" is deprecated. We should use document:keydown instead.

Link: https://developer.mozilla.org/fr/docs/Web/API/Document/keypress_event


Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to keypress

onKeyDown event not working on divs in React How can I listen for keypress event on the whole page? How to handle the `onKeyPress` event in ReactJS? detect key press in python? jQuery Keypress Arrow Keys Submit form on pressing Enter with AngularJS How to trigger an event in input text after I stop typing/writing? How to capture Enter key press? JQuery: detect change in input field Pressing Ctrl + A in Selenium WebDriver

Examples related to key-bindings

How can I listen for keypress event on the whole page? How do I bind the enter key to a function in tkinter? How to select all instances of a variable and edit variable name in Sublime KeyListener, keyPressed versus keyTyped Binding arrow keys in JS/jQuery