Search code examples
angulartypescriptkeydownenteronkeydown

How to trigger button by pressing enter in Angular 9


Is it possible to trigger my "Add" button by pressing enter on the keyboard?

////

enter image description here

This is the last div in the form, for the third gap:

  <div fd-form-item *ngIf="targetType.value != null">
    <label fd-form-label for="input-showroom-hostname" [required]="true">URL:</label>
    <fd-form-input-message-group>
      <input
        fd-form-control
        type="text"
        id="input-showroom-hostname"
        placeholder="e.g. l2w.demo.hybris.com"
        formControlName="hostname"
        [state]="determineFormControlState(hostname)"
      />
      <fd-form-message *ngIf="hasRequiredErrors(hostname)" [type]="'error'"> {{ REQUIRED }} </fd-form-message>
      <fd-form-message *ngIf="hasShowroomUserRightsErrors(hostname)" [type]="'error'"> {{ SHOWROOM_USER_RIGHTS }}</fd-form-message>
      <fd-form-message *ngIf="hasPatternErrors(hostname)" [type]="'error'"> {{ URL_PATTERN }} </fd-form-message>
    </fd-form-input-message-group>
  </div>
  <br />
</div>

Solution

  • Add an event on the last input element and the button. Use (keydown.enter)='add_showroom()' on the last input.

    Below is some minimal code of the idea. Also check the StackBlitz if you want.

    xx.component.html

    <button (click)='add_showroom()'>Add</button><br>
    <select>
      <option>Option 1</option>
      <option>Option 2</option>
      <option>Option 3</option>
      <option>Option 4</option>
    </select><br>
    <input (keydown.enter)='add_showroom()' type='text'/>
    

    xx.component.ts

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      public add_showroom() {
        alert('adding showroom');
      }
    }
    

    Some extra tips:

    • Check if the form is valid before processing the enter click.
    • Add (keydown.enter)='add_showroom()' only to the last element. This is generally speaking better than adding it to an area or multiple elements, because that could lead to unexpected behaviour for someone using enter to navigate somewhere. Or using enter to select a value from a dropdown.
    • Be very careful using this. Your user may not expect an enter click to submit the form. So UX-wise it is a bit of a grey area. At least notify your user about this behaviour somehow.