我有以下代码:
initializeForm(): void {
this.myForm = new FormGroup({
name: new FormControl('hello world', Validators.required)
});
}
clearValues(): void {
// save my form.. or do something, then clear my form
this.myForm.patchValue({ name: null });
}
然后在我的 html 中,我有输入和一些按钮来保存更改。之后我调用 clearValues。
<input type=text formControlName="name">
<button (click)="clearValues()">Save</button>
当我启动我的应用程序时,该字段没有红色错误,因此我可以输入所有内容,但是如果我将其留空,则会出现红色错误(显然)。
如果我写了诸如“Hello World”之类的内容并保存。输入变为空,出现红色错误。
我尝试使用 markAsTouched() 或 markAsDirty,但结果相同。
如何单击按钮并保持输入无错误?
这就是我得到的,我想要一个没有错误输入的空。
答案 0 :(得分:0)
表单对象上有 a function for this。
this.myForm.resetForm();
答案 1 :(得分:0)
我最终这样做了:
this.myForm.reset();
Object.keys(this.myForm.controls).forEach(key => {
this.myForm.controls[key].setErrors(null);
});
以这种方式工作。谢谢大家。