How to submit a form by pressing Enter Key from any field in the form in Angular Material?

5.2k views Asked by At

I want to submit the form by pressing enter key without clicking on update button once any field is edited and update button gets enabled as below in the screenshot.

This update form is a dialog which opens up on click of edit functionality on a row of the table. enter image description here

Case: Now form is edited on Emp Code field and it's highlighted, so on click of enter key this form should be submitted.

Below is code sample of update form in HTML.

<mat-card-content>
    <form class="example-form" [formGroup]="docForm">
      <table>
        <tr>
          .
          .
          <td>
            <mat-form-field appearance="outline">
              <mat-label>Emp Code</mat-label>
              <input matInput name="empCode" formControlName="empCd" maxLength = "4" >
            </mat-form-field>
          </td>
         .
         .
       </tr>
      </table>
    </form>
</mat-card-content>

<button mat-raised-button style="width: 95px;" color="primary" [disabled]='docForm.invalid || !docForm.dirty (click)="update()"> Update </button>

I tried some approach, but not working as expected.

 <button mat-raised-button (keyup.enter)="!($event.target.tagName == 'TEXTAREA' || $event.target.tagName == 'BUTTON')" 
  style="width: 95px;" color="primary" [disabled]='docForm.invalid || !docForm.dirty' (click)="update()"> Update </button>

Thanks in advance for any help on this.

1

There are 1 answers

6
bryan60 On BEST ANSWER

you should be able to just bind to the ngSubmit event:

<form class="example-form" [formGroup]="docForm" (ngSubmit)="docForm.valid && docForm.dirty && update()">

for this to trigger, you need a submit type element somewhere inside your form, it may be hidden though:

<input [style.display]="'none'" type="submit">

or if you prefer, you may just bind to the keyup.enter event on the form:

<form class="example-form" [formGroup]="docForm" (keyup.enter)="docForm.valid && docForm.dirty && update()">