what-is-angular2-way-of-creating-global-keyboard-shortcuts
只有我有兴趣将快捷方式绑定到特定元素(或容器,如果你愿意)。快捷方式应仅适用于用户焦点位于元素或其子节点之间,当元素从dom中删除时,绑定自然应随之删除。
我找到了一些方法来做这些我发现不太干净:
/**
* Created by Ziv on 5/23/2016.
*/
import {Injectable} from "angular2/core";
@Injectable()
export class KeyBoardService {
public registerKeyStrokeForElemet(
strKeyStroke: string,
fnCallBack: () => void,
fnIsButtonAvailable: () => boolean,
element: any,
bShouldEffectOnlyInContainer: boolean,
functionThisContext: any): void {
// Adding tab index property to the container so the events will be raised only when
// the container is focused
jQuery(element).prop("tabindex", 1);
jQuery(element).css("outline", "none");
jQuery(element).bind(
'keystrokes', {
keys: [strKeyStroke]
}, (e) => {
// Checking if this event should only happen when the div container is focused
if (!bShouldEffectOnlyInContainer || jQuery(e.target).is("div")) {
if (typeof fnIsButtonAvailable !== "function" || fnIsButtonAvailable.apply(functionThisContext, event)) {
e.preventDefault();
fnCallBack.apply(functionThisContext);
}
}
}
);
// If the event should effect all the elements inside the container too,
// there is a special case when events in jquery keystroke library ignored text inputs.
// the solution offered by the libraray author is to assign thoose events to them inputs
// explicitly, which is what were gonna do next
if (!bShouldEffectOnlyInContainer)
{
jQuery(element).find(
"textarea, :text"
).bind(
'keystrokes',
{
keys: [strKeyStroke]
},
(e) => {
if (typeof fnIsButtonAvailable === "function" || fnIsButtonAvailable.apply(functionThisContext, event)) {
e.preventDefault();
fnCallBack.apply(functionThisContext);
}
}
);
}
}
}
它依赖于使用jquery-keystrokes jquery keystrokes 这有点旧,一般我发现在角度2应用程序中使用很多jquery相当脏,所以我正在寻找“角度方式”来实现这个
答案 0 :(得分:2)
这应该让你开始......
要收听DOM元素上的击键(例如,div
),您可以创建一个使用
tabindex
属性添加到div
(so the div will get keyboard events)div
及其子级import {Component, Directive, Input, HostBinding, HostListener} from '@angular/core';
@Directive({selector: '[catchkeys]'})
export class CatchKeys {
// add tabindex attribute so host element (e.g., a div) will receive keyboard events
// https://stackoverflow.com/questions/10722589/how-to-bind-keyboard-events-to-div-elements
@HostBinding('tabindex') tabIndex = 1;
@HostListener('keyup', ['$event'])
onKeyUp(kbdEvent) {
console.log(kbdEvent);
}
}
@Component({
selector: 'child',
template: `<div catchkeys>child: {{msg}}
<div>child element</div>
</div>`,
directives: [CatchKeys]
})
class Child {
@Input() msg:string;
}
要过滤特定键,请将列表传递到CatchKeys指令:
<div catchkeys="someListOfKeys">
然后修改指令:
@Input() catchkeys:string; // or maybe use an Array
ngOnInit() {
console.log(this.catchkeys);
}
// use this.catchkeys in the onKeyUp() method to filter