Is there a way to submit Angular 2 model form (reactive form) from an external button?

I am trying to submit my reactive form with a button outside the tags. This form was previously template-driven, and I could:

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

if 'f' was the name of the form.

But if I use this approach with a model drive, an error is displayed:

TypeError: Cannot read property 'emit' of undefined

I can model this behavior by creating a hidden button inside the form and setting the click event for the external button:

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

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

This is not the best approach ... Is there an even better way?

Thank.

EDIT:

If I add an id field to the form, but I really think this is not the best approach ...

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

<button form="loginF" (click)="submit.click"></button>
+4
source share
2 answers

, "form" , :

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

, HTML, , (, , IE (http://caniuse.com/#feat=form-attribute)

0

, @BhargavRao ,

ViewChild('f') f: FormGroupDirective

-3

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


All Articles