1

I'm currently working on an Angular 6 applicaiton. I try to call a method from an expression. Unfortunately it seems it doesn't work anymore.

The example is very simple and looks like that in my car.component.html:

<div>Car Name: {{ getCarName() }} </div>

In my component code car.component.ts, I implemented that function something like that:

getCarName() {
  return this.carName;
}

Actually I'm changing the property carName each time I hover over another div on my component UI.

Unfortunately I'm getting the following error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value...

Do you know how to solve this issue?

Thank you!!

1
  • 2
    you can put in your html <div>Car Name: {{ carName }} </div>, have you tried this? Commented May 17, 2018 at 16:27

1 Answer 1

3

ExpressionChangedAfterItHasBeenCheckedError means, that if you construct your logic this way, you have to detect changes manually inside your component:

import { Component, AfterViewChecked, ChangeDetectorRef } from '@angular/core';

/* Other stuff goes here */

export class PhoneVerifyComponent implements AfterViewChecked {
  constructor(private _changeDetectorRef: ChangeDetectorRef) { }

  ngAfterViewChecked() {
    /* This way the detector will run after every change */
    this._changeDetectorRef.detectChanges();
  }

  getCarName() {
    /* This way you run detector only on this function call */
    this._changeDetectorRef.detectChanges();
    return this.carName;
  }
}

You can choose every way you like, run detector in specific place, or after every change. If your goal is just to solve the issue only with this method, I recommend to run it on specific function call, but if you have many cases like that - better run it in ngAfterViewChecked.

BUT

The shortest way is to store the result of this function execution to class property and simply interpolate this property, instead of method:

<div>Car Name: {{ carName }}</div>

Anyway, we don't know your goals and what's going on in your real project, so you have to choose more proper way for your case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.