Đang cố gắng để theo dõi các sự kiện bàn phím với góc 2 sử dụng nguyên cảo và What is Angular2 way of creating global keyboard shortcuts (a.k.a. hotkeys)? là hữu ích nhưng tslint (codelyzer) các đối tượng với thông điệpgóc 2 Keyboard Sự kiện
Trong "@Component" lớp trang trí bạn đang sử dụng "máy chủ " tài sản, đây được coi là thực hành không tốt. Sử dụng "@HostBindings", "@HostListeners" trang trí thuộc tính để thay thế.
Tôi làm cách nào để sử dụng các trình trang trí được đề xuất? Tôi không chắc làm thế nào các ví dụ trong Angular 2: Host binding and Host listening áp dụng cho trường hợp sử dụng của tôi vì tôi không ràng buộc với bất kỳ phần tử DOM nào.
Dưới đây là bản demo của tôi
@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
FYI - người plunker được tham chiếu ở trên không hoạt động đối với tôi trong IE 11, nhưng nó hoạt động độc đáo trong Chrome. Nó bị mắc kẹt tại Loading ... –
host: { '(cửa sổ: KeyDown)': 'keyboardInput ($ sự kiện)'} và keyboardInput (sự kiện: có) {} là câu trả lời, thanx !! ! –