首页 > 解决方案 > 如何以角度跟踪 Double ngFor 循环中的索引?

问题描述

我正在设计一个反馈页面,其中有多个问题被问到,并且所有问题都有相同的多项选择答案。所以我设计如下。

options: string[] = ['Excellent', 'Fair', 'Good', 'Poor'];

  questions: any = [
    {
      question: "How would you rate A",
      answer: this.options,
      radioSelected: ""
    },
    {
      question: "How would you rate B",
      answer: this.options,
      radioSelected: ""
    },
    {
      question: "How would you rate C",
      answer: this.options,
      radioSelected: ""
    },
    {
      question: "How would you rate D",
      answer: this.options,
      radioSelected: ""
    },
    {
      question: "How would you rate E",
      answer: this.options,
      radioSelected: ""
    }
  ];
<div *ngFor="let q of questions; index as i">
        <label id="example-radio-group-label">{{q.question}}</label>
        <div class="row">
            <div class="form-check" *ngFor="let option of q.answer">
                <div class="col-md-3">
                    <input class="form-check-input" id="{{option}}" [value]="option" type="radio" name="options"
                        [(ngModel)]="q.radioSelected">
                    <label class="form-check-label" for="{{option}}">
                        {{option}}
                    </label>
                </div>
            </div>
        </div>
        <hr>
    </div>

代码在 UI 中显示良好。但是当我点击任何问题的单选按钮时,只有第一个问题的选项被选中。我是角度新手,请帮助我如何解决这个问题。

标签: htmlangulartypescript

解决方案


您缺少收音机上的唯一名称属性。一组选项的名称应该是唯一的。

在您动态生成单选按钮的用例中,您可以使用循环索引来设置名称,如下所示 -

 <div *ngFor="let q of questions; let  questionIndex=index">
                    <label id="example-radio-group-label">{{q.question}}</label>
                    <div class="row">
                        <div class="form-check" *ngFor="let option of q.answer; let answerIndex=index">
                            <div class="col-md-3">
                                <input class="form-check-input" [value]="option" type="radio" name="options{{questionIndex}}{{answerIndex}}"
                                    [(ngModel)]="q.radioSelected">
                                <label class="form-check-label">
                                    {{option}}
                                </label>
                            </div>
                        </div>
                    </div>
                    <hr>
                </div>

请在此处查看工作示例。

类似的问题在这里这里

希望对你有帮助 !!


推荐阅读