如何在整个页面上监听按键事件? [英] How can I listen for keypress event on the whole page?

查看:608
本文介绍了如何在整个页面上监听按键事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将功能绑定到我的整个页面的方法(当用户按下一个键时,我希望它触发我的component.ts中的功能)

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)

使用ng-keypress在AngularJS中很容易,但是对于(keypress)="handleInput($event)"则不起作用.

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

我在整个页面上使用div包装器进行了尝试,但似乎不起作用. 它只有在焦点对准它时才起作用.

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">

推荐答案

我会使用 @HostListener 组件中的装饰器:

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;
  }
}

还有其他选项,例如:

宿主属性@Component装饰器

Angular建议在主机属性@HostListener装饰器.rel ="noreferrer"> https://angular.io/guide/styleguide#style-06-03

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();
  }
}

这篇关于如何在整个页面上监听按键事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆