13

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.

1 Answer 1

16

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

5
  • I haven't seen the document:keyup syntax before. Do you have any references for that so I can learn more? Jan 26, 2016 at 22:18
  • @MarkRajcok Not sure where I found it for the first time.. I know I saw <input #box (keyup.enter)="values=box.value"> at official Developer Guides - look for Key event filtering... I'll try to find where I got document:_event_ syntax. Works with window:click too, for example.
    – Sasxa
    Jan 26, 2016 at 22:29
  • 1
    @MarkRajcok I was looking for "click outside" some time ago, and I found the code for Angular2 Modal. After that I looked through source code for key_events and with some experimenting I got to this syntax...
    – Sasxa
    Jan 26, 2016 at 22:53
  • 1
    So almost 2 months later I found it... Buried deep in the API doc for DirectiveMetadata, under the host property we find these words: "To listen to global events, a target must be added to the event name. The target can be window, document or body." Mar 21, 2016 at 18:24
  • 1
    The link to the host property changed: angular.io/docs/ts/latest/api/core/… (I wish there was a way to edit comments). Apr 18, 2016 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.