Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angular - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...