Angular 2键盘事件

尝试使用TypeScript监控Angular 2的键盘事件,以及什么是Angular2创建全局键盘快捷键(又名热键)的方式? 是有帮助的,但tslint(codelyzer)与消息对象

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

我如何使用推荐的装饰器? 我不确定Angular 2中的例子:主机绑定和主机监听适用于我的用例,因为我没有绑定到任何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


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

@HostListener('window:keydown', ['$event'])
keyboardInput(event: KeyboardEvent) {

@HostBindings('attr.foo') foo = 'bar'用于将组件实例的值绑定到主机元素,如class ,属性,属性或样式。

链接地址: http://www.djcxy.com/p/40693.html

上一篇: Angular 2 Keyboard Events

下一篇: Accessing a property in a parent Component in Angular2 with TypeScript