Angular 2键盘事件

Angular 2 Keyboard Events

尝试使用typescript用angular2监视键盘事件,angular2创建全局键盘快捷键(又称热键)的方式是什么?有帮助,但tslint(codelyzer)对象带有消息

In the"@Component" class decorator you are using the"host"
property, this is considered bad practice. Use"@HostBindings",
"@HostListeners" property decorator instead.

如何使用推荐的装饰师?我不确定Angular2中的示例:主机绑定和主机监听如何应用于我的用例,因为我没有绑定到任何DOM元素。

这是我的演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
@Component({
  selector: 'my-app',
 template: `
   
      Keyboard Event demo
      Start typing to see KeyboardEvent values
   
    <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
2
3
4
5
6
import {HostListener} from '@angular/core';

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