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

后端 未结 6 1748
耶瑟儿~
耶瑟儿~ 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...
        }
      }
    
    0 讨论(0)
  • 2020-11-28 03:49

    Be aware "document:keypress" is deprecated. We should use document:keydown instead.

    Link: https://developer.mozilla.org/fr/docs/Web/API/Document/keypress_event

    0 讨论(0)
  • 2020-11-28 03:56

    Just to add to this in 2019 w Angular 8,

    instead of keypress I had to use keydown

    @HostListener('document:keypress', ['$event'])
    

    to

    @HostListener('document:keydown', ['$event'])
    

    Working Stacklitz

    0 讨论(0)
  • 2020-11-28 03:58

    I would use @HostListener decorator within your component:

    import { HostListener } from '@angular/core';
    
    @Component({
      ...
    })
    export class AppComponent {
    
      @HostListener('document:keypress', ['$event'])
      handleKeyboardEvent(event: KeyboardEvent) { 
        this.key = event.key;
      }
    }
    

    There are also other options like:

    host property within @Component decorator

    Angular recommends using @HostListener decorator over host property https://angular.io/guide/styleguide#style-06-03

    @Component({
      ...
      host: {
        '(document:keypress)': 'handleKeyboardEvent($event)'
      }
    })
    export class AppComponent {
      handleKeyboardEvent(event: KeyboardEvent) {
        console.log(event);
      }
    }
    

    renderer.listen

    import { Component, Renderer2 } from '@angular/core';
    
    @Component({
      ...
    })
    export class AppComponent {
      globalListenFunc: Function;
    
      constructor(private renderer: Renderer2) {}
    
      ngOnInit() {
        this.globalListenFunc = this.renderer.listen('document', 'keypress', e => {
          console.log(e);
        });
      }
    
      ngOnDestroy() {
        // remove listener
        this.globalListenFunc();
      }
    }
    

    Observable.fromEvent

    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/fromEvent';
    import { Subscription } from 'rxjs/Subscription';
    
    @Component({
      ...
    })
    export class AppComponent {
      subscription: Subscription;
    
      ngOnInit() {
        this.subscription = Observable.fromEvent(document, 'keypress').subscribe(e => {
          console.log(e);
        })
      }
    
      ngOnDestroy() {
        this.subscription.unsubscribe();
      }
    }
    
    0 讨论(0)
  • 2020-11-28 03:59

    yurzui's answer didn't work for me, it might be a different RC version, or it might be a mistake on my part. Either way, here's how I did it with my component in Angular2 RC4 (which is now quite outdated).

    @Component({
        ...
        host: {
            '(document:keydown)': 'handleKeyboardEvents($event)'
        }
    })
    export class MyComponent {
        ...
        handleKeyboardEvents(event: KeyboardEvent) {
            this.key = event.which || event.keyCode;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 04:06

    I think this does the best job

    https://angular.io/api/platform-browser/EventManager

    for instance in app.component

    constructor(private eventManager: EventManager) {
        const removeGlobalEventListener = this.eventManager.addGlobalEventListener(
          'document',
          'keypress',
          (ev) => {
            console.log('ev', ev);
          }
        );
      }
    
    0 讨论(0)
提交回复
热议问题