Duannx
Duannx

Reputation: 8726

Right way to use multiple buttons in angular form

i am building a from with angular forms and it works well with 1 button. But when i want to have 2 buttons, it is hard to handle.

I want to have 1 button reset and 1 button submit. reset must be placed before submit. Here is the template:

<form (ngSubmit)="submit()" [formGroup]="form">
    //inputs...
    <button type="submit" (click)="reset($event)">reset</button>
    <button type="submit">submit</button>
</form>

When i press enter in one input, the form fire both submit() and reset($event) function. It is the same when i click on reset button. My expectation is:

I can find a walk around is adding a hidden button before reset button and call event.stopPropagation(); event.preventDefault() in reset() function. But it is ugly. Is there a clean way to do it? Any help would be appreciated. Many thanks!

Upvotes: 26

Views: 21870

Answers (1)

Stefan Svrkota
Stefan Svrkota

Reputation: 50633

You have to set your reset button's type to button, not submit. You have to explicitly set it because default value of attribute type is submit:

<form (ngSubmit)="submit()" [formGroup]="form">
    //inputs...
    <button type="button" (click)="reset($event)">reset</button>
    <button type="submit">submit</button>
</form>

Upvotes: 48

Related Questions