Angular中如何为FormGroup内嵌套的FormArray设置值?
问题根因
你初始化时requirements对应的FormArray为空,内部没有对应结构的FormGroup控件:
setValue要求FormArray的控件数量、结构和赋值的数组完全匹配,空数组和返回的数组结构不匹配所以直接报错patchValue只会给已存在的对应索引的控件赋值,没有对应控件时就会静默失败,数据写不进去
解决方法
把你原来赋值FormArray的this.jobOpportunity.controls['requirements'].patchValue(data.requirements);替换为以下代码即可:
// 清空FormArray原有控件,避免旧数据残留 this.requirements().clear(); // 遍历接口返回的要求列表,逐个创建对应FormGroup并加入FormArray data.requirements.forEach(item => { const reqForm = this.newRequirement(); reqForm.patchValue(item); this.requirements().push(reqForm); });
优化建议(可选)
你不需要逐个给表单控件赋值,直接用FormGroup的patchValue方法批量赋值即可,代码更简洁:
this.api.getByIdJobOpportunity(this.jopId.id).subscribe( (data: any) => { // 处理FormArray this.requirements().clear(); data.requirements.forEach(item => { const reqForm = this.newRequirement(); reqForm.patchValue(item); this.requirements().push(reqForm); }); // 批量赋值普通字段,单独处理日期格式 this.jobOpportunity.patchValue({ ...data, initDate: data.initDate.split('T')[0], endDate: data.endDate.split('T')[0] }); // 其他业务赋值 this.url = data.image; this.formTitle = 'Actualizar empleo'; this.labelBtn = 'Actualizar'; }, );
内容的提问来源于stack exchange,提问作者Deybi Tabora Paz
相关产品推荐
相关产品推荐

