[SOLVED]Ion-checkbox dynamically set checked


Here is the html code:

<ion-checkbox color="dark" [checked]="selectedCategory.indexOf(category.i_id) >= 0" (ionChange)="updateCheckedOptions(category.i_id,$event)"></ion-checkbox>

Here is the ionViewDidLoad() method:

for (let i = 0; i < vendor.category_id.length; i++) {

and the ionChange event method:

updateCheckedOptions(id) {
    let idx = this.selectedCategory.indexOf(id);
    if (idx > -1) {
      this.selectedCategory.splice(idx, 1);
    } else {

Problem: When I am dynamically setting the selectedCategory array with the values, I get an error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.

If I comment the updateCheckedOptions method, I don’t get the error but I am not able to perform my task on ionChange. I need this method to set the array when the user taps on the checkboxes.

How to keep the ionChange method working and not get the above error? Can anybody help?


I’ve found it a good policy to bind always to variable names. [property] = nameOfVariable Then I change the value of nameOfVariable in the ts file. This isn’t necessary, but I’m pretty sure it’s helped me avoid a lot of weird errors. If you do that, you’ll probably get a page that compiles but behaves incorrectly. Then you can improve the page’s behavior.


changed (ionChange) to (click). it worked. Not marking this as solved as I have to test on the device. Hopefully this will work.


I completely agree with @AaronSterling here that overly cute template expressions and change handlers not only introduce lots of hard-to-understand bugs, but also result in poor performance because of how many times they are executed. I would simply bind to an isSelected property of each category here.