Emanuel Weinsjö
Emanuel Weinsjö

Reputation: 491

Angular 2 Global Key detection

How can I bind a keyevent listener on the document instead of an specific inputfield in Angular 2 using RC5?

For example:

I Know this "bind it to an element"

<input (keypress)="onKeyDown($event)" [(ngModel)]="something" type="text">

How can I bind it to the document for example

<div (keypress)="onKeyDown($event)"> <input /> ... </div>

Upvotes: 12

Views: 8781

Answers (2)

Zolt&#225;n Lehoczky
Zolt&#225;n Lehoczky

Reputation: 11

You can also use rxjs for this

fromEvent<KeyboardEvent>(document, 'keydown')
  .pipe(...)
  .subscribe()

See: https://www.learnrxjs.io/learn-rxjs/operators/creation/fromevent

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658067

@HostListener('window:keydown', ['$event'])
onKeyDown(event) {
  ...
}

You can also do

<div (window:keypress)="onKeyDown($event)">

or

<div (document)="onKeyDown($event)">

Declarative filtering like

<div (window:keydown.alt.a)="onKeyDown($event)">

is currently not supported for global listeners

See also https://github.com/angular/angular/issues/7308

Upvotes: 24

Related Questions