如何清除 Angular Material mat-error 的验证错误 [英] how to clear validation errors for Angular Material mat-error
本文介绍了如何清除 Angular Material mat-error 的验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在添加值后尝试重置表单.
I'm trying to reset a form after I've added a value.
表单代码片段
<form [formGroup]="addAttributeForm" fxLayout="column">
<mat-form-field>
<input matInput formControlName="title" placeholder="Title" required>
<mat-error>This field is required</mat-error>
</mat-form-field>
</form>
在组件中
onSubmit(form: FormGroup) {
// do work
form.reset();
}
我观察到的:
- 表单值设置为空.
- 但是验证消息仍然从 mat-error 中显示出来.
- 我尝试了
form.markAsPristine()
、form.markAsUntouched()
并将这三者结合起来.
- The form values are set to empty.
- But the validation messages are still displayed from mat-error.
- I've tried
form.markAsPristine()
,form.markAsUntouched()
and combining all three.
如何重置表单以不显示 mat-error?
How can I reset the form so the mat-error is not displayed?
推荐答案
表单组不知道"实际的 HTML 表单是否已经提交.它只跟踪表单值/有效性/启用状态.因此,重置表单组确实会重置值,但不会重置任何关于表单是否已submitted
的状态.
The form group has no "knowledge" about whether the actual HTML form has been submitted or not. It only keeps track of the form values/validity/enabled state. So resetting the form group does reset the values but not any state regarding whether the form has been submitted
.
为此,您需要掌握FormGroupDirective
并在其上调用 resetForm()
.
表单代码片段
<form [formGroup]="addAttributeForm" fxLayout="column">
<!-- ... -->
</form>
在组件中
@ViewChild(FormGroupDirective) formDirective: FormGroupDirective;
onSubmit(form: FormGroup) {
// do work
this.formDirective.resetForm();
}
这篇关于如何清除 Angular Material mat-error 的验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文