Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple submit buttons in angular2 form

I am building angular2 form and I would like to have multiple buttons to submit the form, e.g "Save" and "Save and close".

I have tried to use simple buttons with click action on them, but I didn't find anyway to manually mark form as submitted to force form validation.

<form #ticketForm="ngForm" novalidate>
    <input type="text" id="customerName" required
        name="customerName" [(ngModel)]="ticket.customerName"
        #customerName="ngModel">

    <div class="tj-form-input-errors"
        *ngIf="customerName.errors && (customerName.dirty ||
        customerName.touched || ticketForm.submitted)">

        <small [hidden]="!customerName.errors.required">
            Customer name is required
        </small>
    </div>

    <button type="button" (click)="save(ticketForm)">Save</button>
    <button type="button" (click)="saveAndClose(ticketForm)">Save and close</button>
</form>
like image 931
Ruben Nagoga Avatar asked Nov 05 '16 20:11

Ruben Nagoga


1 Answers

Assign different id to each button. Then you can obtain the id of the button which triggered submit using document.activeElement.id. like the following :

In your Html :

<form #form="ngForm" (submit)="firstSave(form,$event)">
    ...
    <div class="form-group">
        <input type="submit" id="submit-1" value="Submit 1" class="btn btn-sm btn-primary"/>
        <input type="submit" id="submit-2" value="Submit 2" class="btn btn-sm btn-success"/>
    </div>
</form>

Then in your typescript :

firstSave(form: NgForm, $event: Event) {
  var activeButton = document.activeElement.id;
  if (activeButton == "submit-1") {
    alert("you have clicked on submit 1");
  }
  if (activeButton == "submit-2") {
    alert("you have clicked on submit 2");
  }
}

StackBlitz Here.

like image 181
AbolfazlR Avatar answered Oct 28 '22 00:10

AbolfazlR