angular - 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>
解决方案
我通过创建自己的错误状态匹配器来解决我的问题。
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 大喊输入!
推荐阅读
- python - 深度神经网络内存不足
- python-3.x - 如何使用 python 建立 TLS 连接?
- java - IntellijIDEA 打开时,Gluon SceneBuilder 不会打开 FXML 文件
- azure - 如何删除 Azure 中不存在的 VM
- python - 当 n_components 为 None 时如何解释 Scikit-learn 的 PCA?
- python - 如何从 svg 字节流渲染 svg 图像
- vue.js - Parcel - Babel - Vue - 错误:找不到模块`.../.../img.svg`
- single-sign-on - Keycloak 如何使用 AdminURL 实现单点登出
- javascript - 如何使用 map() 为组件传递 ref
- javascript - 在我的 disocrd 服务器上使用 dm 命令时出现 Discord.js dming 问题