angular - 在触摸控件之前显示 mat-form-field 错误消息
问题描述
这个问题有一个 Stackblitz;stackblitz.com/edit/yz1dhz。
当组件加载时和用户触摸控件之前,如何呈现 mat-form-field 验证错误消息?
class AppComponent implements OnInit {
form: FormGroup;
constructor(private readonly fb: FormBuilder) {
// Create a form in an invalid state.
this.form = this.fb.group({
a: this.fb.control(null, [Validators.required])
});
}
ngOnInit() {
// This does do what I had hoped.
this.form.updateValueAndValidity();
}
}
该代码创建了一个立即无效的表单。我希望<mat-error>
展示:
<form [formGroup]="form">
<mat-form-field>
<mat-select formControlName="a">
<mat-option>Foo</mat-option>
<mat-option>Bar</mat-option>
<mat-option>Baz</mat-option>
</mat-select>
<mat-hint>I am a hint.</mat-hint>
<mat-error>{{ form.controls['a'].errors | json }}</mat-error>
</mat-form-field>
</form>
而是<mat-hint>
显示。
解决方案
你可以这样强制
this.form.get('a').markAsTouched();
或者您可以将所有控件标记为已触摸
this.form.markAllAsTouched();
您可以使用markAsTouched、markAllAsTouched、markAsUntouched、markAsDirty、markAsPristine、markAsPending更改表单控件的状态...
推荐阅读
- java - 如何修改 SLF4J 日志输出
- c# - 需要实体框架:具有两个导航属性的可选 1 对 1 关系
- javascript - 如何在 Node.js 中使用传入的函数初始化子进程
- azure-iot-sdk - Azure IoT 设备:client.js 中的类型错误
- python-3.x - Group by 和 Count 函数返回 NaN
- java - JNoSQL + MongoDB + Wildfly Swarm
- python - “Pip install spacy”失败并出现错误
- ios - Swift - 删除 CoreData 行
- maven - 无法运行 RichFaces,出现不同类型的异常
- asp.net-mvc - 文件上传/下载网络根目录