I'm trying to programatically set the value of Angular checkboxes to either, false
true
or intermediate
. I understand that I cannot set the checkbox to the value intermediate
however we do have access to [intermediate]
on the input. Is it possible to set all three states via ngModel
somehow?
I have the following code which kinda works, however I am getting a ExpressionChangedAfterItHasBeenCheckedError
error.
HTML
<div *ngFor="let label of ClientLabels | async">
<label for=""></label>
<input id="" type="checkbox" name="group" [indeterminate]="checkedLabels()"
[checked]="checkedLabels(label)" (change)="toggleSelectedLabels(label)" />
</div>
TS
checkedLabels(label): boolean {
const index = this.selectedLabels.indexOf(label.objectId);
this.intermediateState = false;
if (!this.selectedClients.length) {
return false;
}
if (this.countInArray(this.selectedLabels, label.objectId) === this.selectedClients.length) {
return true;
}
if (index >= 0) {
this.intermediateState = true;
}
}
countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
Here the use case is similar to that of labels in Gmail, except clients are used in the place of an email. If all of the emails have the same label then they show as checked, however if not all of them share the label then it will show an intermediate which can be cycled through the three states (true, false, intermediate).
Q1. How can I cycle through these three state in the same way as you can with gmail?
Q2. Why am I getting the ExpressionChangedAfterItHasBeenCheckedError
with the current setup?
Here is a Stackblitz of current progress https://stackblitz.com/edit/angular-3bbutx
Aucun commentaire:
Enregistrer un commentaire