0

我想在点击提交按钮时显示验证错误。我尝试使用 markAllAsTouched() 函数,但它不起作用。错误仅在触摸字段后进行比较

html:

     <ion-content >
       <div class="ion-text-center tab1-padding">
         <form [formGroup]="newCat" (ngSubmit)="logForm()">
            <mat-form-field appearance="outline" class="tab1-name-field">
              <mat-label>Nome*</mat-label>
            <input matInput #input  formControlName="name">
            <mat-error 
                   *ngIf="newCat.controls['name'].hasError('required')"> 
                    Campo obbligatorio</mat-error>
            </mat-form-field>
           <mat-form-field appearance="outline">
            <mat-label>Data di nascita*</mat-label>
            <input matInput [matDatepicker]="picker" 
              formControlName="birthday" readonly (click)="picker.open()">
               <mat-datepicker-toggle matSuffix [for]="picker"></mat- 
                 datepicker-toggle>
              <mat-datepicker touchUi #picker></mat-datepicker>
             <mat-error                 
            *ngIf="newCat.controls['birthday'].hasError('required')">Campo 
           obbligatorio</mat-error>
         </mat-form-field>

         <button ion-button type="submit" [disabled]="newCat.pristine || 
           newCat.invalid" class="btn btn-success" 
           (click)="validateFields()">Inserisci</button>
         </form>

        </div>
      </ion-content>

TS:

     constructor(private formBuilder: FormBuilder) {
       this.newCat = this.formBuilder.group({
       name: ['', Validators.required],
       birthday: ['', Validators.required],
     });
     }

      validateFields() {
        this.newCat.markAllAsTouched();
         this.newCat.markAllAsTouched();
       }
4

1 回答 1

1

尝试循环遍历所有控件并制作单个控件,如下所示,

validateFields(){
   this.validateAllFormFields(this.newCat);
}

validateAllFormFields(formGroup: FormGroup) {         
  Object.keys(formGroup.controls).forEach(field => {  
    const control = formGroup.get(field);             
    if (control instanceof FormControl) {             
      control.markAsTouched({ onlySelf: true });
    } 
  });
}
于 2019-10-19T12:17:15.913 回答