Button in Angular form being "clicked" when I press enter

Viewed 569

I'm have a strange issue in my Angular form. I have a simple form like the following:

<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
      <button (click)="addUser()">Add a user</button>

      <input name="first" ngModel required #first="ngModel">
      <input name="last" ngModel>

      <button>Submit</button>
</form>

The problem is that when I press ENTER when in the form, instead of submitting, it fires the function addUser(), which is not what I want it to do.

How do I stop it from "clicking" ADD A USER and firing addUser()?

1 Answers

The solution was simply to add the type attribute with value button to the first button.

The browser assigns type="submit" by default to all buttons.

Simply needed to change

<button (click)="addUser()">Add a user</button>

to

<button (click)="addUser()" type="button">Add a user</button>

Related