Angular 2 HostListener keypress detect escape key?

前端 未结 6 1099
温柔的废话
温柔的废话 2020-12-24 01:47

I am using the following method to detect keypresses on a page. My plan is to detect when the Escape key is pressed and run a method if so. For the moment I am just attempti

相关标签:
6条回答
  • 2020-12-24 02:08

    Angular makes this easy with the @HostListener decorator. This is a function decorator that accepts an event name as an argument. When that event gets fired on the host element it calls the associated function.

    @HostListener('document:keydown.escape', ['$event']) onKeydownHandler(event: 
        KeyboardEvent) {
        this.closeBlade();
       }
    
    0 讨论(0)
  • 2020-12-24 02:24

    Modern approach, event.key == "Escape"

    The old alternatives (.keyCode and .which) are Deprecated.

    @HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {
        if (event.key === "Escape") {
            // Do things
        }
    }
    
    0 讨论(0)
  • 2020-12-24 02:25

    In my case (with Angular 10) keydown.escape works fine to track event escape by console.log():

    @HostListener('keydown.escape')
    fn() {
     console.log();
    }
    

    But Angular change detector work fine only with keyup.escape.

    0 讨论(0)
  • 2020-12-24 02:27

    Try it with a keydown or keyup event to capture the Esc key. In essence, you can replace document:keypress with document:keydown.escape:

    @HostListener('document:keydown.escape', ['$event']) onKeydownHandler(event: KeyboardEvent) {
        console.log(event);
    }
    
    0 讨论(0)
  • 2020-12-24 02:29

    keydown and keyup seem to work: http://embed.plnkr.co/VLajGbWhbaUhCy3xss8l/

    0 讨论(0)
  • 2020-12-24 02:30

    It worked for me using the following code:

    const ESCAPE_KEYCODE = 27;
    
    @HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {
        if (event.keyCode === ESCAPE_KEYCODE) {
            // ...
        }
    }
    

    or in shorter way:

    @HostListener('document:keydown.escape', ['$event']) onKeydownHandler(evt: KeyboardEvent) {
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题