FormArray 返回为 FormControl 而不是 FormArray [英] FormArray returning as FormControl instead of FormArray

查看:29
本文介绍了FormArray 返回为 FormControl 而不是 FormArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Angular 反应式表单中的嵌套 FormArray 时遇到问题.我的表单数组之一正确返回为 FormArray,另一个返回为 FormControl.在 initialMaterials() 函数中,我有两个 console.logs.console.log(control) 返回一个 FormControl 项,console.log(this.objectServiceJobsArray) 返回一个 FormArray.

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

推荐答案

我在 IDE 中尝试了您的代码,但更改了提取控件的样式,我可以看到 console.log(control) 将我返回为 FormArray.

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

这篇关于FormArray 返回为 FormControl 而不是 FormArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆