使用* ngFor [Angular2]创建多个单选按钮 [英] Creating multiple radio buttons with *ngFor [Angular2]
本文介绍了使用* ngFor [Angular2]创建多个单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要根据对象数组(例如:enum_details )的长度动态选择单选按钮的数量:
I need dynamic number of radio buttons based on the length of Array Of Objects (eg: enum_details):
以下是我尝试的代码:
<div *ngFor="let enum of enum_details">
<label for="enum_answer_{{enum.value}}">
<input id="enum_answer_{{enum.value}}" type="radio" name="enums" [(ngModel)]="enum.value">
{{enum.display_text}}
</label>
</div>
但是,当我单击任何单选按钮时,总是选择最后一个单选按钮,并且永远不会将值分配给 ngModel .
But, when I click any radio, always the last one gets selected and the value is never assigned to ngModel.
如果我删除了 ngModel ,则收音机可以正常工作,但是未设置值.可以解决这里的问题吗?
If I remove ngModel, the radios work fine, but, value is not set. What can be the fix here?
推荐答案
像这样使用您的代码
<div *ngFor="let enum of enum_details">
<label for="enum_answer_{{enum.name}}">
<input id="enum_answer_{{enum.name}}" [value]='enum.name' type="radio" name="enums" [(ngModel)]="radioSelected">
{{enum.name}}
</label>
</div>
<button (click)='radioFun()'>Checked value of radio button</button>
工作示例
working example
Working example here
这篇关于使用* ngFor [Angular2]创建多个单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文