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