What is Angular2 way of creating global keyboard shortcuts (a.k.a. hotkeys)?

You can use this syntax in your template

<div (window:keydown)="doSomething($event)">click me<div>

to call this method in your component

doSomething($event) {
  // read keyCode or other properties 
  // from event and execute a command
} 

To listen on the host component itself

@Component({
  selector: 'app-component',
  host: { '(window:keydown)': 'doSomething($event)' },
})
class AppComponent { 
  doSomething($event) {
    ...
  }
}

or by this equivalent syntax

@Component({
  selector: 'app-component',
})
class AppComponent { 
  @HostListener('window:keydown', ['$event'])
  doSomething($event) {
    ...
  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)