FormArray returning as FormControl instead of FormArray

雨燕双飞 提交于 2021-02-11 12:09:07

问题


I'm having trouble with nested FormArrays in Angular reactive forms. One of my form arrays correctly returns as a FormArray and the other returns as FormControl. In the initialMaterials() function I have two console.logs. console.log(control) returns a FormControl item and console.log(this.objectServiceJobsArray) returns a FormArray.

I need to be able to add materials to specific jobs in the array and change them in the form when necessary.

this.objectServiceForm = this.formBuilder.group({
          onHolidays: [this.objectService.onHolidays],
          objectServiceJobs: this.formBuilder.array([this.objectServiceJobs()]),
          isBillable: [this.objectService.isBillable],
          defaultPrice: [this.objectService.defaultPrice],
          pricePerHour: [this.objectService.pricePerHour],
          doneWeekly: [this.doneWeekly],
        });

objectServiceJobs(): FormGroup {
    return this.formBuilder.group({
      job: [''],
      workDetail: [''],
      competentWorkers: [[]],
      materials: this.formBuilder.array([this.objectServiceJobMaterials()])
    });
}

objectServiceJobMaterials(): FormGroup {
    return this.formBuilder.group({
      material: [null],
      quantity: [null]
    });
}

initialMaterials(job) {
    const index = (<FormArray>this.objectServiceForm.get('objectServiceJobs')).controls.findIndex(x => x.value.job.id === job.id);
    const control = (<FormArray>this.objectServiceForm.controls['objectServiceJobs']).at(index).get('materials') as FormArray;
    console.log(control);
    console.log(this.objectServiceJobsArray);

    // job.materials.forEach(mat => {
    //   this.objectServiceJobsArray[index].materials.push(this.makeMaterialFormGroup(mat));
    // });
}

回答1:


I tried your code in my IDE but changed the style of extracting controls and I can see that console.log(control) returns me as FormArray.

initialMaterials(job) {
    const objectServiceJobs = this.objectServiceForm.get('objectServiceJobs') as FormArray;
    const index = objectServiceJobs.controls.findIndex(x => x.value.job.id === job.id);
    const control = objectServiceJobs.at(index).get('materials') as FormArray;
    console.log(control);
  }



回答2:


As saloo said the code works perfectly and returns a FormArray, just keep in mind that job is a form control (value isn't an object) so x.value.job.id is always undefined inside this line :

const index = objectServiceJobs.controls.findIndex(x => x.value.job.id === job.id);


来源:https://stackoverflow.com/questions/58639872/formarray-returning-as-formcontrol-instead-of-formarray

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