我在使用Angular reactive表单中的嵌套FormArrays时遇到了问题。我的一个表单数组正确地返回为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));
// });
}发布于 2019-10-31 17:46:20
我在集成开发环境中尝试了您的代码,但是更改了提取控件的样式,我可以看到console.log(控件)将我作为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);
}发布于 2019-10-31 18:21:35
正如saloo所说的,代码运行良好并返回一个作业,只要记住FormArray是一个表单控件(值不是一个对象),所以x.value.job.id在这一行中总是未定义的:
const index = objectServiceJobs.controls.findIndex(x => x.value.job.id === job.id);https://stackoverflow.com/questions/58639872
复制相似问题