You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中使用单选按钮处理嵌套数组的问题求助

Angular嵌套数组MCQ问答组件问题及解决方案

项目背景

我正在开发一个需处理嵌套数组的Angular项目,示例数据如下:

options = [
   {
     value: 1,
     text: 'Cheeseburger',
     content: [
       { id: 101, name: 'Cheese' },
       { id: 102, name: 'Bread' },
       { id: 103, name: 'Veggies' },
     ],
   },
   {
     value: 2,
     text: 'Taco',
     content: [
       { id: 201, name: 'Nun' },
       { id: 202, name: 'Veggies' },
       { id: 203, name: 'Sauce' },
     ],
   },
];

需要实现MCQ风格的单选问答,目前基础功能已完成,但遇到两个问题:


问题1:新增问答组时之前选中的选项被取消

点击“Add More”按钮新增空白问答组(克隆options)时,之前选中的选项会被取消,尽管答案已存储在数组中,尝试的代码如下:

addMoreQuestions() {
    const existingQuestionSet = this.questionandAnswer[0].slice();
    console.log('existingQuestionSet =>', existingQuestionSet);

    this.questionandAnswer.push(existingQuestionSet);
    console.log('this.questionAnswer =>', this.questionandAnswer);

    // Copy the selected options for the previous question sets
    const previousSelectedOptions = [...this.selectedOptions];

    this.answers.push(previousSelectedOptions);
    console.log('answer =>', this.answers);

    // Reset selectedOptions only for the new question set
    this.selectedOptions = [];
}

解决方案

问题核心是所有问答组共享同一选中状态变量,重置时会覆盖之前的选中记录。需为每个问答组维护独立的选中状态:

  1. 调整初始数据结构,让answers数组的每个元素对应一个问答组的选中值:
answers: number[][] = [[]]; // 初始第一个组的选中值数组
  1. 修改新增方法,克隆问答组时避免引用问题,并为新组添加独立的选中状态容器:
addMoreQuestions() {
    // 深克隆初始问答组,避免原数据被修改
    const newQuestionSet = JSON.parse(JSON.stringify(this.questionandAnswer[0]));
    this.questionandAnswer.push(newQuestionSet);
    // 为新组添加空的选中状态数组
    this.answers.push([]);
}
  1. 模板中为每个问答组绑定对应索引的answers元素,同时通过动态name属性保证单选互斥:
<div *ngFor="let questionGroup of questionandAnswer; let i = index">
  <div *ngFor="let option of questionGroup">
    <h3>{{ option.text }}</h3>
    <div *ngFor="let content of option.content">
      <label>
        <input 
          type="radio" 
          name="question-{{i}}-{{option.value}}" 
          [(ngModel)]="answers[i][option.value - 1]" 
          [value]="content.id"
        >
        {{ content.name }}
      </label>
    </div>
  </div>
</div>

问题2:API响应数据回显到单选按钮

示例API响应数据:

res = [
      [102, 201],
      [101, 202],
];

需要根据res中的id值,生成对应数量的问答组并自动选中对应选项。

解决方案

  1. 编写加载保存数据的方法,根据响应长度生成问答组并赋值选中状态:
loadSavedAnswers(res: number[][]) {
    // 清空现有数据
    this.questionandAnswer = [];
    this.answers = [];

    // 根据响应条目数生成对应数量的问答组
    res.forEach(() => {
        const questionSet = JSON.parse(JSON.stringify(this.options));
        this.questionandAnswer.push(questionSet);
    });

    // 直接将响应数据赋值给answers,实现回显
    this.answers = [...res];
}
  1. 在组件初始化或API请求完成后调用该方法:
ngOnInit() {
    // 模拟API响应数据
    const res = [
      [102, 201],
      [101, 202],
    ];
    this.loadSavedAnswers(res);
}

模板沿用问题1修改后的绑定逻辑,即可自动选中对应选项。


内容的提问来源于stack exchange,提问作者Netranjit Borgohain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:23:12