L.querter L.querter - 2 months ago 144
TypeScript Question

Angular 2 | listen for keypress event on 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 conponent.ts)

It was easy in Angular 1 with a

ng-keypress
but it does not work with
(keypress)="handelInput($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)="handelInput($event)" tabindex="1">


THIS IS FOR ANGULAR 2, NOT JQUERY OR ANGULAR 1!
I don't want to use jquery in my app for this. (so no ID-binding)

Thank you!

Answer

You can use something like this within your component:

  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) { 
    this.key = event.key;
  }

See also https://angular.io/docs/ts/latest/api/core/index/HostListener-var.html

Comments