Multiple submit buttons in angular2 form

I am creating an angular2 form and would like to have several buttons for submitting the form, for example, “Save” and “Save and close”.

I tried to use simple buttons with clicking on them, but I did not find a way to manually mark the form as submitted to force verification of the form.

<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> 
+5
source share
3 answers

Assign different id for each button. Then you can get the id button that caused the dispatch 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 typewriting:

 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.

+1
source

You can subscribe to form changes that I think will see form validation.

I am doing 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 you save or save and update this.physicalForm.valid .

0
source

I faced the same situation. In my case, I have 2 send "Save", "Save and highlight"

Decision

You can simply set the send type button in the payload and perform the corresponding action in the backend code.

Code example

 //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> 
0
source

Source: https://habr.com/ru/post/1259343/


All Articles