在 angular 表单数组中使用 setControl 或 patchValue 时出错

Error when using setControl or patchValue in angular form array

请协助,我有嵌套表格数组,如下所示:

  this.form = this.formBuilder.group({
        projectTitle: ['', [Validators.required, Validators.maxLength(300)]],
        projectDescription: ['', [Validators.required, Validators.maxLength(300)]],
        funding: this.formBuilder.array([this._buildFundingItems()]),
    });

this._buildFundingItems()如下

        private _buildFundingItems(): FormGroup {
          return this.formBuilder.group({
          items: ['', [Validators.required, Validators.pattern(this.regexValidation.shortWordRegex)]],,
          amount: ['', [Validators.required, Validators.pattern(this.regexValidation.amountTypeRegex)]],
        });
     }


    // after reloading the page, i get data from api and I tried setting the value as follows 
    this.form.setControl('funding', this.formBuilder.array(data.funding || []));

执行上述操作或 this.form.setControl('funding', this.formBuilder.array(data.funding || [])); 我收到错误消息:Cannot find control with path: 'funding -> 0 -> amount'Cannot find control with path: 'funding -> 0 -> items'

在我执行以下操作之前,我没有收到任何错误,但是在更新表单或(在值更改时)时,formarray 没有更新。

     let length: number = data[0].funding.length;
     while (length-- > 0) {
         fundingSupport.push(this._buildFundingItems()); 
     }

     this.form.controls['funding'] = this.formBuilder.array([]);                   
     this.form.controls['funding'].patchValue(data.funding)

我看到了以下 link 这就是我尝试第一种方法的原因。

尝试这样的事情:

this.form = this.formBuilder.group({
  projectTitle: ['', [Validators.required, Validators.maxLength(300)]],
  projectDescription: ['', [Validators.required, Validators.maxLength(300)]],
  funding: this.formBuilder.array([this._buildFundingItems({ items: null, amount: null })]),
});

 _buildFundingItems(data): FormGroup {
  if (!data) {
      data = {
        items: null,
        amount: null
      }
  } 
  return this.formBuilder.group({
        items: [data.items, [Validators.required, Validators.pattern(this.regexValidation.shortWordRegex)]],
      amount: [data.amount, [Validators.required, Validators.pattern(this.regexValidation.amountTypeRegex)]],
     })

}

如果我们不知道您拥有的数据或您想要获取的数据,那将很难提供帮助。 我猜你的数据就像

{
  projecTitle:"title",
  projectDescription:"description"
  items:[{
     items:"item 1",
     amount:10
  },
  {
     items:"item 2",
     amount:5
  }]

}

为什么不使用函数创建包含数据的表单?

    createForm(data:any)
    {
    this.form = this.formBuilder.group({
            projectTitle: [data?data.projecTitle:'', [Validators.required, Validators.maxLength(300)]],
            projectDescription: [data?data.projectDescription:'', [Validators.required, Validators.maxLength(300)]],
            funding: //See that I change your formBuilder to return
                     //an array, this is because when create the array don't enclosed
                     // by [ ]

                    this.formBuilder.array(this._buildFundingItems(data?data.items:null)),
        });
    }

    //see that I was to return an array of FormGroup
    _buildFundingItems(items:any[]|null):FormGroup[]
    {
    return items?items.map(x=>{
            return this.formBuilder.group({
              items: [x.items, [Validators.required, Validators.pattern(this.regexValidation.shortWordRegex)]]
              amount: [x.amount, [Validators.required, Validators.pattern(this.regexValidation.amountTypeRegex)]]
            }):
 this.formBuilder.group({
          items: ['', [Validators.required, Validators.pattern(this.regexValidation.shortWordRegex)]],,
          amount: ['', [Validators.required, Validators.pattern(this.regexValidation.amountTypeRegex)]],
        });

    }

可以看到调用函数createForm发送数据:this.createForm(data),创建带有日期的表单。如果您调用发送空值的函数:this.createForm(null) create a empy form

我遇到了同样的问题。通过为每一行创建 formBuilder 组来尝试这种事情:

let employeeFormGroups = team.employees.map(employee => this.formBuilder.group(employee));
let employeeFormArray = this.formBuilder.array(employeeFormGroups);
this.teamForm.setControl('employees', employeeFormArray);

如需更多帮助,您可以参考此link: https://www.concretepage.com/angular-2/angular-2-4-formbuilder-example