Angular 2+ elegant way to intercept Command+S

前端 未结 3 1488
刺人心
刺人心 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:41

    1. The methods preventDefault() and stopPropagation() and so on did not work for me (using current Chrome), so i had to go multiple keys: ctrl+shift+s
    2. When defining the event handler in my component, it only worked for this subsite and only if some form inputs were in focus, so i had to add the listener at another place.
    3. I compressed the multiple functions, since i do not care about which environment the hotkey gets called, i want to save my object.
    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;
          }
        }
      });
    }
    

提交回复
热议问题