html - 如何以角度跟踪 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 中显示良好。但是当我点击任何问题的单选按钮时,只有第一个问题的选项被选中。我是角度新手,请帮助我如何解决这个问题。
解决方案
您缺少收音机上的唯一名称属性。一组选项的名称应该是唯一的。
在您动态生成单选按钮的用例中,您可以使用循环索引来设置名称,如下所示 -
<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>
请在此处查看工作示例。
希望对你有帮助 !!
推荐阅读
- entity-framework - 是否有针对 Visual Studio 2019 的 enable-migrations Command Not foundError 的解决方案?
- php - htaccess 404 和 400 重定向不适用于网站上的所有页面
- php - SQL 两个 SELECTS 多个和两个 JOINS
- sql-server - Sql 服务器备份
- c# - Unity sprite 在位置更改之前显示
- scala - com.typesafe.config.ConfigFactory.load(Config) 做什么?
- javascript - ReactJS:将状态传递给孩子返回未定义
- c++ - clang-analyzer 可能出现误报(垃圾或未定义)
- google-cloud-platform - 将控件 A (\u0001) 分隔文件加载到 Google Big Query
- android - 实现一个简单的 Dagger2 示例