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:
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:
Here is a plunker link: PLUNKER DEMO