ngIf - Expression has changed after it was checked
Asked Answered
E

11

88

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?

Edwinaedwine answered 20/4, 2017 at 7:53 Comment(1)
relevant: github.com/angular/angular/issues/6005#issuecomment-165905348Precondemn
M
120

This error occur because you are 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

Macguiness answered 20/4, 2017 at 8:18 Comment(3)
This works for me. In my ngAfterViewChecked method I only have this.cdRef.detectChanges();.Razo
Same as @Razo it worked for me too with only this.cdRef.detectChanges(); in the ngAfterViewCheckedPhonemic
I still don't understand this .... if angular sees the model was changed, why does it not just update the view then instead of throwing an error?Abdominous
L
29

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/

Lau answered 15/11, 2019 at 7:2 Comment(1)
Only problem is ngAfterContentChecked is run after every ngDoCheck, meaning it will run like hundreds of time within a seconds and may make page rendering slow. See if you can solve the error by calling "this.changeDetector.detectChanges()" within ngAfterViewInitTrig
S
23

implement AfterContentChecked method.

constructor(
    private cdr: ChangeDetectorRef,
) {}

ngAfterContentChecked(): void {
   this.cdr.detectChanges();
}  
Stimulant answered 7/6, 2021 at 10:14 Comment(1)
this one did it for me <3Tallula
I
19

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

Indetermination answered 15/4, 2019 at 19:10 Comment(0)
I
8

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
})
Immature answered 12/2, 2021 at 17:47 Comment(2)
Dude...you save my day!!Solita
@Solita Happy to save 😊Immature
D
6

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.

Dimension answered 6/2, 2020 at 6:11 Comment(1)
Note for me: I was calling an async function to get the data (from ngoninit) but was not awaiting said functionWhitechapel
L
3

This is for Angular version 9+:

This error also occurs when using @ViewChild('templateRefVar') xyz!: TemplateRef. The reason is, that the reference obviously is undefind until the view is ready, causing this error when the value actually changes to the template reference.

If you know your template reference is there because, you have e.g.: xyz.html:

...
<ng-template #templateRefVar>
  ...
</ng-template>
...

You can declare it as static like so: @ViewChild('templateRefVar', {static: true}) xyz!: TemplateRef.

"This option was introduced to support creating embedded views on the fly." - angular.io guide

See for further reading on how to:

  • choose which static flag value to use: true or false see here.
  • understand when to use {static: true} see here.
Lioness answered 5/7, 2022 at 15:8 Comment(1)
I can't thank you enough!!! I had the issue with the @ViewChild(), tried the ngAfterContentChecked() hack but was not convinced, it just slowed down the app. Your solution is the proper way to resolve the error. Thank you again.Arvizu
G
1

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

Ghetto answered 15/6, 2020 at 18:31 Comment(0)
B
0

if you are using BehaviorSubject for sharing the value between components:

component.ts:

import { Observable } from 'rxjs/Observable';
import {tap, map, delay} from 'rxjs/operators';

private _user = new BehaviorSubject<any>(null);
user$ = this._user.asObservable();

Observable.of('response').pipe(
            tap(() =>this._user.next('yourValue'),
            delay(0),
            map(() => 'result')
          );

component.html:

<login *ngIf="!(dataService.user$ | async); else mainComponent"></login>
Balikpapan answered 8/1, 2020 at 4:57 Comment(0)
H
0

I received this error because I was opening up a Ngbmodal popup on load which included the object being changed after it was checked. I resolved this issue by calling the modal open function inside of setTimeout.

setTimeout(() => {
  this.modalReference = this.modalService.open(this.modal, { size: "lg" });
});
Headmaster answered 4/3, 2021 at 15:52 Comment(0)
G
0

Angular change detection Process is Synchronous, to avoid this error we can make this as async process, and we can make that code to run outside of Change Detection by doing something like. we can put this snippet inside onInit or Constructor method.

this.ngZone.runOutsideAngular(() => {    
     this.interval = window.setInterval(() => {        

         //logic which we want to handle

     }, 1)});
Gilbertogilbertson answered 1/5, 2021 at 6:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.