[SOLVED]Ion-checkbox dynamically set checked


#1

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++) {
            this.selectedCategory.push(
                  vendor.category_id[i].i_vendor_category_id
                );
            }

and the ionChange event method:

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

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?


#2

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.


#3

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


#4

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.