Trying to implement a shortcut key combination for Command+S to save a form.
I\'ve read this - https://angular.io/guide/user-input, but it does not say anything about me
UPDATE
To stop the save dialog of the browser from opening, we must use the keydown
event instead of keyup
and call the function $event.preventDefault();
. Updated code below:
onKeyDown($event): void {
// Detect platform
if(navigator.platform.match('Mac')){
this.handleMacKeyEvents($event);
}
else {
this.handleWindowsKeyEvents($event);
}
}
handleMacKeyEvents($event) {
// MetaKey documentation
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/metaKey
let charCode = String.fromCharCode($event.which).toLowerCase();
if ($event.metaKey && charCode === 's') {
// Action on Cmd + S
$event.preventDefault();
}
}
handleWindowsKeyEvents($event) {
let charCode = String.fromCharCode($event.which).toLowerCase();
if ($event.ctrlKey && charCode === 's') {
// Action on Ctrl + S
$event.preventDefault();
}
}
Then bind this method to the (keydown)
event in your div:
<div (keydown)="onKeyDown($event)" tabindex="0">
</div>
Updated PLUNKER DEMO
ORIGINAL ANSWER
Here is an idea, how about detecting the event in you class:
onKeyUp($event): void {
// Detect platform
if(navigator.platform.match('Mac')){
this.handleMacKeyEvents($event);
}
else {
this.handleWindowsKeyEvents($event);
}
}
handleMacKeyEvents($event) {
// MetaKey documentation
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/metaKey
let charCode = String.fromCharCode($event.which).toLowerCase();
if ($event.metaKey && charCode === 's') {
// Action on Cmd + S
$event.preventDefault();
}
}
handleWindowsKeyEvents($event) {
let charCode = String.fromCharCode($event.which).toLowerCase();
if ($event.ctrlKey && charCode === 's') {
// Action on Ctrl + S
$event.preventDefault();
}
}
Then bind this method to the (keyup)
event in your div:
<div (keyup)="onKeyUp($event)" tabindex="0">
</div>
Here is a plunker link: PLUNKER DEMO
ngOnInit() {
document.body.addEventListener("keydown", event => {
let charCode = String.fromCharCode(event.which).toLowerCase();
switch (((navigator.platform.match('Mac') && event.metaKey) || event.ctrlKey) && event.shiftKey && charCode === 's') {
case true: {
this.saveArticle(); //whatever your usecase is
break;
}
}
});
}
Global listener, non-deprecated answer:
@HostListener('window:keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
if ((event.metaKey || event.ctrlKey) && event.key === 's') {
this.save();
event.preventDefault();
}
}