Reputation: 53
HTML file
<ion-list *ngIf="items" >
<ion-item *ngFor="let driver of items; let i = index">
<ion-label>{{driver.name}}</ion-label>
<ion-checkbox [(ngModel)]="driver.checked" (ionChange)="checked(driver)" item-right></ion-checkbox>
</ion-item>
</ion-list>
TS File
checked(driver) {
if (driver.checked === true) {
this.checkedDrivers.push(driver);
} else if (driver.checked === false) {
this.checkedDrivers.splice(this.checkedDrivers.indexOf(driver), 1);
}
}
This is the html file and ts file for my checkbox, I manage to allow user to check the check boxes and print the value of the checkboxes but I want to limit the checkboxes where user can only checked two of it. How do I do it?
Upvotes: 1
Views: 2125
Reputation: 29625
You could have a check in checked()
to see if two items are checked and use a boolean variable to enable/disable the checkboxes.
<ion-list *ngIf="items" >
<ion-item *ngFor="let driver of items; let i = index">
<ion-label>{{driver.name}}</ion-label>
<ion-checkbox [(ngModel)]="driver.checked" [disabled]="isCheckboxDisabled" (ionChange)="checked(driver)" item-right></ion-checkbox>
</ion-item>
</ion-list>
In your TS file, set isCheckboxDisabled
as false,
isCheckboxDisabled:boolean=false;
checked(driver) {
if (driver.checked === true) {
this.checkedDrivers.push(driver);
} else if (driver.checked === false) {
this.checkedDrivers.splice(this.checkedDrivers.indexOf(driver), 1);
}
//check for two selected.
if(this.items.filter(driver=> driver.checked).length===2){
this.isCheckboxDisabled=true;
}
}
Upvotes: 2