Angular12响应式表单动态FormArray提交后无法更新如何解决
问题原因
核心错误出在表单值映射的字段名不匹配:
你在表单中定义的联系方式FormArray控件名为contacts,但在mapFormValueForContactModel方法中,错误地读取了不存在的employeephones属性,导致提交给后端的employeephones字段始终为undefined,所以没有更新。
修正方案
1. 修复表单值映射逻辑
修改mapFormValueForContactModel方法的取值字段:
mapFormValueForContactModel() { this.contactdata.current_residential_address = this.contactInfoForm.value.current_residential_address; // 把employeephones改成contacts,读取表单中实际存在的FormArray值 this.contactdata.employeephones = this.contactInfoForm.value.contacts; }
2. 可选优化(建议补充)
如果需要更新已有的联系方式而不是全量新增,需要在FormGroup中保留原有联系方式的id:
修改SetExistingContacts方法,给每个联系方式表单项添加id控件:
SetExistingContacts(contactSets: IContact[]): FormArray { const formarray = new FormArray([]); contactSets.forEach(c => { formarray.push(this.fb.group({ id: c.id, // 保留原有数据的id phone_number: c.phone_number, phone_type_id: c.phone_type_id, is_primary_contact_number: c.is_primary_contact_number })); }); return formarray; }
另外可以把表单初始化时默认添加的空联系方式项去掉,避免无数据时多出来一条空记录:
updateContact() { this.contactInfoForm = this.fb.group({ id: [''], current_residential_address: ['', [Validators.required]], contacts: this.fb.array([]) // 初始为空数组,后续加载数据或用户点击新增再添加 }); }
内容的提问来源于stack exchange,提问作者user11352561
相关产品推荐
相关产品推荐

