当前位置: 动力学知识库 > 问答 > 编程问答 >

Does Angular2 have an equivalent of $document

问题描述:

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.

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.

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...

});

But I have yet to find an Angular2 solution.

网友答案:

You can do something like this:

@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, 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 :)

分享给朋友:
您可能感兴趣的文章:
随机阅读: