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

后端 未结 3 1975
花落未央
花落未央 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 20:59

    A simple and elegant solution will look like as following:-

    Create a global service, which will store the bindings of shortcuts with clickable elements. Note:- Use NgOnDestroy, for removing bindings on component is destroyed.

    Now create a directive, which will take keycodes as input like this.

    
    
    

    Now in your root most component, listen keypresses and use them as indices for locating Elements in Global Service for HotKeys. Now on getting the reference do something like this.

    I assume you have formatted recorded keycodes in this format = 1-23-32-... , dont forget to sort them in ascending/descending format, both while adding it to keypair array in service and while checking

    if(this.keypair[combo].length)this.keypair[combo].click();
    

    this.keypair[combo] contain reference of element on which angularHotKey directive was added.

    Further Notes: 1.) In angularHotKey directive while adding new keypair and element/clickable reference please check if there don't exist pairing with same combo, if yes throw a exception, it will be helpful while debugging, and prevent you from doing silly mistakes, and in Angular 2 component class,in ngOnDestroy method define a logic of removing all shortcuts paired with it's child elements.

    Visit http://keycode.info/ for getting keycodes for all types of keys present on your keyboard.

    JavaScript multiple keys pressed at once A answer with every little detail about how to deal with combo key presses

提交回复
热议问题