首页 > 解决方案 > Angular formControl 在进行验证时未显示 mat-error

问题描述

我正在使用 Angular,我正在制作一个包含 FormArray 的 FormGroup,其中包含一个包含 FormControl 的 FormGroup。单击提交按钮时,我想在执行操作之前验证我的所有字段。

当您单击提交按钮时,所有有错误的文件都将变为红色,但 mat-error 组件将保持隐藏状态,这是我的问题。我想知道如何更新我的代码,以便 mat-error 按预期响应。

这是我的代码示例:

我的.component.ts:

export class myComponent implements OnInit {

  public optionList = [{
    value: 1
    name: option1
  }, {
    value: 2
    name: option2
  }, {
    value: 3
    name: option3
  }];

  public myFormArray: FormArray = new FormArray([]);
  public myFormGroup: FormGroup;

  public ngOnInit(): void {
    this.myFormGroup = new FormGroup({
      myFormArray: this.myFormArray
    });
    this.myFormArray.push(
      new FormGroup({
        myFormControl: new FormControl('', Validators.required)
      })
    );
  }

  public validateAllFields(formGroup: FormGroup): void {
    Object.keys(formGroup.controls).forEach(field => {
      const control = formGroup.get(field);
      if (control instanceof FormControl) {
        control.markAsTouched({ onlySelf: true });
      } else if (control instanceof FormGroup) {
        this.validateAllFields(control);
      }
    });
  }

  public validateOneField(formControl: FormControl): boolean {
    return formControl.invalid && (formControl.dirty || formControl.touched);
  }

}

我的.component.html

<div [formGroup]="myFormGroup">
  <div *ngFor="let myItem of myFormArray.controls">
    <ng-container [formGroup]="myItem">
      <mat-form-field>
        <mat-label>Choose</mat-label>
        <mat-select formControlName="myFormControl">
          <mat-option *ngFor="let opt of optionList" [value]="opt.value">{{opt.name}}</mat-option>
        </mat-select>
        <mat-error *ngIf="validateOneField(opt.controls.myFormControl)">
          My Error Message!!!
        </mat-error>
      </mat-form-field>
    </ng-container>
  </div>
</div>
<button (click)="validateAllFields(myFormGroup)">Submit</button>

标签: angularvalidation

解决方案


我通过创建自己的错误状态匹配器来解决我的问题。

custom-error.state-matcher.ts:

import { ErrorStateMatcher } from '@angular/material/core';
import { FormControl, FormGroupDirective, NgForm } from '@angular/forms';

export class CustomErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}

创建自定义状态匹配器后,您需要在组件中添加以下行以激活它。

我的.component.ts:

public matcher = new CustomErrorStateMatcher();

完成后,您可以删除所有用于验证的 *ngIf=""。

向@Eliseo 大喊输入!


推荐阅读