Skip to content

Instantly share code, notes, and snippets.

@rakia
Created July 10, 2020 18:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rakia/08bb29bf737b3784de87b0dc485fc9be to your computer and use it in GitHub Desktop.
Save rakia/08bb29bf737b3784de87b0dc485fc9be to your computer and use it in GitHub Desktop.
Handling Keyboard Listener in Angular
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