Angular 5 Button Submit On Enter Key Press

murday1983 picture murday1983 · May 2, 2018 · Viewed 90.5k times · Source

I have an Angular 5 form application using all the usual models but on the forms I want the form to submit without having to physically click on the 'Submit' button.

I know it's normally as easy as adding type=submit to my button element but it does not seem to be working at all.

I don't really want to call an onclick function just to get it working. Can anyone suggest anything that I may be missing.

<form (submit)="search(ref, id, forename, surname, postcode)" action="#">
  <mat-card>
    <mat-card-title class="firstCard">Investor/Adviser search</mat-card-title>
    <mat-card-content>
      <p *ngIf="this.noCriteria" class="errorMessage">Please enter search criteria.</p>
      <p *ngIf="this.notFound" class="errorMessage">No investor's or adviser's found.</p>
        <mat-form-field>
          <input matInput id="invReference" placeholder="Investor/Adviser reference (e.g. SCC/AJBS)" #ref>
        </mat-form-field>
        <mat-form-field>
          <input matInput id="invId" placeholder="Investor/Adviser ID" type="number" #id>
        </mat-form-field>
        <mat-form-field>
          <input matInput id="invForname" placeholder="Forename" #forename>
        </mat-form-field>
        <mat-form-field>
          <input matInput id="invSurname" placeholder="Surname" #surname>
        </mat-form-field>
        <mat-form-field>
          <input matInput id="invPostcode" placeholder="Postcode" #postcode>
        </mat-form-field>
    </mat-card-content>
    <mat-card-footer>
      <button mat-raised-button type="submit" class="successButton" id="invSearch" title="Click to perform search.">Search</button>
    </mat-card-footer>
  </mat-card>
</form>

Answer

shanhaichik picture shanhaichik · May 2, 2018

try use keyup.enter or keydown.enter

  <button type="submit" (keyup.enter)="search(...)">Search</button>