Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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!

like image 726
Duannx Avatar asked Oct 07 '17 06:10

Duannx


People also ask

Can we have 2 submit buttons in a form?

yes, multiple submit buttons can include in the html form. One simple example is given below.

How do I use multiple submit buttons in one form?

Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.

WHAT IS controls in angular?

In Angular, form controls are classes that can hold both the data values and the validation information of any form element. Every form input you have in a reactive form should be bound by a form control. These are the basic units that make up reactive forms.


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>
like image 105
Stefan Svrkota Avatar answered Oct 17 '22 03:10

Stefan Svrkota