【问题标题】:Error when using setControl or patchValue in angular form array在角度形式数组中使用 setControl 或 patchValue 时出错
【发布时间】:2019-01-10 02:26:56
【问题描述】:

请帮忙,我有嵌套表单数组,如下:

  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'

在我执行以下操作之前,我没有收到任何错误,但是在更新表单或(在 valuechanges 上)时,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)

我看到了以下链接Angular 4 patchValue based on index in FormArray 这就是我尝试第一种方法的原因。

【问题讨论】:

  • 你可以创建 stackblitz 示例吗??

标签: angular angular-reactive-forms angular-forms formarray


【解决方案1】:

如果我们不知道您拥有的数据或您想要获取的数据,我们将无法提供帮助。 我想你的数据是这样的

{
  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),创建带有日期的表单。如果调用发送null的函数:this.createForm(null)创建一个empy表单

【讨论】:

    【解决方案2】:

    试试这样的:

    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)]],
         })
    
    }
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2018-12-06
        • 2021-02-17
        • 2019-11-20
        • 2023-04-10
        • 2018-11-04
        • 2019-08-09
        • 2020-06-15
        • 2021-03-14
        • 2018-05-10
        相关资源
        最近更新 更多