Sunday, July 15, 2018

How can I listen for keypress event on the whole page in AngularJS 2 – 6

Add following line on @component decorator class
host: {‘(document:keypress)’: ‘handleKeyboardEvent($event)’}
and implement handleKeyboardEvent(event:KeyboardEvent)
i.e.
@Component({
selector:’app-add-component’,
templateUrl:’./add-component.component.html’,
styleUrls: [‘./add-component.component.css’],
// tslint:disable-next-line:use-host-property-decorator
host: {‘(document:keypress)’:’handleKeyboardEvent($event)’}
})
handleKeyboardEvent(event: KeyboardEvent) {
console.log(event);
if (event.keyCode===13)
{
console.log(“Enter key pressed 13”);
} else if (event.keyCode === 40)
{
} else if (event.keyCode === 38)
{
}
}

No comments: