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.
To add validation to a template-driven form, you add the same validation attributes as you would with native HTML form validation. Angular uses directives to match these attributes with validator functions in the framework.
How to add a Validator to Reactive Forms. We configure the validators as the second and third argument to the FormControl , FormGroup or FormArray in the component class. The second argument is a collection of sync validators and the third argument is a collection of an async validators.
You can link the button to the form using the form attribute on the button:
<form (ngSubmit)="save()" id="ngForm" #documentEditForm="ngForm"> ... </form> <button form="ngForm"> SAVE </button>
You can still check its validity like this:
<button 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"
See here for more details: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-form
Found out how to do it:
<formname>.ngSubmit.emit()
<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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With