Angular表单仅获取最后一个值,无法收集全部答案问题排查
Angular表单无法收集所有问题答案的原因及修复方案
问题根源
- 表单控件数量不匹配:初始化时仅给
answers表单数组添加了1个表单组,但数据库返回的是多个问题,控件数量和问题数量不一致。 - 模板循环嵌套错误:外层遍历问题列表,内层又遍历表单控件数组,导致每个问题下都渲染了所有表单控件(仅1个),所有输入都绑定到同一个控件,最终只能拿到最后一次输入的值。
修复步骤
1. 修正TS代码:动态生成对应数量的表单控件
获取到问题列表后,清空原有表单数组,为每个问题创建带ID的表单组,确保控件和问题一一对应。
anamnezQuestion: any; anamnezForm: FormGroup; answersDetail: any = []; constructor(private clientService: ClientService, private fb: FormBuilder) {} ngOnInit(): void { this.getAnamnezQuestion(); // 初始化空的表单数组,不提前添加表单组 this.anamnezForm = this.fb.group({ answers: this.fb.array([]), }); } // 获取表单数组 answers(): FormArray { return this.anamnezForm.get('answers') as FormArray; } // 创建带问题ID的表单组 newAnswers(questionId: number): FormGroup { return this.fb.group({ questionId: [questionId], // 绑定对应问题ID,方便后端匹配 answerValue: [false], // 复选框默认设为布尔值false answer: [''], }); } get anamnezFormGroup() { return this.anamnezForm.get('answers') as FormArray; } onFormSubmit(value: any) { console.log(value); // 此时value.answers即为所有问题的答案集合 } getAnamnezQuestion() { this.clientService.getAnamnezQuestion().subscribe((res: any) => { this.anamnezQuestion = res.data; const answersArray = this.anamnezForm.get('answers') as FormArray; answersArray.clear(); // 清空原有内容 // 遍历问题列表,为每个问题添加表单组 this.anamnezQuestion.forEach((question: any) => { answersArray.push(this.newAnswers(question.id)); }); }); }
2. 修正模板代码:正确绑定表单控件
去掉内层循环,直接通过问题的索引绑定对应位置的表单组,确保每个问题对应唯一的控件。
<form [formGroup]="anamnezForm" (ngSubmit)="onFormSubmit(anamnezForm.value)"> <div formArrayName="answers"> <div *ngFor="let question of anamnezQuestion; let i = index"> <div>{{ question.id }}. {{ question.question }}</div> <!-- 用当前问题的索引绑定对应表单组 --> <div [formGroupName]="i"> <div class="input-group mb-3"> <div class="input-group-prepend"> <div class="input-group-text"> <input type="checkbox" aria-label="Checkbox for following text input" formControlName="answerValue" /> </div> </div> <input type="text" class="form-control" aria-label="Text input with checkbox" formControlName="answer" /> </div> </div> </div> </div> <button type="submit">Gönder</button> </form>
最终提交结果
点击提交后,onFormSubmit里的value.answers会输出符合你需求的格式:
answers: [ { questionId: 1, answerValue: true, answer: "第一个问题的输入内容" }, { questionId: 2, answerValue: false, answer: "第二个问题的输入内容" }, { questionId: 3, answerValue: true, answer: "第三个问题的输入内容" } ]
内容的提问来源于stack exchange,提问作者Tolga HATİPOĞLU
相关产品推荐
相关产品推荐

