Error when using setControl or patchValue in angular form array

走远了吗. 提交于 2019-12-31 04:13:27

问题


Please assist, I have nested form array, se below :

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

the this._buildFundingItems() is as follows

        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 || []));

doing the above or this.form.setControl('funding', this.formBuilder.array(data.funding || [])); i getting an error : Cannot find control with path: 'funding -> 0 -> amount' and Cannot find control with path: 'funding -> 0 -> items'.

Before i did the following below, i was not receiving any errors but when updating the form or (on valuechanges), the formarray was not updating.

     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)

I saw the following link Angular 4 patchValue based on index in FormArray that's why i tried the first approach.


回答1:


It's difficut help if we don't know the data you have or the data you want to get. I supouse your data was like

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

}

why not use a function to create the form with the data included?

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

    }

You can see that you call the function createForm sending data: this.createForm(data), create the form with the date. If you call the function sending null: this.createForm(null) create a empy form




回答2:


Try something like this:

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:


I faced the same issue. Try this sort of thing by creating formBuilder group for each row:

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

For more help, you may refer to this link: https://www.concretepage.com/angular-2/angular-2-4-formbuilder-example



来源:https://stackoverflow.com/questions/51651531/error-when-using-setcontrol-or-patchvalue-in-angular-form-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!