Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 prevent enter from submitting in template-driven form

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?

like image 587
Chrillewoodz Avatar asked Nov 17 '16 11:11

Chrillewoodz


People also ask

How do you avoid implicit form submission?

You can also use javascript:void(0) to prevent form submission.

What is the use of [( ngModel )] in template driven form?

The ngModel directive declared in the FormsModule lets you bind controls in your template-driven form to properties in your data model.


2 Answers

Turns out that you can use something as simple as:

<form (keydown.enter)="$event.preventDefault()"></form> 

To prevent the form from submitting on ENTER.

like image 100
Chrillewoodz Avatar answered Oct 02 '22 21:10

Chrillewoodz


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.

like image 20
bharatpatel Avatar answered Oct 02 '22 21:10

bharatpatel