Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngIf - Expression has changed after it was checked

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?

like image 742
naomi Avatar asked Apr 20 '17 07:04

naomi


People also ask

How do you fix expression has changed after it was checked?

Navigate up the call stack until you find a template expression where the value displayed in the error has changed. Ensure that there are no changes to the bindings in the template after change detection is run. This often means refactoring to use the correct component lifecycle hook for your use case.

Does ngIf detect changes?

the next time that parent component data changes and its change detection triggered also check for changes in child component because you reserved this check by calling markForCheck() in the previous time, again *ngIf react to changes before its container, so it gets and replaces dom with the old data.

Has change detection hook been created?

Has it been created in a change detection hook? You've created component dynamically ("outside" of angular lifecycle), this means you need to control change detection manually. Yep!


7 Answers

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

like image 91
Tiep Phan Avatar answered Oct 11 '22 12:10

Tiep Phan


Causing change detector to run after ngAfterContentChecked solved the problem for me

example as below:

import { ChangeDetectorRef,AfterContentChecked} from '@angular/core'
export class example implements OnInit, AfterContentChecked {
    ngAfterContentChecked() : void {
        this.changeDetector.detectChanges();
    }
}

Although, as I read some of the articles, this issue gets solved in production mode without any required fix.

Below is the possible reason for such issue:

It enforces a uni-directional data flow: when the data on our controller classes gets updated, change detection runs and updates the view.

But that updating of the view does not itself trigger further changes which on their turn trigger further updates to the view

https://blog.angular-university.io/how-does-angular-2-change-detection-really-work/

like image 39
Nikhil Kamani Avatar answered Oct 11 '22 12:10

Nikhil Kamani


For some reason, @Tiep Phan's answer didn't work for me to force change detection, but using setTimeout (which also forces change detection) did.

I also only had to add it to the offending line, and it worked fine with the code I already had in ngOnInit instead of having to add ngAfterViewInit.

Example:

ngOnInit() {
    setTimeout(() => this.loadingService.loading = true);
    asyncFunctionCall().then(res => {
        this.loadingService.loading = false;
    })
}

More details here: https://github.com/angular/angular/issues/6005

like image 29
cs_pupil Avatar answered Oct 11 '22 13:10

cs_pupil


implement AfterContentChecked method.

constructor(
    private cdr: ChangeDetectorRef,
) {}

ngAfterContentChecked(): void {
   this.cdr.detectChanges();
}  
like image 33
Parinda Rajapaksha Avatar answered Oct 11 '22 12:10

Parinda Rajapaksha


To overcome this issue you can move the variable that changes *ngIf state, from ngAfterViewInit to ngOnInit or constructor.Because it's not allowed to change the state of html while AfterViewInit method is calling.

As @tiep-phan told, another way is passing ChangeDetectorRef to constructor and calling this.chRef.detectChanges() after changing state of *ngIf in AfterViewInit method.

like image 37
AmirHossein Rezaei Avatar answered Oct 11 '22 12:10

AmirHossein Rezaei


We can also suppress this ExpressionChangedAfterItHasBeenCheckedError being thrown by changing the changeDetection to OnPush. So, extra change detection will not be executed hence no error is thrown. For this, you need to add ChangeDetectionStrategy.OnPush as part of @Component decorator in your .ts file as below:

@Component({
  selector: 'your-component',
  templateUrl: 'your-component.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
like image 27
Steffi Keran Rani J Avatar answered Oct 11 '22 11:10

Steffi Keran Rani J


For anyone struggling with something similar, basically you are trying to update the dom in a place where you shouldn't, in this link https://blog.angular-university.io/angular-debugging/ you can find details on how to debug, find the exact piece of code that is generating the issue, and some ideas on how to fix it

like image 34
Camilo Casadiego Avatar answered Oct 11 '22 13:10

Camilo Casadiego