Search code examples
angularangular2-pipe

Angular 2 - Date pipe exception: Expression has changed after it was checked


I am using the DatePipe inside my component to transform timestamp into readable expression. But once the document is loaded i get the exception:

EXCEPTION: Error in http://localhost:3000/app/interest/user-interest.component.html:15:15 caused by: Expression has changed after it was checked. Previous value: '6 бер. 2017'. Current value: '5 бер. 2017'.

Can anyone ,please ,explain me what is going on here. Here is the basic code:

user-interest.component.html

<p md-line>{{getFolderLastLearningSessionDate(folder.learningSessions)}}</p>

user-interest.component.ts

getFolderLastLearningSessionDate(sessions:Array<LearningSession>):string {
    if (sessions)
      try {
        return this.learningSessionService.getLearningSessionDate(this.learningSessionService.getLastLearningSession(sessions));
      } catch (ex) {
        console.log(ex);
      }
    else return "Folder have not bean studied yet";
  }

learning-sessions.service.ts

public getLearningSessionDate(session:LearningSession):string {
    let datePipe = new DatePipe("uk-UA");
    return datePipe.transform(session.sessionDate);
  }
public getLastLearningSession(sessions:Array<LearningSession>):LearningSession {
    if (sessions) {
      return sessions.sort(
        (session1:LearningSession, session2:LearningSession) => {
          return session2.sessionDate.getDate() - session1.sessionDate.getDate();
        }).shift();
    }
    else
      throw new Error("folder is not studied yet");
  }

Solution

  • This error is thrown when change detection causes a change in the model.

    In devMode Angular does an additional change detection turn after the first one and checks if the model changed between the first and second turn. If it did, then you get the error message you mentioned.

    In your case this is probably caused by binding to a method that returns different values on subsequent calls

    {{getFolderLastLearningSessionDate(folder.learningSessions)}}
    

    Binding to methods is problematic, especially if subsequent calls can return different values (different object instances with the same properties and same property values are considered different).

    It is therefore better to register some event handler and update a class-field in such an event handler and bind to the class-field instead.