Search code examples
angulardevopsproduction-environment

ExpressionChangedAfterItHasBeenCheckedError in Production


Version Details

  • Angular Version: 7.3.7

I read about this error and found out that this cannot get in the Production but I am getting ExpressionChangedAfterItHasBeenCheckedError in Production Environment.

Error Message:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value:'ng-valid: true'. Current value: 'ng-valid: false'.

Configuration in Angular.json:

"qa": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.qa.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "serviceWorker": true
            },

Script for building

node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng build --prod --configuration=qa

Question:

My question is How am I getting this error in production and how can I fix it?

Updated

I just noticed this line Angular is running in the development mode. Call enableProdMode() to enable the production mode.

Question:

So i am running this script for building what else I need to do to enable production? node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng build --prod --configuration=qa

Image of error in browser:

img

Image of environment

img


Solution

  • Main.ts should contain the following contents:

    import { enableProdMode } from '@angular/core';
    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    
    import { AppModule } from './app/app.module';
    import { environment } from './environments/environment';
    
    if (environment.production) {
      enableProdMode();
    }
    
    platformBrowserDynamic().bootstrapModule(AppModule)
      .catch(err => console.log(err));
    

    So, two things need to be true. This needs to exist above in main.ts, and your environment.qa.ts file must have production = true. After verifying this, set a breakpoint here to ensure the values are what you think they are.

    Additional Thought

    You didn't ask, but I'm going to offer it anyway - you need to fix the error. The presence of the ExpressionChanged... error indicates a problem with your application logic - most likely, you are manipulating a variable inside one of the lifecycle hooks (e.g. AfterContentInit). This is unlikely to have a noticeable effect, but you could encounter some strange bugs as a result of this error.