Angular CTRL + S 提交表单

Angular CTRL + S to submit form

如何在所有申请表中添加调用提交按钮的全局侦听器

当用户按下ctrl+s

我使用模板表单,所有的来源都是 ngForm

我想实现这样的事情:(没有jQuery)

$("#container form").submit();

您可以在全球注册以下活动。 根据您当前使用的表单,触发提交( formSubmit / 触发按钮点击方法)

    document.addEventListener('keydown', e => {
      if (e.ctrlKey && e.key === 's') {
        // Stop app to open save window
        e.preventDefault();
        console.log('CTRL + S Clicked');
        // do your form submission logic here
      }
    });

@HostListener('document:keydown.control.s', ['$event']) onKeydownHandler(event: 
KeyboardEvent) {
   console.log('Submitted');
   event.preventDefault();
   // todo
}

它对我有用:

@Directive({
    selector: 'form'
})
export class SaveCtrlSDirective {

    constructor(private ngForm: NgForm) {
    }

    @HostListener('document:keydown.control.s', ['$event'])  
    onKeydownHandler(event:KeyboardEvent) {
        event.preventDefault();
        (this.ngForm as {submitted: boolean}).submitted = true;
        this.ngForm.ngSubmit.emit(this.ngForm);
    }

}