动态单选按钮 2 路绑定使用 ngModel - 角度 6



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

我已经在stackoverflow上看到了有关此主题的其他相关帖子,但是它们似乎都没有帮助我。

这是我的代码:

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

然后在组件类中声明函数

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

最后在表单提交检查

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

最新更新