2017-02-20 179 views
12

我正在使用以下方法來檢測頁面上的按鍵。我的計劃是檢測何時按Escape鍵並運行方法。目前我只是試圖記錄哪個鍵被按下。但是,Escape鍵從未被檢測到。Angular 2 HostListener按鍵檢測轉義鍵?

@HostListener('document:keypress', ['$event']) 
handleKeyboardEvent(event: KeyboardEvent) { 
    console.log(event); 
    let x = event.keyCode; 
    if (x === 27) { 
     console.log('Escape!'); 
    } 
} 

回答

19

與​​或keyup事件試試吧捕捉Esc關鍵。

+1

感謝兄弟。你讓我今天一整天都感覺很好! –

+0

要決定使用哪一個關鍵事件,請檢查以下答案:https://stackoverflow.com/a/46403258/3380547 – Sagar

+0

這只是'keyup'對我的工作:豎起大拇指: – vincecampanale

15

它使用下面的代碼爲我工作:

const ESCAPE_KEYCODE = 27; 

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

或在更短的方式:

@HostListener('document:keydown.escape', ['$event']) onKeydownHandler(evt: KeyboardEvent) { 
    // ... 
} 
0

現代的方法

@HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) { 
    if (event.key === "Escape") { 
     // Do things 
    } 
}