Home > Mobile >  Is there a way to disable submit button when enter key is pressed in Angular?
Is there a way to disable submit button when enter key is pressed in Angular?

Time:06-10

When a beacon device is scanned, scanner sends the beacon id and an 'Enter' key at the end. Sometimes, users scans the beacon device and also click Submit button resulting in multiple calls to onSubmit(). Is it possible to disable the submit button after 'Enter' key is pressed, which will prevent users from clicking the submit button?
Note: Need to keep the 'Enter' key enabled to make it consistent with other UIs in the application. So, changing button type from 'submit' to 'button' or preventing 'Enter' key is not an option.

<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>

Tried following code in onSubmit(), but didn't work due to async method call due to which processingSubmit was reset to false right away.

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

CodePudding user response:

You can use the following disabled condition with the button:

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

CodePudding user response:

I imagine you can "play" with (focus) (blur) and (keydown.enter)

Declare a variable

disabled:boolean=false

And use

<input (focus)="disabled=true" 
       (blur)="disabled=false" 
       (keydown.enter)="btSubmit.focus();$event.preventDefault()">

<button #btSubmit (click)="!disabled && onSubmit()">click</button>
  • Related