【问题标题】:Adding a new FormGroup to FormArray has errors after form submiission and reset表单提交和重置后向 FormArray 添加新的 FormGroup 有错误
【发布时间】:2020-11-01 18:54:50
【问题描述】:

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

我在 https://stackblitz.com/edit/angular-ahnmv3 上添加了一个 StackBlitz 链接来演示这一点

【问题讨论】:

    标签: angular angular-material angular9


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      不要使用FormGroup 类的reset() 方法重置表单,而是使用FormGroupDirectiveresetForm()

      首先,您必须获取对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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-15
        • 2014-08-05
        • 1970-01-01
        • 2013-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-12
        相关资源
        最近更新 更多