FormArray返回为FormControl而不是FormArray

时间:2019-10-31 09:04:58

标签: angular angular-reactive-forms

我在Angular反应形式中嵌套FormArray遇到了麻烦。我的一个表单数组正确返回为FormArray,另一个返回为FormControl。在initialMaterials()函数中,我有两个console.logs。 console.log(control)返回一个FormControl项,console.log(this.objectServiceJobsArray)返回一个FormArray。

我需要能够向阵列中的特定作业添加材料,并在必要时以表格形式对其进行更改。

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));
    // });
}

2 个答案:

答案 0 :(得分:2)

我在IDE中尝试了您的代码,但更改了提取控件的样式,并且可以看到console.log(control)将我返回为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);
  }

答案 1 :(得分:1)

就像saloo所说的那样,代码可以完美地工作并返回一个FormArray,只需记住job是一个表单控件(值不是对象),因此x.value.job.id在此行中始终是未定义的:

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