Angular获取所有选中复选框值 合并同问题多选选项优化表单结构
Angular测验应用复选框表单逻辑优化方案
现有实现的核心问题
当前的复选框联动逻辑存在两处明显缺陷:
- 勾选选项时无差别新建问题级表单组,导致同一问题选中多个选项时,
answer数组会重复生成相同questionCode的条目,每条仅存储单个选项值,冗余度高 - 取消勾选的匹配逻辑存在错误:判断条目时直接将整个表单组的value对象和问题编码字符串做等值比较,永远无法匹配到对应条目,导致取消操作无法正常执行
优化实现思路
核心调整条目维护的匹配和操作逻辑,对齐业务要求的「单问题单条目、选项聚合存储」结构:
- 每次触发联动时,优先判断当前选项所属问题,在
answer数组中是否已存在对应条目 - 勾选选项时:
- 若问题条目已存在,直接将选项值追加到该条目下的
emailCodeFormArray中,不重复创建问题条目 - 若问题条目不存在,才新建完整问题表单组,将当前选项作为初始值存入
emailCode数组后,推送到answer数组
- 若问题条目已存在,直接将选项值追加到该条目下的
- 取消勾选选项时:
- 若对应问题条目不存在,直接终止逻辑
- 找到对应问题条目下的
emailCode数组,移除匹配的选项值 - 若该问题下所有选中选项都被清空,再将整条问题条目从
answer数组中删除
优化后的完整逻辑代码
ngOnInit() { this.myForm = this.fb.group({ lessonCode: "test", answer: this.fb.array([]) }); } onChange(questionCode: string, optionCode: string, isChecked: boolean) { const answerFormArray = this.myForm.get('answer') as FormArray; // 匹配当前问题在answer数组中的条目位置 const existingQuestionIndex = answerFormArray.controls.findIndex( group => group.get('questionCode')?.value === questionCode ); if (isChecked) { if (existingQuestionIndex > -1) { // 问题条目已存在,直接向选项数组追加值 const currentQuestionGroup = answerFormArray.at(existingQuestionIndex) as FormGroup; const optionArray = currentQuestionGroup.get('emailCode') as FormArray; optionArray.push(new FormControl(optionCode)); } else { // 问题条目不存在,新建完整条目 const newQuestionGroup = new FormGroup({ questionCode: new FormControl(questionCode), emailCode: new FormArray([new FormControl(optionCode)]) }); answerFormArray.push(newQuestionGroup); } } else { // 不存在对应问题条目时直接返回 if (existingQuestionIndex === -1) return; const currentQuestionGroup = answerFormArray.at(existingQuestionIndex) as FormGroup; const optionArray = currentQuestionGroup.get('emailCode') as FormArray; // 定位要移除的选项在选项数组中的位置 const optionIndex = optionArray.controls.findIndex(control => control.value === optionCode); if (optionIndex > -1) { optionArray.removeAt(optionIndex); } // 问题下无剩余选中选项时,删除整条问题条目 if (optionArray.length === 0) { answerFormArray.removeAt(existingQuestionIndex); } } }
优化后的输出结构
运行优化后的逻辑,生成的表单值完全匹配业务需求:
{ "lessonCode": "test", "answer": [ { "questionCode": "pertanyaan2", "emailCode": ["option1", "option2"] } ] }
注:需求描述中书写的
emailCode: { "option2", "option1" }为格式笔误,结合Angular响应式表单的实现规范,聚合的多选项值以数组形式存储,是当前场景下的合理结构。
内容的提问来源于stack exchange,提问作者naoval
相关产品推荐
相关产品推荐

