0

I'm getting the ExpressionChangedAfterItHasBeenCheckedError error from my child component. I tried to add detectChanges() method inside the ngOnchanges but it didn't work. I'm new to angular. I also tried the other questions' solutions but didn't work for me.

      ngOnInit() {
        if (this.IsInGrid === false) {
          this.duration = this.Duration * 60 * 60 * 1000;
          this.startDate = this.StartDate;
          this.timerText();
          this.init(null);
        }
      }
      ngOnChanges() {
        this.changeDetector.detectChanges();
      }
      ngAfterViewChecked() {
        this.changeDetector.detectChanges();
      }
    
      agInit(params: any): void {
        this.params = params;
        this.init(params);
      }
    
      init(params: any) {
    
      }
    
      timerText(): string {
        if (this.StartDate == null) {
          return "";
        }
        this.elapsed = new Date().getTime() - this.StartDate.getTime();
        if (this.elapsed > this.duration) {
          this.isPassed = true;
        }
    
        return this.msToTime(this.elapsed);
      }
    
      msToTime(ms, delim = ' : ') {
        const showWith0 = value => (value < 10 ? `0${value}` : value);
        const days = Math.floor((ms / (1000.0 * 60 * 60 * 24)));
        const hours = showWith0(Math.floor((ms / (1000.0 * 60 * 60)) % 24));
        const minutes = showWith0(Math.floor((ms / (1000.0 * 60)) % 60));
    
        if (days > 0)
          return `${days}d ${hours}h ${minutes}m`;
        if (hours > 0)
          return `${hours}h ${minutes}m`;
        return `${minutes} minutes`;
      }
    
      refresh(params: any): boolean {
        return true;
      }
    }
4

2 回答 2

2

I added changeDetection: ChangeDetectionStrategy.OnPush to my component and it seems worked for me. I found the correct explanation for my solution .

The source:

https://medium.com/@bencabanes/angular-change-detection-strategy-an-introduction-819aaa7204e7

于 2021-01-08T12:45:16.167 回答
1

Its a bit of black art debugging these errors. Whilst I can't comment on your code I can give you some pointers that helped me get rid of them.

From what I can fathom, this message is shown when a property is updated after an initial value is set and checked.

First thing is, experiment setting these value using the Angular Lifecycle hooks https://angular.io/guide/lifecycle-hooks, specifically ngAfterViewInit(). You may get a performance hit using ngOnChanges().

ExpressionChangedAfterItHasBeenCheckedError Explained

于 2021-01-07T09:35:06.367 回答