使用 ngModel - Angular 6 的动态单选按钮 2 路绑定 [英] Dynamic Radio Buttons 2 Way Binding using ngModel - Angular 6

查看:22
本文介绍了使用 ngModel - Angular 6 的动态单选按钮 2 路绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成动态单选按钮,这些按钮将全部合并到表单提交中,而不是单独提交.但是,我需要将它们分别绑定到组件中的特定值,但我不知道该怎么做.

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>

任何帮助将不胜感激.

推荐答案

在组件中取一个数组的新变量:

Take a new variable of an array in component :

private radioButtonValues : Array<any> = [];

然后将它绑定在你的 ngModel 中,索引 i 为:

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 - Angular 6 的动态单选按钮 2 路绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆