Skip to content

Instantly share code, notes, and snippets.

@corneil
Created September 22, 2019 18:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save corneil/4a75adec82b157a6bce3e9f5dff31c7b to your computer and use it in GitHub Desktop.
Save corneil/4a75adec82b157a6bce3e9f5dff31c7b to your computer and use it in GitHub Desktop.
Angular form submission on enter key.

While playing with Ionic I came across an error when pressing enter in a form.

onloadwff.js:71 Uncaught TypeError: Cannot read property 'type' of undefined
    at setFieldValue (onloadwff.js:71)
    at HTMLFormElement.formKeydownListener (onloadwff.js:71)

You would expect the form to submit if one of the buttons is a submit button.

I tried by adding (keydown.enter)="submitForm()" (ngSubmit)="submitForm()" to the form element. But now enter causes the submitForm to be called twice. Turns out NgForm has the solution:

Add #triggerForm="ngForm" to the form element and ensure the enter key calls a different function which will trigger the submit event as if clicking the button.

<form [formGroup]="myForm" #triggerForm="ngForm" (keydown.enter)="triggerSubmit()" (ngSubmit)="submitForm()">
    <!-- form controls -->
</form>

In your component use @ViewChild to bind an NgForm to the triggerForm. In the aforementioned function emit the event.

export class MyForm {
  // This can be moved to a common base class
  @ViewChild('triggerForm', {static: false})
  triggerForm: NgForm;

  myForm: FormGroup;
  // This can be moved to a common base class.
  triggerSubmit() {
    if (!this.triggerForm) {
      console.warn('triggerForm not assigned a value');
    } else {
      if (this.triggerForm.valid) {
        this.triggerForm.ngSubmit.emit();
      }
    }
  }

  submitForm() {
    // do what you need to submit the form
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment