使用ngModel的动态单选按钮2方式绑定-Angular 6 [英] Dynamic Radio Buttons 2 Way Binding using ngModel - Angular 6
问题描述
我正在生成动态单选按钮,它们将全部合并到表单提交中,而不是单独提交.但是,我需要将它们分别绑定到组件中的特定值,但我不知道该怎么做.
I'm generating dynamic radio buttons which will all be consolidated on form submit not individually. I however need to bind them to a particular value in my component individually which I have no clue how to do.
我在stackoverflow上看到了与此主题相关的其他文章,但是似乎没有一个对我有帮助.
I've seen the other related posts on this subject on stackoverflow but none of them seem to help me out.
这是我的代码:
<input type="radio" class="one" id="{{ i }}_{{ candidate.user._id }}_{{post.id}}_{{ candidate.date}}" name="{{post.id}}" [value]='candidate.user._id' [(ngModel)]="post.id">
<label for="{{ i }}_{{ candidate.user._id }}_{{post.id}}_{{ candidate.date }}">
<span>
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/242518/check-icn.svg" alt="Checked Icon" />
</span>
</label>
任何帮助将不胜感激.
推荐答案
在component中获取数组的新变量:
Take a new variable of an array in component :
private radioButtonValues : Array<any> = [];
然后将其绑定到索引为i
的ngModel中:
then bind it in you ngModel with index i
as :
<input type="radio" class="one"
id="{{ i }}_{{ candidate.user._id }}_{{post.id}}_{{ candidate.date}}"
name="{{post.id}}"
[value]='candidate.user._id'
[(ngModel)]="radioButtonValues[i]">
如果您想进行一些操作,还可以使用ngModelChange
事件获得更多功能.
if you want some manipulation you can also use ngModelChange
event for more functionality.
<input type="radio" class="one"
id="{{ i }}_{{ candidate.user._id }}_{{post.id}}_{{ candidate.date}}"
name="{{post.id}}"
[value]='candidate.user._id'
[(ngModel)]="radioButtonValues[i]"
(ngModelChange)='changeEventInRadioButton($event)'>
然后在组件类中声明函数
then declare function in your component class
changeEventInRadioButton($event) {
console.log($event);
}
最后进行表单提交检查
onSubmit(){
console.log(this.radioButtonValues);
}
这篇关于使用ngModel的动态单选按钮2方式绑定-Angular 6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!