简体   繁体   中英

Angular Error: ExpressionChangedAfterItHasBeenCheckedError

I have a little problem with Angular 4. The error below is thrown

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '225px'. Current value: '-21150px'.

Here's my html:

<div class="channelRow" *ngFor="let epgChannel of channelGroupEpg?.epgChannels">
    <div class="epgChannelList">
      {{epgChannel.channel.name}}
    </div>
    <template ngFor let-epgDate [ngForOf]="epgChannel.dates">
        <div class="epgEntry" 
          *ngFor="let epgProgram of epgDate.programs" 
          [style.width]="getWidth(epgProgram, epgDate.date)" 
          (click)="selectProgram(epgProgram)" 
          data-toggle="modal" 
          data-target="#detailModal">
            {{epgProgram.title}}
        </div>
    </template>
</div>

And this is where the error comes from:

getWidth(program: EPGProgram, date: Date) {
  let min = this.helperService.getDurationByProgramInMinutes(program);
  let startDate = new Date(program.start.getFullYear(), program.start.getMonth(), program.start.getDate(), 0, 0, 0, 0);
  let stopDate = new Date(program.stop.getFullYear(), program.stop.getMonth(), program.stop.getDate(), 0, 0, 0, 0);
  if (startDate.getTime() !== date.getTime()) {
      let minNextDay = this.helperService.getMinutesToNextDay(program.start, date);
      min = min - minNextDay;
  } 
  if (stopDate.getTime() !== date.getTime()) {
      let minNextDay = this.helperService.getMinutesToLastDay(program.stop, date);
      min = min - minNextDay;
  }
  let width = min * 5;
  return width.toString() + 'px';
}

Can someone tell me, why this is the case?

Component state was changed after it was checked ...

use

this._changeDetectionRef.detectChanges();

at the end of your method, not forgetting to add

private _changeDetectionRef : ChangeDetectorRef

as parameter of the constructor of the Component owning your method.

See discution here

This error occurs because you are changing the variable before the angular ouput the HTML. So, what you can do is. change your variable when the content is loaded. solution.

import { AfterContentInit } from '@angular/core';

ngAfterContentInit(){
   // write your code here
}

快速解决方法是将代码放在setTimeout()中。

I had same error outputed. After long research I found out that it's caused when the data that are inputted to html template has changed before angular refresh the html. This error won't be displayed when you switch to production mode. See this issue for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM