How to use the indeterminate checkbox in Angular or in any other framework?
We have seen this common feature in emails or whenever we select anything on other platforms.
Whenever we select all the checkboxes of the list, then the checkbox on the table header shows checked.
If no checkbox is selected in the list, then the checkbox is unchecked.
But what if we select some of the lists only so it means we have some list that is checked and some that are not checked which result in the indeterminate situation.
Also, for selecting all checkboxes or deselecting all checkboxes, we can also click the table header checkbox.
If it’s currently in an indeterminate state, then after click it will go checked state.
and If it’s in the checked state it will go to the unchecked state.
Html
<table class="table table-hover>
<thead>
<tr>
<th>
<mat-checkbox [indeterminate]="chkBoxStatus==1" [checked]="chkBoxStatus==2"
(change)="clrUnClrSel($event.checked)"></mat-checkbox>
</th> <!-- this checkbox in the table header
<th>Name</th>
</tr>
</thead>
<tbody *ngFor="let user of users">
<td>
<mat-checkbox [checked]="user.chk" (change)="chngChkBox($event, user)"></mat-checkbox>
</td>
<td>{{user.name}}</td></tbody>
</table>
Here we will use two functions one function when checkbox click that is inside the table body and the other which we use that is on the table header.
TS File
//variables declaration
chkBoxStatus: number = 0;//0 means no, 1 means inderminate,2 means checked - using in the table headerselItems: number = 0;//holding how many data is selected 1,2 ,3 so I can show the selected number or I can also calculate by interating the array whose value is checkedchngChkBox(event: any, c: any) {
c.chk = event.checked;
let isSome = false, type = 0;
let items = 0;
for (let k = 0; k < this.users.length; k++) {
if (this.users[k].chk) {
items++;
isSome = true;
if (type != 1)
type = 2
} else
type = 1;
}
this.selItems = items;
this.chkBoxStatus = type == 2 ? 2 : isSome ? 1 : 0;
}clrUnClrSel(val: boolean) {
for (let k = 0; k < this.users.length; k++) {
this.users[k].chk = val;
}
if (val) {
this.selItems = this.users.length;
this.chkBoxStatus = 2;
} else {
this.selItems = 0;
this.chkBoxStatus = 0;
}
}
For showing the selected items, clear selection button, we need to add that in the HTML. Also, make sure we show that row only if some checkbox is selected for better user experience, and whenever all checkboxes user unchecks, then that row will be removed from the dom.
The new HTML which we need to be added for the above functionality
<div *ngIf="selItems>0">
{{selItems}} of {{cntnts.length}} items selected
<div class="btn btn-primary btn-sm" (click)="clrUnClrSel(false)">Clear Selection</div>
</div>
For the react also, plain js or any other front end framework we can use the same concept too.
Happy Coding with the indeterminate checkbox.💗