使用 ngModel 的动态单选按钮 2 路绑定 - Angular 6

Dynamic Radio Buttons 2 Way Binding using ngModel - Angular 6

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

我在 Whosebug 上看到了关于此主题的其他相关帖子,但其中 none 似乎对我有所帮助。

这是我的代码:

<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>

任何帮助将不胜感激。

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

private radioButtonValues : Array<any> = [];

然后将其绑定到您的 ngModel 中,索引 i 为 :

<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 事件以获得更多功能。

<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)'>

然后在你的组件中声明函数 class

changeEventInRadioButton($event) {
    console.log($event);
}

最后在表单提交检查

onSubmit(){
    console.log(this.radioButtonValues);
}