【问题标题】:angular form is never reset角度形式永远不会重置
【发布时间】:2020-07-15 18:34:36
【问题描述】:

我正在使用 angular 9 和 formController。

根据按钮点击,提供的表单添加或删除一个字段,所以我希望,当点击按钮时,表单(AND错误)全部被重置。

https://stackblitz.com/edit/angular-ivy-mku86s

我都试过了

/*  Object.keys(this.form.controls).forEach((field) => {
      console.log(field)
      this.form.get(field).setErrors(null)
    }) */
    this.formDirective.resetForm()
    this.form.reset()
/*  this.form.updateValueAndValidity()
    this.formDirective.resetForm()
    this.form.reset()
    this.form.markAsPristine()
    this.form.markAsUntouched()
    this.form.clearValidators() */

但没有任何效果...

为什么?

【问题讨论】:

  • 我认为您需要为您的 ngIf 语句添加一个新变量,例如 showError,因为错误始终存在于 formControl 中,甚至在用户触摸表单之前也是如此。跨度>
  • 不应该重置全部隐藏?或clearValidators

标签: angular forms


【解决方案1】:

这不是因为app-input组件或app-input组件本身的真正输入元素没有与任何表单控件链接。你的反应形式应该是这样的:

<form [formGroup]="form">
  <input formControlName="name"/>
  <input formControlName="email"/>
  <input formControlName="userRole"/>
  <!-- etc -->
</form>

https://angular.io/guide/reactive-forms

【讨论】:

  • 我尝试将formControlName 传递给app-input 组件,但它不起作用。它必须是直接嵌套的子元素而不是另一个组件吗?
  • @Bobby 在您的情况下,它必须直接链接到输入元素,或者 app-input 应该是 custom control
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多