向 FormArray 添加新的 FormGroup 在表单提交和重置后出现错误

Adding a new FormGroup to FormArray has errors after form submiission and reset

在我的 Angular 应用程序中,我有一个包含多个文本字段的表单以及一个 FormArray,其中每个元素都是一个表示一行字段的 FormGroup。此 FormArray 在启动时有 1 个 FormGroup,可以通过单击按钮添加更多。此外,该表单还有一个提交按钮,在填写所有字段之前不应启用该按钮。提交表单后,我想调用 Web 服务并重置我的表单并删除我成功完成的字段错误。然而,在提交表单后,我单击按钮将一行添加到我的 FormArray 中,这个新 FormGroup 的所有表单字段都以红色突出显示。提交按钮也已启用,但我希望它会被禁用,因为所有表单字段都没有填写。知道如何解决这个问题吗?

我在 https://stackblitz.com/edit/angular-ahnmv3

中包含了一个 StackBlitz link 来演示这一点

不要使用 FormGroup class 的 reset() 方法重置表单,而是使用 FormGroupDirective.[=17= 的 resetForm() 方法]

首先,您必须获取对 FormGroupDirective 的引用。一种方法是在您的表单上放置一个模板引用变量并将其传递给您的提交方法:

<form [formGroup]="orderForm" #f="ngForm">
  ...

  <button (click)="submitForm(f)" 
          [disabled]="orderForm.invalid">
    Submit Form
  </button>

</form>

在你的 ts 文件中:

submitForm(f: FormGroupDirective): void {
  const items = this.orderForm.get("items") as FormArray;
  items.controls = [];
  this.addItem();

  f.resetForm(); // => instead of this.orderForm.reset()

  // There's no need to call the below method
  // this.clearErrorsFromFormGroup(this.orderForm);
}

您必须在提交表单后重新初始化表单。 我在 stackblitz 分叉了你的演示。你可以在https://stackblitz.com/edit/angular-g1fme8

看到