是否有Angular2 $文件的等效 [英] Does Angular2 have an equivalent of $document
问题描述
我已经开始寻找到Angular2,有一个基本与3嵌套其它的组件工作。不过,我不能工作,如何一键preSS处理程序添加到文档中。
I've started looking into Angular2 and have a basic up with 3 nested componenets working. However I cannot work out how to add a keypress handler to the document.
如果不是,我怎么会听文档上的关键preSS和反应?
需要明确的是,我需要对文档本身kepyress响应,而不是输入。
If not, how would I listen for a keypress on the document and react to it? To be clear I need to respond to a kepyress on the document itself, NOT an input.
在角1我会创造一个指令,并使用$文件;是这样的:
In Angular 1 I would create a directive and use $document; something like this:
$document.on("keydown", function(event) {
// if keycode...
event.stopPropagation();
event.preventDefault();
scope.$apply(function() {
// update scope...
});
但我还没有找到一个解决方案Angular2
But I have yet to find an Angular2 solution.
推荐答案
您可以做这样的事情:
@Component({
host: {
'(document:keyup)': '_keyup($event)',
'(document:keydown)': '_keydown($event)',
},
})
export class Component {
private _keydown(event: KeyboardEvent) {
let prevent = [13, 27, 37, 38, 39, 40]
.find(no => no === event.keyCode);
if (prevent) event.preventDefault();
}
private _keyup(event: KeyboardEvent) {
if (event.keyCode === 27) this.close();
else if (event.keyCode === 13) ...;
else if (event.keyCode === 37) ...;
else if (event.keyCode === 38) ...;
else if (event.keyCode === 39) ...;
else if (event.keyCode === 40) ...;
// else console.log(event.keyCode);
}
}
BTW,角队有一些有趣的<一个href=\"https://github.com/angular/angular/blob/909031e6887175b380492119df3b694d164c66eb/modules/angular2/test/platform/dom/events/key_events_spec.ts\"相对=nofollow>有关键盘事件的想法的,不知道是这个此刻的状态。它甚至可以它的工作,没有尝试自己:)
BTW, Angular team had some interesting ideas about keyboard events, not sure what's the status of this at the moment. It's even possible it's working, didn't try myself :)
这篇关于是否有Angular2 $文件的等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!