【问题标题】:Clear Angular FormControls after save without form errors保存后清除 Angular FormControls 而不会出现表单错误
【发布时间】:2021-04-07 01:57:40
【问题描述】:

我有以下代码:

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”之类的东西然后我保存了。输入为空,出现红色错误。

我尝试使用 ma​​rkAsTouched()ma​​rkAsDirty,但结果相同。

我怎样才能点击按钮并保持输入没有错误?

这就是我得到的,我想要一个没有错误输入的空。

【问题讨论】:

  • 你的html应该有一个&lt;form&gt;标签和(submit)="clearValues()",而按钮可以是:&lt;button type="submit"&gt;...。然后在你的提交函数中调用this.myForm.reset()清除它就足够了
  • 错误仍然出现,因为FormControl它有“Validators.required”所以​​当.reset()调用时,输入变为空并且出现错误,因为是必需的。

标签: angular input angular-material form-control formgroups


【解决方案1】:

我最终这样做了:

this.myForm.reset();
Object.keys(this.myForm.controls).forEach(key => {
    this.myForm.controls[key].setErrors(null);
});

以这种方式工作。谢谢大家。

【讨论】:

    【解决方案2】:

    表单对象上有a function for this

    this.myForm.resetForm();
    

    【讨论】:

      猜你喜欢
      • 2016-02-28
      • 2016-12-30
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      相关资源
      最近更新 更多