javascript - Angular 6 中的自定义单选按钮选择错误(在 ngFor 内部)

标签 javascript html angular angular6 ngfor

在 ngFor 中的一个项目内选择 radio 输入会触发其他 radio 输入检查。创建了一个 demo .

HTML

<div class='section' *ngFor="let item of radioData">
    <div class="radio-selection">
        <input type="radio" attr.name="radio-{{item.Id}}" value="true" attr.id="radio-first-{{item.Id}}" [(ngModel)]='item.IsSelected'>
        <label attr.for="radio-first-{{item.Id}}">Radio-first {{item.Id}}--value={{item.IsSelected}}</label>
    </div>
    <div class="radio-selection">
        <input type="radio" attr.name="radio-{{item.Id}}" value="false" attr.id="radio-second-{{item.Id}}" [(ngModel)]='item.IsSelected'>
        <label attr.for="radio-second-{{item.Id}}">Radio-second {{item.Id}}--value={{item.IsSelected}}</label>
    </div>
</div>

CSS

.section {
  border:1px solid #000;
  margin-bottom:1rem;
}
.radio-selection {
    input[type="radio"] {
      display: none;
    }
    input[type="radio"] + label {
      position: relative;
      display: inline-block;
      vertical-align: middle;
      margin: 5px;
      cursor: pointer;
      &:hover {
        &:before {
          border-color: green;
        }
      }
    }

    input[type="radio"] + label:before {
      content: "";
      background: #fff;
      border: 1px solid #333;
      display: inline-block;
      vertical-align: middle;
      width: 15px;
      height: 15px;
      margin-right: 10px;
      text-align: center;
      padding: 2px;
      border-radius:50%;
    }

    input[type="radio"]:checked + label:before {
      background:red;
      box-shadow: inset 0px 0px 0px 2.5px #fff;
    }
  }

谢谢

最佳答案

使用 name 而不是 attr.name 来设置输入元素的名称(参见 this stackblitz ):

<input type="radio" name="radio-{{item.Id}}" ...>

或使用属性绑定(bind)语法(参见 this stackblitz ):

<input type="radio" [name]="'radio-'+item.Id" ...>

关于javascript - Angular 6 中的自定义单选按钮选择错误(在 ngFor 内部),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51898641/

相关文章:

javascript - React js - 表达: res.发送与res.render错误

javascript - 尽管在我的 Controller 中使用了await,为什么我还是收到Promise Pending?

javascript - 点击外部导航关闭

javascript - 如何打印(在屏幕上)具有外部 url 的 iframe 所需的所有 JS 代码

javascript - 基于 id 的 React 路由

Javascript:从选择输入中获取多个值

angular - 如何从 Intellij idea 2017.1 运行 Angular 应用程序?

express - 赋值表达式的左侧不能是常量或只读属性

angular - 嵌套情况下cdk拖拽

javascript:禁用文本选择