Angular中categoryIdArray.push不是函数错误排查求助
问题分析
错误根源是第一次勾选复选框后,你执行了this.patientReportForm.setControl('hubxCategoryId', this.formBuilder.group([desiredFormat])),直接将原本的FormArray替换成了FormGroup。第二次触发onChange时,categoryIdArray被断言为FormArray,但实际已是FormGroup,没有push方法,因此抛出错误。
解决方案
不要修改原FormArray的结构,仅维护其增删操作,在需要使用格式化数据的时机(比如提交表单)再将FormArray的值转为逗号分隔字符串。
1. 修正onChange方法
onChange(categoryId: string, isChecked: boolean) { const categoryIdArray = this.patientReportForm.controls.hubxCategoryId as FormArray; if (isChecked) { categoryIdArray.push(new FormControl(categoryId)); } else { const index = categoryIdArray.controls.findIndex(x => x.value === categoryId); if (index !== -1) { // 增加判断,避免index为-1时触发删除报错 categoryIdArray.removeAt(index); } } }
注意:方法参数
categoryId原定义为string[],但HTML中传递的是单个hubxReport.categoryId,需将参数类型改为string。
2. 按需生成逗号分隔字符串
在提交表单或需要使用格式化数据时,再进行转换:
submitForm() { // 从FormArray中提取值并转成逗号分隔字符串 const categoryIds = (this.patientReportForm.get('hubxCategoryId') as FormArray).value; const desiredFormat = categoryIds.join(','); // 构造提交数据,保留原表单结构的同时传入格式化后的字段 const submitData = { ...this.patientReportForm.value, hubxCategoryId: desiredFormat }; // 执行后续提交逻辑 }
3. 额外优化建议
- 封装
FormArray的getter,简化后续调用:
get hubxCategoryIdArray(): FormArray { return this.patientReportForm.get('hubxCategoryId') as FormArray; }
之后在onChange中可直接使用this.hubxCategoryIdArray,无需重复断言。
- 简化表单初始化写法:
this.patientReportForm = this.formBuilder.group({ patientId: [Number(this.clientId)], hubxCategoryId: this.formBuilder.array([]), notes: [] });
内容的提问来源于stack exchange,提问作者KingCk
相关产品推荐
相关产品推荐

