Search code examples
angularangular2-forms

Angular2 - Validate and submit form from outside


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.


Solution

  • Found out how to do it:

    • trigger submit with <formname>.ngSubmit.emit()
    • get form status with <formname>.form.valid

    Example:

    <form (ngSubmit)="save()" #documentEditForm="ngForm">
    ...
    </form>
    
    <button class="btn-save button primary"
    (click)="documentEditForm.ngSubmit.emit()"
    [disabled]="!documentEditForm.form.valid">SAVE</button>
    

    Edit: As @yuriy-yakovenko has pointed out, you should add in your component code the following:

    @ViewChild('documentEditForm') documentEditForm: FormGroupDirective; 
    

    And don't forget to import the FormGroupDirective if you haven't done yet