Angular2 - Validate and submit form from outside

Philipp picture Philipp · Jun 27, 2016 · Viewed 60.2k times · Source

I have a simple form that looks like this

<form (ngSubmit)="save()" #documentEditForm="ngForm">
...
</form>

and need to submit the the form and check its validity from outside

eg. Either submit it programatically, or with a <button type="submit"> that is outside the <form> tags.

Answer

Yodacheese picture Yodacheese · Oct 11, 2016

The correct way of doing is actually

<form (ngSubmit)="save()" id="ngForm" #documentEditForm="ngForm"> 
    ... 
</form>

<button class="btn-save button primary" form="ngForm" [disabled]="!documentEditForm.form.valid">
    SAVE
</button>

The form needs to have an ID id="example-form" and the submit button a matching ID in the form="example-form"