ngIf - Expression has changed after it was checked

naomi picture naomi · Apr 20, 2017 · Viewed 93.2k times · Source

I have a simple scenario, but just can't get it working!

In my view I display some text in a box with limited height.

The text is being fetched from the server, so the view updates when the text comes in.

Now I have an 'expand' button that has a ngIf that should show the button if the text in the box is overflowing.

The problem is that because the text changes when it is fetched, the 'expand' button's condition turns to true after Angular's change detection has finished...

So I get this error: Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'.

Obviously the button does not show...

see this Plunker (check the console to see the error...)

Any idea how to make this work?

Answer

Tiep Phan picture Tiep Phan · Apr 20, 2017

this error occur because you in dev mode:

In dev mode change detection adds an additional turn after every regular change detection run to check if the model has changed.

so, to force change detection run the next tick, we could do something like this:

export class App implements AfterViewChecked {

  show = false; // add one more property

  constructor(private cdRef : ChangeDetectorRef) { // add ChangeDetectorRef
    //...
  }
  //...
  ngAfterViewChecked() {
    let show = this.isShowExpand();
    if (show != this.show) { // check if it change, tell CD update view
      this.show = show;
      this.cdRef.detectChanges();
    }
  }

  isShowExpand()
  {
    //...
  }
}

Live Demo: https://plnkr.co/edit/UDMNhnGt3Slg8g5yeSNO?p=preview