【问题标题】:Custom Radio button selection bug in angular 6 (inside of ngFor)角度 6 中的自定义单选按钮选择错误(ngFor 内部)
【发布时间】:2019-01-24 16:31:17
【问题描述】:

在 ngFor 中的一项内选择无线电输入会触发其他无线电输入检查。创建了一个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;
    }
  }

谢谢

【问题讨论】:

    标签: javascript html angular angular6 ngfor


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 是的,它奏效了,你能为这种奇怪的行为添加理由吗?
    • 如果您注意到,name="radio-{{item.Id}}"[name]="'radio-'+item.Id" 不会在无线电输入中添加名称属性。
    • @ sachin - 检查单选按钮时,浏览器会自动取消选中具有相同名称的其他单选按钮。 Angular 可能更喜欢保持单选按钮未命名,以便自己处理,而不必与浏览器的自动处理作斗争。
    猜你喜欢
    • 2020-05-28
    • 1970-01-01
    • 2019-11-17
    • 2013-09-03
    • 1970-01-01
    • 2017-02-16
    • 2013-06-08
    • 2020-03-03
    • 2019-01-17
    相关资源
    最近更新 更多