This is how I create a list with checkboxes to check/uncheck employees. I am binding the checked property of an employee to the checkbox.
<ion-list>
<ion-item *ngFor="let employee of employees; let i = index">
<ion-label>{{employee.name}}</ion-label>
<ion-checkbox value="{{employee.id}}"
[(ngModel)]="employee.isChecked"
(ionChange)="emplsChange($event.detail.checked, i)"></ion-checkbox>
</ion-item>
</ion-list>
However, when the checkbox is changed, I want to check if it can be checked or has to be false. In order to do that, I set the isChecked property of the selected employee to false after I’ve checked the conditions.
emplsChange(detail: boolean, index: number) {
const newEmployees: IEmployee[] = this.employees;
this.employees = [];
// get all checked employees
const checkedEmpls = newEmployees.filter(e => e.isChecked).length;
newEmployees[index].isChecked = detail && checkedEmpls === this.needdedEmpls ? false : detail;
this.employees = newEmployees;
}
Now, the thing is, that if the condition is true and I set the isChecked to false it works correctly and the checkbox is not checked. But only on the first time. If I check the same employee again the isChecked is set to false but on the UI it is checked.
I’ve tried to solve this by using (ngModelChange) instead of (ionChange) but it did nothing to it.
So the main Problem is, that the UI is not properly updated, when I set the ion-checkbox-Model in the onchange method of the component. Can one of you see another problem? Did someone experienced the same? CaN Som3One plZ HeLp!1!!!11
Thx
I am using Ionic:
Ionic CLI : 5.2.1 Ionic Framework : @ionic/angular 4.7.0-dev.201907122213.5db409f @angular-devkit/build-angular : 0.801.1 @angular-devkit/schematics : 8.1.1 @angular/cli : 8.1.1 @ionic/angular-toolkit : 2.0.0
UPDATE: I solved it by using a deep copy instead of handling the reference of the employees array in the ionchange-method. the new looks like this:
emplsChange(detail: boolean, index: number) {
const newEmployees: IEmployee[] = this.copy(this.employees);
const checkedEmpls = newEmployees.filter(e => e.isChecked).length;
const needdedEmpls = this.day.event.scheduledTask.scheduledTaskDays[this.indexOfDay].neededEmployees;
if (detail !== newEmployees[index].isChecked) {
newEmployees[index].isChecked = detail && checkedEmpls === needdedEmpls ? !detail : detail;
this.employees = newEmployees;
}
}
copy(o) {
let output, v, key;
output = Array.isArray(o) ? [] : {};
for (key in o) {
v = o[key];
output[key] = (typeof v === 'object') ? this.copy(v) : v;
}
return output;
}
Try to this:-
<ion-checkbox value="{{employee.id}}" [(ngModel)]="employee.isChecked" (ionChange)="emplsChange($event.checked, i)">