Angular 2+ elegant way to intercept Command + S

Trying to implement a keyboard shortcut for Command + S to save a form.

I read this - https://angular.io/guide/user-input , but it doesn't say anything about the meta or command.

Tried the form environment:

<div
  (keyup.command.s)="save()"
  (keyup.command.u)="save()"
  (keyup.control.u)="save()"
  (keyup.control.s)="save()"
  (keyup.meta.u)="save()"
>

Of these, only control.uand worked control.s.

Thanks to all the powerful and cross-browser capabilities of Angular 2+, I was hoping that it would somehow be handled in an elegant way using (keyup...).

And for sure, many Angular Devs use Macs :).

Mac JavaScript? http://unixpapa.com/js/key.html, Angular , ...

+6
1

UPDATE

, keydown keyup $event.preventDefault();. :

  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();
    } 
  }

(keydown) div:

<div (keydown)="onKeyDown($event)" tabindex="0">
</div>

PLUNKER DEMO


, :

  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();
    } 
  }

(keyup) div:

<div (keyup)="onKeyUp($event)" tabindex="0">
</div>

plunker: PLUNKER DEMO

+2

All Articles