Checkbox UI form control provides basic states like checked, unchecked and disabled. But there is one more state known as Indeterminate state.
The indeterminate state usually depicts that only partial checkboxes are checked in the list. It is mostly used in Master checkbox which indicates the child checkbox list.
Indeterminate checkbox state indicates that not all but some of the checkboxes are checked.
Let’s create a demo app with Check/ Uncheck All item list
On the master check, we will add <strong>indeterminate </strong>
property which takes a boolean value. Also, there will be a click event and <strong>ngModel</strong>
. In Child list checkbox we will have a <strong>ionChange</strong>
event. Child item with checkboxes will iterate using *ngFor
<ion-list>
<ion-item>
<ion-label><strong>Select All</strong></ion-label>
<ion-checkbox slot="start"
[(ngModel)]="masterCheck"
[indeterminate]="isIndeterminate"
(click)="checkMaster($event)"></ion-checkbox>
</ion-item>
</ion-list>
<ion-list>
<ion-item *ngFor="let item of checkBoxList">
<ion-label>{{item.value}}</ion-label>
<ion-checkbox slot="start"
[(ngModel)]="item.isChecked"
(ionChange)="checkEvent()"></ion-checkbox>
</ion-item>
</ion-list>
Add methods and dummy list <strong>checkBoxList</strong>
in ts file. The <strong>checkMaster</strong>
method will check/uncheck list items by iterating using <strong>forEach</strong>
. The <strong>checkEvent</strong>
will be available on every child list checkbox to calculate total checked items to handle the state of master checkbox.
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
isIndeterminate:boolean;
masterCheck:boolean;
checkBoxList:any;
constructor(){
this.checkBoxList = [
{
value:"Esteban Gutmann IV",
isChecked:false
},{
value:"Bernardo Prosacco Jr.",
isChecked:false
},{
value:"Nicholaus Kulas PhD",
isChecked:false
},{
value:"Jennie Feeney",
isChecked:false
},{
value:"Shanon Heaney",
isChecked:false
}
];
}
checkMaster() {
setTimeout(()=>{
this.checkBoxList.forEach(obj => {
obj.isChecked = this.masterCheck;
});
});
}
checkEvent() {
const totalItems = this.checkBoxList.length;
let checked = 0;
this.checkBoxList.map(obj => {
if (obj.isChecked) checked++;
});
if (checked > 0 && checked < totalItems) {
//If even one item is checked but not all
this.isIndeterminate = true;
this.masterCheck = false;
} else if (checked == totalItems) {
//If all are checked
this.masterCheck = true;
this.isIndeterminate = false;
} else {
//If none is checked
this.isIndeterminate = false;
this.masterCheck = false;
}
}
}
So using the above method we can easily create a nice check/uncheck all list in Ionic using new Indeterminate state.
Leave a Reply