ngIf - Expression has changed after it was checked

后端 未结 6 1505
误落风尘
误落风尘 2021-02-01 12:37

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,

6条回答
  •  天涯浪人
    2021-02-01 13:13

    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

提交回复
热议问题