简体   繁体   中英

Multiple submit buttons in angular2 form

I am building angular2 form and I would like to have multiple buttons to submit the form, eg "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>

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.

You can subscribe to form changes, which I think will fire form validation.

I do something like this:

 this.physicalForm.valueChanges
   .map((value) => {
      return value;
   })
   .filter((value) => this.physicalForm.valid) 
   .subscribe((value) => {
      do what you need with the values here...
 });

Then in your click handler for each button, if this.physicalForm.valid you save or save&update.

i ran into the same situation. In my case i have 2 submit 'Save','Save and Allocate'

Solution

You can simply set the the type of submit button in the payload and do the action accordingly in the backend code.

Sample code

//here formData is my payload for the API call eg: formData.name,formData.email

<button type="submit" class="btn btn-primary md" (click)="formData.save_type='save'">Save</button>
<button type="submit" class="btn btn-primary md" (click)="formData.save_type='allocate'">Save And Allocate</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM