5

I'm trying to submit my reactive form from a button outside tags. Before, this form was Template-driven and I could do:

<button (click)="f.ngSubmit.emit()"></button>

if 'f' was form name.

But if I use this approach with model-drive form an error is shown:

TypeError: Cannot read property 'emit' of undefined

I can simulate this behaviour writing a hidden button inside form and setting click event for outside button:

<form [formGroup]="loginForm" (ngSubmit)="login()">
   ...
   <button #submit type="submit" style="visibility:hidden"></button>
</form>

<button (click)="submit.click"></button>

It doesn't seem to be the best approach... Is there another better way?

Thank you.

EDIT:

If I add an id field to the form works, but I really think that isn't the best approach...

<form id="loginF" [formGroup]="loginForm" (ngSubmit)="login()">
   ...
</form>

<button form="loginF" (click)="submit.click"></button>
jmpmscorp
  • 71
  • 1
  • 4
  • have a look on this http://stackoverflow.com/questions/38054631/angular2-validate-and-submit-form-from-outside – styopdev Nov 30 '16 at 05:14
  • Thank you @styopdev. I have seen this questions and, as I wrote on EDIT, now works... I don't know if there is a better approach. – jmpmscorp Nov 30 '16 at 23:34

2 Answers2

0

To call a submit button from outside a form, you should use the 'form attribute' on the button to make a reference to the wanted form:

<form [formGroup]="loginForm" (ngSubmit)="login()" id="thatForm">
  ...
</form>    
<button type="submit" form="thatForm"></button>

As you can see, it's plain old HTML, not a weird hack, and it supported on all the good browsers (aka, everyone except IE (http://caniuse.com/#feat=form-attribute)

Alejandro Silva
  • 8,808
  • 1
  • 35
  • 29
-3

Use this:

ViewChild('f') f: FormGroupDirective
Bugs
  • 4,491
  • 9
  • 32
  • 41