Angular 2+ elegant way to intercept Command+S
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
Global listener, non-deprecated answer:
@HostListener('window:keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
if ((event.metaKey || event.ctrlKey) && event.key === 's') {
this.save();
event.preventDefault();
}
}