我在添加值后尝试重置表单。
表单代码段
<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();
}
我在观察:
form.markAsPristine()
,form.markAsUntouched()
并将所有三个结合起来。如何重置表单以便不显示mat-error?
答案 0 :(得分:7)
表单组没有关于是否已提交实际HTML表单的“知识”。它只跟踪表单值/有效性/启用状态。因此,重置表单组会重置值,但不会重置有关表单是否为submitted
的任何状态。
要执行此操作,您需要暂停FormGroupDirective
并在其上调用resetForm()
。
表单代码段
<form [formGroup]="addAttributeForm" fxLayout="column">
<!-- ... -->
</form>
在组件中
@ViewChild(FormGroupDirective) formDirective: FormGroupDirective;
onSubmit(form: FormGroup) {
// do work
this.formDirective.resetForm();
}
答案 1 :(得分:4)
此解决方案适用于我。 您需要执行以下操作:
formReset(form: FormGroup) {
form.reset();
Object.keys(form.controls).forEach(key => {
form.get(key).setErrors(null) ;
});
}
这将重置表单并清除所有错误。
答案 2 :(得分:0)
我能够成功完成此操作的唯一方法是设置一个标志,以便在您想要重置它时隐藏表单,然后使用超时将该标志设置回true。据我所知,目前还没有内置方法可以做到这一点。
showForm = true;
reset(): void {
this.showForm = false;
setTimeout(() => this.showForm = true);
}
然后在表单元素的HTML中使用*ngIf="showForm"
。