Issue
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">
Solution
I would use @HostListener decorator within your component:
import { HostListener } from '@angular/core';
@Component({
  ...
})
export class AppComponent {
  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) { 
    this.key = event.key;
  }
}
There are also other options like:
host property within @Component decorator
Angular recommends using @HostListener decorator over host property https://angular.io/guide/styleguide#style-06-03
@Component({
  ...
  host: {
    '(document:keypress)': 'handleKeyboardEvent($event)'
  }
})
export class AppComponent {
  handleKeyboardEvent(event: KeyboardEvent) {
    console.log(event);
  }
}
renderer.listen
import { Component, Renderer2 } from '@angular/core';
@Component({
  ...
})
export class AppComponent {
  globalListenFunc: Function;
  constructor(private renderer: Renderer2) {}
  ngOnInit() {
    this.globalListenFunc = this.renderer.listen('document', 'keypress', e => {
      console.log(e);
    });
  }
  ngOnDestroy() {
    // remove listener
    this.globalListenFunc();
  }
}
Observable.fromEvent
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { Subscription } from 'rxjs/Subscription';
@Component({
  ...
})
export class AppComponent {
  subscription: Subscription;
  ngOnInit() {
    this.subscription = Observable.fromEvent(document, 'keypress').subscribe(e => {
      console.log(e);
    })
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
Answered By - yurzui
 
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.