Angular 2 prevent enter from submitting in template-driven form

Chrillewoodz picture Chrillewoodz · Nov 17, 2016 · Viewed 44.4k times · Source

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?

Answer

Chrillewoodz picture Chrillewoodz · Nov 17, 2016

Turns out that you can use something as simple as:

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

To prevent the form from submitting on ENTER.