【问题标题】:Is there a way to disable submit button when enter key is pressed in Angular?在Angular中按下回车键时,有没有办法禁用提交按钮?
【发布时间】:2022-06-14 09:29:57
【问题描述】:

扫描信标设备时,扫描器会在末尾发送信标 ID 和“Enter”键。有时,用户扫描信标设备并单击提交按钮会导致多次调用 onSubmit()。是否可以在按下“Enter”键后禁用提交按钮,从而阻止用户点击提交按钮?
注意:需要保持启用“Enter”键以使其与应用程序中的其他 UI 保持一致。因此,将按钮类型从“提交”更改为“按钮”或阻止“回车”键不是一种选择。

<form [formGroup]="commissioningForm"  class=commission-form #formGroupDirective> 
      <mat-form-field appearance="standard">
        <mat-label>Beacon Id</mat-label>
        <input #beaconIdEle matInput placeholder="Scan or type..." formControlName="beaconId" autocomplete="off" specialCharacterRegex/>
        <mat-error *ngIf="beaconId.invalid">Not a valid Beacon Id.</mat-error>
      </mat-form-field>
      <br />
      <br />
      <button type="submit" (click)="onSubmit()" [disabled]="commissioningForm.invalid" mat-raised-button>
        Submit
      </button>
 </form>

在 onSubmit() 中尝试了以下代码,但由于异步方法调用而无法正常工作,因为 processingSubmit 立即被重置为 false。

    onSubmit() {
    if( !this.processingSubmit )
    {  this.processingSubmit = true;
       this.async_method_call();
       this.processingSubmit = false;
       return true;
    }
    else
    {
      return false;
    }
  }

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以对按钮使用以下禁用条件:

    <button type="submit" (click)="onSubmit()" [disabled]="formGroupDirective.submitted || formGroupDirective.submitted"  mat-raised-button>
        Submit
    </button>
    

    【讨论】:

      【解决方案2】:

      我想你可以用 (focus) (blur) 和 (keydown.enter) 来“玩”

      声明一个变量

      disabled:boolean=false
      

      并使用

      <input (focus)="disabled=true" 
             (blur)="disabled=false" 
             (keydown.enter)="btSubmit.focus();$event.preventDefault()">
      
      <button #btSubmit (click)="!disabled && onSubmit()">click</button>
      

      【讨论】:

        【解决方案3】:
        onSubmit() {
        
        if( !this.processingSubmit )
        {
          this.processingSubmit = true;
          this.async_method_call();
        }
        

        }

        在所有处理完成后使用布尔变量并将其重置为 false(以不同的方法),这是我能够忽略多次“Enter”按键或提交按钮点击的唯一方法。上面提供的其他解决方案主要是因为 Async 方法调用而不起作用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-20
          • 2021-06-12
          • 2011-08-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多