Reactive Forms: replacing the enter key submit with a different function on some controls

Viewed 170

I'm learning reactive forms and writing a simple application to help my understanding. I've got a couple text inputs that are used to modify the FormGroup and there is a button in place to execute the function that does so, but I find that I've been naturally hitting enter when trying to fill in those fields and accidentally triggering the form submit. I'm wondering if there is a way to prevent the normal submit behavior on the enter key, but only while some fields have focus, I would like to keep the enter key submit functionality in all other cases and not disable it entirely.

2 Answers

Try adding validations, and only submit when the forms are valid.

This can be done by adding validations in Reactive form fields.

Plus for specific fields, you can listen for change event / focus event and set a bool to stop form submission. Set disabled property on submit input / submit button with value of bool. So when specific fields will have focus / change event (whatever functionality is required) the submit input / button will be disabled. However, to enable the submit input set bool to false in blur (lost focus) event ((blur)="methodhere($event)") of the field(s). This will again enable the submit input.

Another way is for specific fields, you can listen for change event / focus event and set a bool to stop form process in form submit method. i.e. form will be submitted but will not process further in form submit method.

Related