Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Angular2 have an equivalent of $document

Tags:

angular

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.

like image 730
Kildareflare Avatar asked Jan 26 '16 21:01

Kildareflare


1 Answers

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

like image 133
Sasxa Avatar answered Oct 16 '22 00:10

Sasxa