问题
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