Angular 2键盘事件

时间:2016-04-18 13:49:05

标签: angular

尝试使用TypeScript和What is Angular2 way of creating global keyboard shortcuts (a.k.a. hotkeys)?监视Angular 2的键盘事件很有帮助,但tslint(codelyzer)对象带有消息

  

在“@Component”类装饰器中,您正在使用“主机”   财产,这被认为是不好的做法。使用“@HostBindings”,   而是“@HostListeners”属性装饰器。

如何使用推荐的装饰器?我不确定Angular 2: Host binding and Host listening中的示例如何应用于我的用例,因为我没有绑定到任何DOM元素。

这是我的演示

@Component({
  selector: 'my-app',
 template: `
    <div>
      <h2>Keyboard Event demo</h2>
      Start typing to see KeyboardEvent values
    </div>
    <hr />
    KeyboardEvent
    <ul>
      <li>altKey: {{altKey}}</li>
      <li>charCode: {{charCode}}</li>
      <li>code: {{code}}</li>
      <li>ctrlKey: {{ctrlKey}}</li>
      <li>keyCode: {{keyCode}}</li>
      <li>keyIdentifier: {{keyIdentifier}}</li>
      <li>metaKey: {{metaKey}}</li>
      <li>shiftKey: {{shiftKey}}</li>
      <li>timeStamp: {{timeStamp}}</li>
      <li>type: {{type}}</li>
      <li>which: {{which}}</li>
    </ul>
      `,
  host: { '(window:keydown)': 'keyboardInput($event)' }
  /*
  In the "@Component" class decorator you are using the "host" property, this is considered bad practice. 
  Use "@HostBindings", "@HostListeners" property decorator instead.
  */

})
export class App {

  /* a few examples */
  keyboardEvent: any;
  altKey: boolean;
  charCode: number;
  code: string;
  ctrlKey: boolean;
  keyCode: number;
  keyIdentifier: string;
  metaKey: boolean;
  shiftKey: boolean;
  timeStamp: number;
  type: string;
  which: number;

  keyboardInput(event: any) {
    event.preventDefault();
    event.stopPropagation();

    this.keyboardEvent = event;
    this.altKey = event.altKey;
    this.charCode = event.charCode;
    this.code = event.code;
    this.ctrlKey = event.ctrlKey;
    this.keyCode = event.keyCode;
    this.keyIdentifier = event.keyIdentifier;
    this.metaKey = event.metaKey;
    this.shiftKey = event.shiftKey;
    this.timeStamp = event.timeStamp;
    this.type = event.type;
    this.which = event.which;
  }

}

https://plnkr.co/edit/Aubybjbkp7p8FPxqM0zx

1 个答案:

答案 0 :(得分:31)

import {HostListener} from '@angular/core';

@HostListener('window:keydown', ['$event'])
handleKeyDown(event: KeyboardEvent) {
  // event.key === 'ArrowUp'
}
  • @HostBindings('attr.foo') foo = 'bar'用于将组件实例中的值绑定到主机元素,如class,属性,属性或样式。