Checkbox 在ngFor的angular 5中,如何在给定列表中一次只选中一个复选框?
我只想在ngFor angular 5中一次选中一个复选框。 我有下面的代码Checkbox 在ngFor的angular 5中,如何在给定列表中一次只选中一个复选框?,checkbox,angular5,ngfor,Checkbox,Angular5,Ngfor,我只想在ngFor angular 5中一次选中一个复选框。 我有下面的代码 <div class="form-check" style="margin-top:0;"> <label class="form-check-label"> <input class="form-check-input" id="res{{restaurant._id}}" (change)="selectRestaurant(restaurant,i)" [checke
<div class="form-check" style="margin-top:0;">
<label class="form-check-label">
<input class="form-check-input" id="res{{restaurant._id}}" (change)="selectRestaurant(restaurant,i)" [checked]="restaurant.checked" type="checkbox">
<span class="form-check-sign"></span>
</label>
</div>
因此,对于给定列表中仅选择一个复选框,是否有任何可能的解决方案?您必须使用ngmodel将复选框项绑定到for循环中的特定实例。
您可以尝试使用ReactiveForms。参见一个示例我看到了许多使用循环的示例。但我认为复选框太多是个坏主意。我建议用另一种方法 创建包含复选框索引的变量
public checkboxIndex = 0; //default value for checking
public checkboxModel = [];
ngOnInit() {
for (let i = 0; i < checkboxCount.length; i++) {
this.checkboxModel.push({ name: `${i}`, enabled: false });
}
public checkboxChange(index) {
if (this.checkboxIndex !== index) {
this.checkboxModel[this.checkboxIndex].enabled = false;
}
this.checkboxIndex = index;
}
//HTML
<div *ngFor="let checkbox of checkboxCount.length; let i = index">
<input type="checkbox" [(ngModel)]="checkboxModel[i].enabled"
name="checkboxModel[i].name"
(change)="checkboxChange(i)"> </input>
</div>
public checkboxIndex=0//用于检查的默认值
公共checkboxModel=[];
恩戈尼尼特(){
for(设i=0;i
这应该会有帮助。如果我犯了一些错误,请纠正我
public checkboxIndex = 0; //default value for checking
public checkboxModel = [];
ngOnInit() {
for (let i = 0; i < checkboxCount.length; i++) {
this.checkboxModel.push({ name: `${i}`, enabled: false });
}
public checkboxChange(index) {
if (this.checkboxIndex !== index) {
this.checkboxModel[this.checkboxIndex].enabled = false;
}
this.checkboxIndex = index;
}
//HTML
<div *ngFor="let checkbox of checkboxCount.length; let i = index">
<input type="checkbox" [(ngModel)]="checkboxModel[i].enabled"
name="checkboxModel[i].name"
(change)="checkboxChange(i)"> </input>
</div>