Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 829
Philipp Avatar asked Jun 27 '16 12:06

Philipp


People also ask

How to validate template driven form?

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 validation in reactive forms?

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.


2 Answers

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

like image 80
Yodacheese Avatar answered Sep 27 '22 22:09

Yodacheese


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

like image 34
Philipp Avatar answered Sep 27 '22 21:09

Philipp