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

后端 未结 3 1987
花落未央
花落未央 2020-12-29 20:06

What would be proper way of creating global keyboard shortcuts (a.k.a. hotkeys) in Angular2 application?

Let\'s say good starting point would be to get working: \"?

3条回答
  •  [愿得一人]
    2020-12-29 21:05

    You can use this syntax in your template

    click me

    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) {
        ...
      }
    }
    

提交回复
热议问题