TAB
TAB

Reputation: 2134

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.

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.

Upvotes: 3

Views: 8892

Answers (3)

Ghoul Ahmed
Ghoul Ahmed

Reputation: 4836

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

Upvotes: 2

Syed Aslam
Syed Aslam

Reputation: 81

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>

Upvotes: 6

Adrita Sharma
Adrita Sharma

Reputation: 22203

Try this:

HTML:

<button (click)="onSubmit(detailForm.value,'save')">Submit</button>
<button (click)="onSubmit(detailForm.value,'update')">Update</button>

TS:

onSubmit(formValue:any, type:string) {
 /// your code
}

Upvotes: 2

Related Questions