Reputation: 67
I have multiple checkboxes but I want user to select one checkbox but not multiple, if he check one checkbox and it returns checked value, else nothing should show up.can anyone help?
<div class="form-check" *ngFor="let product of DisplayProductList">
<label class="form-check-label text-break">
<input class="form-check-input" type="checkbox" [value]="true" [(ngModel)]="product.isChecked"
(change)="changeSelection($event)" />
{{ product.template_name }}
<span class="form-check-sign">
<span class="check"></span>
</span>
</label>
</div>
changeSelection(event: any) {
this.checkedIDs = [];
if (event.target.checked) {
this.selectedItemsList = this.DisplayProductList.filter(
(product, index) => {
if (product.isChecked == true) {
let splitstring = product.template_parameter;
let sepratedArray = splitstring.split(',');
this.variable1 = sepratedArray[0];
this.variable2 = sepratedArray[1];
this.checkedIDs.push(product.id);
this.sendclusteridApi(this.productid);
return product.isChecked;
}
}
);
}
}
Upvotes: 2
Views: 13009
Reputation: 6706
As mentioned in the comments, this is what radio buttons do, but if you need to implement the same functionality using checkboxes, you can achieve that like the following:
selectedIndex
variable, and assign to it the index of the last checked checkbox.ngModel
of the checkboxes to [ngModel]="selectedIndex === index"
where the index
is the index of the checkbox within the *ngFor loop.<div class="form-check" *ngFor="let product of DisplayProductList; let index = index">
<label class="form-check-label text-break">
<input class="form-check-input" type="checkbox" [ngModel]="selectedIndex === index"
(change)="changeSelection($event, index)" />
{{ product.template_name }}
<span class="form-check-sign">
<span class="check"></span>
</span>
</label>
</div>
selectedIndex: number;
changeSelection(event, index) {
this.selectedIndex = event.target.checked ? index : undefined;
// do your logic here...
}
Upvotes: 4