How to avoid the ExpressionChanged error, when using a method to set [ngClass]?

OGarvey

I have the following components:

client-card.component.html:

<div id="content">
<div id="card" (click)="viewDetails(client.clientId)">
  <div id="front">
    <div id="top-pic" [ngClass]="setTopPic()"></div>
    <div id="avatar"></div>
    <div id="info-box" [class.green]="(i + 1) % 2 == 0" [class.blue]="(i + 1) % 2 != 0">
      <div class="info">
        <h1>{{ client.surname }}, {{ client.forename }}</h1>
        <h2>{{ client.postcode }}</h2>
      </div>
    </div>
  </div>
</div>

client-card.component.ts:

import { Router } from '@angular/router';
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-client-card',
  templateUrl: './client-card.component.html',
  styleUrls: ['./client-card.component.css']
})
export class ClientCardComponent implements OnInit {

  @Input() client: any = {};
  @Input() i: number;

  constructor(private router: Router) { }

  ngOnInit() {
    console.log(`Init Card Component`)
  }

  viewDetails(clientId: number) {
    this.router.navigate(['/client', clientId]);
  }

  setTopPic() : string {
    if((this.i + 1) % 2 == 0) {
      return "blue" + Math.ceil(Math.random() * 4).toString();
    } else {
      return "green" + Math.ceil(Math.random() * 4).toString();
    }
  }

}

client-list.component.html:

<div class="row">
  <div class="col-xs-12 col-sm-6 col-md-4 col-lg-3" *ngFor="let client of clients; let i = index">
    <app-client-card [client]="client" [i]="i"></app-client-card>
  </div>
</div>

Whenever the client-list component displays the cards, I receive the following error in the console:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'blue1'. Current value: 'blue2'.

I've read a few different explanations of various causes of this error, but am unfortunately no closer to resolving it.

Any assistance greatly appreciated.

rinukkusu

Usually you'll get this error while running in non-production mode and the cause is change detection running two times to check if you're not having a bug somewhere in your code which modifies data outside of the zone.

What's happening here is that your method setTopPic() might return a different value everytime it's called, so change detection is seeing blue1 on checking the binding and blue2 after that.

I'd suggest to store the class name in a member variable on init, since it relies on your other member variable i:

export class ClientCardComponent implements OnInit {

  @Input() client: any = {};
  @Input() i: number;

  topPic: string;

  constructor(private router: Router) { }

  ngOnInit() {
    console.log(`Init Card Component`);
    this.topPic = setTopPic(); // <-- here
  }

And use that in the binding:

<div id="top-pic" [ngClass]="topPic"></div>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to avoid using function in ngStyle or ngClass?

How to avoid JSON error when using webdriver?

styling error when added styles using ngClass

How to avoid empty value when using getValueAt() method?

How to avoid mutations when using the sub() method in regex?

How to avoid null exception when using equals() method in Java

How to avoid null excpetion when using equals()method in java

How to avoid weird umlaute error when using data.table

How to avoid memory error when using recursion? (Fibonacci Numbers)

How to avoid Type expected error while using WHEN?

How to avoid `out` parameter error when using intrinsics?

How to avoid no match error when using IFS and ARRAYFORMULA

How to avoid a NonType error in template when using ForeignKey in Model?

How to avoid Error 1242 when using LIKE with a subquery with multiple rows

How to avoid null warning when using @NotNull and checking for null in another method before method call?

Angular 6 - How to format [ngClass] when using a variable

How to avoid repetitions within Angular ngClass?

How to avoid a double borrow error in struct method

How to avoid the error for complex round method.?

How to avoid error ocuured due to minus sign of southern latitudes when mixed set of latitudes convert from degrees minutes to decimal degree using R

How to avoid error on MYSQL CONVERT() method, when passing a 0 second string and subtract from that value?

Avoid arithmetic overflow error when using dbplyr

How to avoid the splitting of a string when converting to set?

How to avoid error when using Eloquent's toArray when getting null result

How can I avoid dropping rows with NaNs when using Pandas `where` method?

How do I avoid audio from disappearing when using `Tone.PolySynth()` with `Sequence` method?

How to set CORS of a public Google Cloud Storage buckets to avoid errors when using javascript fetch function?

How to avoid an error when listing nonexistent files?

How to avoid error when including multiple times