Right way to use multiple buttons in angular form

Viewed 18709

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:

  • When press enter or click submit button, the form only fire submit() function
  • When click reset button the form only fire reset() function

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!

1 Answers

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>
Related