Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit reactive form from outside the form [submitting on click save or update buttons outside the form]

I am working on reactive forms in angular 7, and I need to call submit from a button outside the form.

<input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit()" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit()" >
</form>

This function is working fine.

Now, I need to submit the form from multiple buttons i.e.

  • if user click Save button, the form should be submitted and save
  • if user click Update button, the form should be submitted and update

For this purpose, I want to pass a flag 'Save' or 'Update' from

<input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit('Save')" />

<input type="button" form="ngForm"  class='Button' value="Update" (click)="detailForm.ngSubmit.emit('Update')" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit(flag)" >
    </form>

But I could not submit the form with the 'Save' / 'Update' flag. How could I pass a parameter from Save and Update buttons outside the form to my submit function.

Any fruitful suggestion would be highly appreciated.

like image 769
TAB Avatar asked Oct 26 '25 00:10

TAB


2 Answers

Use type="submit" instead type="button", or if you want to use outside the form.

<input type="submit" form="ngForm" (click)="onSubmit(gDetailForm.value, 'save')"/>
<input type="submit" form="ngForm" (click)="onSubmit(gDetailForm.value, 'update')"/>
<form id="myForm" [formGroup]="gDetailForm">
    <input type="text" name="name"/>
</form>
like image 98
Syed Aslam Avatar answered Oct 27 '25 15:10

Syed Aslam


Try this, it's working for me:

in HTML:

<input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit('Save')" />

<input type="button" form="ngForm"  class='Button' value="Update" (click)="detailForm.ngSubmit.emit('Update')" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit($event, detailForm)" id="ngForm" #detailForm="ngForm">
</form>

in component.ts:

onSubmit(isPublished: string, formId: any) {
 console.log(isPublished); //Save or Update
  if (this.gDetailForm.valid) {
   // enter code here
  }
}

Working Demo

like image 35
Ghoul Ahmed Avatar answered Oct 27 '25 15:10

Ghoul Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!