Created
July 10, 2020 18:28
-
-
Save rakia/08bb29bf737b3784de87b0dc485fc9be to your computer and use it in GitHub Desktop.
Handling Keyboard Listener in Angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, HostListener } from '@angular/core'; | |
@Component({ | |
selector: 'app-keyboard-listener', | |
templateUrl: './keyboard-listener.component.html', | |
styleUrls: ['./keyboard-listener.component.css'] | |
}) | |
export class KeyboardListenerComponent { | |
// Listener just for one key | |
@HostListener('keydown.esc', ['$event']) | |
onEsc(event: KeyboardEvent) { | |
// some logic here | |
} | |
// handler of the keyup event | |
@HostListener('document:keyup', ['$event']) | |
onKeyUp(event: KeyboardEvent): void { | |
let keysToIgnore: string[] = ['PrintScreen', 'Escape', 'cControl', 'NumLock', 'PageUp', 'PageDown', 'End', | |
'Home', 'Delete', 'Insert', 'ContextMenu', 'Control', 'ControlAltGraph', 'Alt', 'Meta', 'Shift', 'CapsLock', | |
'TabTab', 'ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp', 'Pause', 'ScrollLock', 'Dead', '', | |
'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12']; | |
if(this.indexOfInArray(event.key, keysToIgnore) === -1) { // if it's not a special key | |
if(event.key === 'Enter') { | |
// some logic here | |
} else { | |
// some logic here | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment