【问题标题】:Dynamic Radio Buttons 2 Way Binding using ngModel - Angular 6使用 ngModel 的动态单选按钮 2 方式绑定 - Angular 6
【发布时间】:2019-02-05 10:59:31
【问题描述】:

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

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

任何帮助将不胜感激。

【问题讨论】:

  • 它不是已经通过 post.id 绑定到特定值了吗?不确定你想要什么,但this 有帮助吗?

标签: angular radio-button angular-ngmodel


【解决方案1】:

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

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);
}

【讨论】:

  • 感谢 Nasiruddin Saiyed,ngModel 中的索引修复了它。虽然我不得不使用 public radioButtonValues : Array = [];使其可访问
猜你喜欢
  • 2017-07-22
  • 2023-03-14
  • 2019-02-14
  • 2018-09-19
  • 2014-03-24
  • 2017-08-20
  • 2017-09-21
  • 2016-10-20
  • 2017-10-17
相关资源
最近更新 更多