Angular 2 HostListener keypress detect escape key?

前端 未结 6 1130
温柔的废话
温柔的废话 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: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) {
        // ...
    }
    

提交回复
热议问题