3
votes

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.

3
provide stackblitz example - Prashant Pimpale
Are you using template-driven or reactive forms? I don't understand why you have both a formGroup and an ngForm. Is there any reason you can't simply call onSubmit() from the buttons, passing the required flags? - Will Alexander
I am using reactive forms and I have edit my code. - TAB

3 Answers

6
votes

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>
2
votes

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

2
votes

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
}