简体   繁体   中英

Template Driven Form Validation of component inside Form

I am trying to validate a component inside a form

  <form #f="ngForm" novalidate (ngSubmit)="submitForm()">
    <app-form-component [f]="f" [model]="model" ></app-form-component>
    <button>Submit</button>
  </form>

Form component:

         <input type="number"
                   #test="ngModel"
                   name="test"
                   required
                   [ngClass]="{ 'is-invalid': f.submitted && test.invalid }"
                   [(ngModel)]="model">

When I submit the form I get an error in my Input Filed but the function submitForm is still called.

<form #f="ngForm" novalidate (ngSubmit)="CheckModelValid()?submitForm():''">

Component File Add One function Which Return Model Is Valid Or not that call

CheckModelValid(){
 ..... 
 return true // on valid
}

you can also check the validation with below ways:

<form #f="ngForm" novalidate (ngSubmit)="f.form.valid && submitForm()">

if form is valid then only submitForm function call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM