[英]Angular ngModel not set radio button value inside ngFor
I am new on angular, need your assistance in one of my problem.我是 angular 的新手,我的一个问题需要您的帮助。 I have a scenario where I am getting array of objects from API like我有一个场景,我从 API 获取对象数组,例如
[{name: "abc", score: 2},{name: ""def, score: 3}]
here score is from 0 to 3. And I have to show the score on UI like below image这里的分数是从 0 到 3。我必须在 UI 上显示分数,如下图所示
first radio button is for score 0 and second for score 1 till last ie score 3第一个单选按钮用于得分 0,第二个单选按钮用于得分 1 直到最后,即得分 3
and my angular code is我的 angular 代码是
<div *ngFor="let mark of marks; let ind = index">
{{mark.name}}
<input type="radio" [value]="0" name="score" id="zero"
[(ngModel)]="mark.score">
<input type="radio" [value]="1" name="score" id="one"
[(ngModel)]="mark.score">
<input type="radio" [value]="2" name="score" id="two"
[(ngModel)]="mark.score">
<input type="radio" [value]="3" name="score" id="three"
[(ngModel)]="mark.score">
</div>
If I run the code, I am getting only last name score in list is checked with the score and rest of the above scores show blank.如果我运行代码,我只得到列表中的姓氏分数,上面的分数和 rest 显示为空白。
PS: And make edit score again with the new scores. PS:并用新的分数再次编辑分数。
Thanks.谢谢。
Having different name for each radio button will solve the problem.为每个单选按钮设置不同的名称将解决问题。
<div *ngFor="let mark of marks; let i = index">
{{mark.name}}
<input type="radio" value="0" id="zero" [name]="marks[i].name + i" [(ngModel)]="marks[i].score">
<input type="radio" value="1" id="one" [name]="marks[i].name + i" [(ngModel)]="marks[i].score">
<input type="radio" value="2" id="two" [name]="marks[i].name + i" [(ngModel)]="marks[i].score">
<input type="radio" value="3" id="three" [name]="marks[i].name + i" [(ngModel)]="marks[i].score">
</div>
This is because ngModel for each radio will be the one which is selected.这是因为每个收音机的 ngModel 都是被选中的。 Try to bind new variable to ngModel.. Try this: https://stackblitz.com/edit/angular-radio-button-api尝试将新变量绑定到 ngModel.. 试试这个: https://stackblitz.com/edit/angular-radio-button-api
Good that you accepted answer;很好,您接受了答案; but to answer the question in title.但要回答标题中的问题。
Set value
to index
, like:将value
设置为index
,例如:
<div *ngFor="let item of itemList; let i = index">
<input type="radio" name="picker"
[value]="i"
[(ngModel)]="item.isPicked">
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.