How can I listen for keypress event on the whole page?

后端 未结 6 1781
耶瑟儿~
耶瑟儿~ 2020-11-28 03:35

I\'m looking for a way to bind a function to my whole page (when a user presses a key, I want it to trigger a function in my component.ts)

It was easy in AngularJS w

6条回答
  •  盖世英雄少女心
    2020-11-28 03:46

    If you want to perform any event on any specific keyboard button press, in that case, you can use @HostListener. For this, you have to import HostListener in your component ts file.

    import { HostListener } from '@angular/core';
    then use below function anywhere in your component ts file.

    @HostListener('document:keyup', ['$event'])
      handleDeleteKeyboardEvent(event: KeyboardEvent) {
        if(event.key === 'Delete')
        {
          // remove something...
        }
      }
    

提交回复
热议问题