0

I've tried to implement all the recommended methods as suggested

Everything you need to know about the ExpressionChangedAfterItHasBeenCheckedError error

ExpressionChangedAfterItHasBeenCheckedError Explained

However, either it's in combination with Ionic or my own developer skills that are letting me down, I am unable to get this to work without hitting the ExpressionChangedAfterItHasBeenCheckedError error.

I have a list of items that I would like to be able to select independently or allow the user to Select All.

In the .ts file I have two methods:

  toggleSelectedUser(user) {
    const index = this.selectedUsers.indexOf(user);
    if (index >= 0) {
      this.selectedUsers.splice(index, 1);
    } else {
      this.selectedUsers.push(user);
    }
  }

  toggleSelectAll() {
    if (!this.selectedUsers.length) {
      this.selectedUsers = [...this.template.userData];
    } else {
      this.selectedUsers = [];
    }
  }

And in my template I am using

  <ion-toggle item-end color="secondary" checked="false" id="checkbox{{idx}}" [checked]="isSelected(user)" (ionChange)="toggleSelectedUser(user)"></ion-toggle>

Is selected simply does this:

  isSelected(user) {
    return this.selectedUsers.indexOf(user) >= 0;
  }

Single toggles are working fine, however when I try to perform toggleSelectAll() I get the dreaded ExpressionChangedAfterItHasBeenCheckedError.

Taylorsuk
  • 1,419
  • 1
  • 16
  • 51

1 Answers1

0

This is developing mode error first of all and should not come to the production environment. This error usually comes when the @Input data is been changed in the child component, as the change detection cycle runs when any changes are detected in the UI.

This error can be fixed calling detectChanges() method inside AfterContentChecked lifecycle hook. Or you can also use setTimeout() function to make you code async.

You can look into this article for detailed understanding.

https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

Yashwardhan Pauranik
  • 5,370
  • 5
  • 42
  • 65
  • Hi, I've checked the link as I said in my question, however I am unable to implement it, I just get an infinite loop. Where in my code would I put the `setTimeout` to prevent my infinite loop? – Taylorsuk Nov 25 '18 at 12:58
  • @Taylorsuk yeah you can check by putting your code inside setTimeout – Yashwardhan Pauranik Nov 25 '18 at 12:59