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