Angular 2+ elegant way to intercept Command+S

前端 未结 3 1504
刺人心
刺人心 2021-02-20 00:10

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

3条回答
  •  长发绾君心
    2021-02-20 00:24

    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

提交回复
热议问题