【问题标题】:Custom button component doesn't work on enter自定义按钮组件在输入时不起作用
【发布时间】:2020-10-03 08:58:38
【问题描述】:

在我的 Angular 项目中,我有一个自定义按钮组件,我在整个应用程序中都将其用作提交表单按钮。

问题是当用户想要提交网站上的任何表单时,当焦点位于pro button component 时,回车键不起作用。

这是我的pro-button 组件:

<ng-template [ngIf]="stroked" [ngIfElse]="normalButton">
  <button
    mat-stroked-button
    [color]="color"
    [type]="type"
    [disabled]="disabled"
    tabindex="-1"
    #theButton
  >
    <ng-content></ng-content>
  </button>
</ng-template>
<ng-template [ngIf]="stroked" #normalButton>
  <button
    mat-raised-button
    [color]="color"
    [type]="type"
    [disabled]="disabled"
    tabindex="-1"
    #theButton
  >
    <ng-content></ng-content>
  </button>
</ng-template>

请注意,我知道 Angular 伪事件,并且知道这样的事情可能会起作用:

<pro-button
     color="primary"
     type="submit"
     (keydown.enter)="onSubmit()"
     #submitButton
>
   submit
</pro-button>

但我在我的项目中经常使用pro-button component,我认为继续将(keydown.enter)="onSubmit()" 添加到我的所有pro-button 选择器中并不是一个好习惯。

【问题讨论】:

    标签: javascript angular form-submit event-delegation


    【解决方案1】:

    我通过将这段代码添加到pro-button.component.ts 文件来解决了这个问题:

      @ViewChild('theButton') theButton: any;
    
      constructor(private renderer: Renderer2, private el: ElementRef) {
        (el.nativeElement as HTMLElement).tabIndex = 0;
      }
    
     @HostListener('keydown.enter', ['$event'])
      handleKeyboardEvent(event: KeyboardEvent) {
        if(this.type === 'submit' && !this.disabled) {
          this.getButtonElement().click();
        };
      }
    
      private getButtonElement(): HTMLButtonElement {
        return (
          this.theButton.nativeElement || this.theButton._elementRef.nativeElement
        );
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      相关资源
      最近更新 更多