Search code examples
javascriptangularangular-lifecycle-hookschange-detector-ref

I got ExpressionChangedAfterItHasBeenCheckedError from child compoenent (timerrenderer), Angular 7


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;
      }
    }

Solution

  • 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