I have forms that uses the template-driven blueprint, so something like this:
<form #myForm="ngForm" ngSubmit="save(myForm.value, myForm.isValid)"> <input #name="ngModel" [(ngModel)]="name"> <button type="submit">Submit form</button> </form>
Now, how can I prevent ENTER from submitting the form? It interferes with custom ENTER behaviour inside of the form and also if you accidentally press enter in an input, which is unwanted.
I've looked around and found some old Angular 1 answers and also some standard JavaScript ones but I feel that Angular 2 must have something like this already built in but I haven't been able to find it.
If they don't, what would be the best way to achieve this?
You can also use javascript:void(0) to prevent form submission.
The ngModel directive declared in the FormsModule lets you bind controls in your template-driven form to properties in your data model.
Turns out that you can use something as simple as:
<form (keydown.enter)="$event.preventDefault()"></form>
To prevent the form from submitting on ENTER.
I know i am late, but may be i got proper solution for this,
if you are using <button
> then just define
<button type="button">
rather not defining it or defining it as type="submit" because if you dont define it, it will submit your form.
Same if you are using <input>
then also define
<input type="button">
and this will work.
-- Edited As @Chrillewoodz comment.
If you wish to do some specific process on submit/click You can add click event to button, and in that you can do what ever you want.
If you want Form tag in angular ts files, then you can use @ViewChild.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With