Passing a variable from one child component to another triggers an ExpressionChangedAfterItHasBeenCheckedError in Angular

My situation involves passing information to two children components.

parent.component.html

<childA [loading]="loading">
    <childB (loadingChanged)="loadingChangedHandler($event)"></childB>
</childA>

parent.component.ts

loading = false;
constructor(){
   ......
}
loadingChangedHandler(loadingChild: boolean){
    this.loading = loadingChild;
  }

childB.component.ts (sending a variable to parent, which then goes to child A)

....
@Output() loadingChanged: EventEmitter<boolean> = new EventEmitter();
....
loadData() {
    this.loadingChanged.emit(true);
      this.service.readDate()
        .subscribe((data: any) => {
            ........
            this.loadingChanged.emit(false);
        })

  }

Lastly, in the childA component, I need to receive the variable and perform operations

childA.component.ts

@Input() loading: boolean = false
constructor() {
....}
....

In child A, I have a loading spinner that works fine, but I am encountering an error in the console:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'loading: false'. Current value: 'loading: true'.

How can I resolve this issue? I have looked into documentation (ngAfterViewInit) but I am struggling to understand why it's not working in my case.

Answer №1

When Angular detects changes in values passed to a child component, it triggers the ExpressionChangedAfterItHasBeenCheckedError. Learn more about this error here

To resolve this issue, you can utilize the AfterContentChecked life cycle hook in childA.component.ts

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

  constructor(
  private cdref: ChangeDetectorRef) { }

  ngAfterContentChecked() {

    this.cdref.detectChanges();

  }

Answer №2

Important Note: When Angular is in development mode, it performs change detection twice.

During the first change detection phase, Angular detects a change in the loading property of the parent component. In the subsequent cycle, it detects another change in the loading property triggered by the child component. This causes an exception because the loading property was modified after it was already checked in the initial cycle.

Unlike in production mode where change detection only occurs once, using development mode helps us identify such errors early on to avoid data-view inconsistencies.

By placing the code that updates the loading property within a setTimeout function, it ensures that the code executes in the next tick once the previous change detection is completed.

For example, try triggering this.loadingChanged.emit(false); within setTimeout with a delay of 0 milliseconds:

setTimeout(() => {
  this.loadingChanged.emit(false);
}, 0);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unique styling implementation for element situated underneath Angular 6 router-outlet

I'm currently working on implementing router transitions in my Angular application, and I've encountered an unusual problem. The styling for the router-outlet element is being applied to the element that comes after it in the DOM hierarchy. Here ...

Leverage the power of TypeScript custom transformer and project reference for enhanced

I am currently working on a project that involves using both project references and custom transformers. The issue I am facing is that project references require the use of TSC for incremental compilation, but when TSC is used, the transformers are not app ...

Having trouble with Angular 5's Post function?

Having some trouble with my Angular 5 application and API calls. For some reason, when I add headers to the request, the browser is not recognizing them properly and showing 'OPTION' instead of the actual headers. This is resulting in a 403 respo ...

During the process of adding a new template to my Angular project, I came across an issue within the core.min.js and script.js files

index.html <html class="wide wow-animation" lang="en"> <body> <app-root></app-root> <!-- Javascript--> <script src="assets/js/core.min.js"></script> <script src="assets/js/script.js"></script& ...

Why isn't my Bootstrap affecting Angular?

Hello, I am currently working on a project using Angular. Recently, I installed Bootstrap and added it to angular.json, but unfortunately, the changes did not take effect even after restarting the app. Here is the code snippet that I am currently using: h ...

Trigger parent Component property change from Child Component in Angular2 (akin to $emit in AngularJS)

As I delve into teaching myself Angular2, I've encountered a practical issue that would have been easy to solve with AngularJS. Currently, I'm scouring examples to find a solution with Angular2. Within my top-level component named App, there&apos ...

Are there any methods to incorporate Facebook and Google login into an Ionic progressive web app (PWA)?

After successfully developing an app in Ionic 3 for Android and iOS, I encountered a problem when adding the browser platform. The Facebook and Google login features were not functioning as expected. Despite the assurance from Ionic documentation that the ...

Utilize the power of Wikitude within an Angular 2 application

I am currently working on integrating Wikitude Architect View in Angular 2 by referring to the code at this link. My goal is to implement this code in an Angular 2 compatible way. import * as app from 'application'; import * as platform from & ...

Include a log out option in the side menu of the ionic2 application

I am working with the sidemenu template to kick off my application. I aim to incorporate a button within the sidemenu that enables users to trigger a modal alert for confirming logout. Below is the code snippet: app.component.ts: import { Component, View ...

There seems to be an issue with transitioning the React.js page

I'm currently working on managing the page with react-hook, react-router-dom, and redux. The login functionality has been implemented, and I've written the code to redirect to the main page upon successful login. To achieve this, I utilized hi ...

Keeping track of important dates is ineffective using the calendar

I am facing an issue with developing a calendar that marks events on the correct dates. I am receiving the dates in the following format in PHP [ { "status": "OK", "statusCode": 200, "statusMensagem": & ...

Best practices for organizing API Services using TypeScript and Next.js Server Actions

My product-actions/index file contains various server actions such as createProduct and getProductAssets, each of which verifies the user session before processing the request. I am looking for a way to check the session validity only once and then procee ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

Is there a way to toggle the visibility of the angular material toolbar at regular intervals?

I'm currently experimenting with the CSS animation feature to display and conceal the angular material toolbar in this demonstration. Inside the application component, the hide attribute is toggled at intervals as shown below: hide:boolean = false ...

Resolve the Angular proxy issue with the backend

Attempting to troubleshoot a similar problem, but struggling to understand why it's not functioning correctly. The API I am working with is located at: localhost:8080/api/acl/authorize Here is the HTTP client code: const AUTH_URI = "/api/acl/&q ...

Struggling to modify a string within my React component when the state is updated

Having a string representing my file name passed to the react-csv CSVLink<> component, I initially define it as "my-data.csv". When trying to update it with data from an axios request, I realize I may not fully understand how these react components w ...

Navigating the correct way to filter JSON data using HttpClient in Angular 4

Struggling with transitioning from Http to HttpClient, here's the code in question: constructor(public navCtrl: NavController, public http: HttpClient, private alertCtrl: AlertController) { this.http.get('http://example.com/date.php') .su ...

angular2 : problem encountered with communication to rest api

Transitioning from PHP to Angular2 has been quite challenging for me, especially when trying to use a real rest API like "Tour of Heroes". I initially thought it would be simple... Currently, I have set up a functional API with Express: curl -XGET http:/ ...

The Tailwind CSS Chrome extension is causing disruptions on the websites I view

Currently, I am in the process of creating a chrome extension using various tools like React, Typescript, TailwindCSS, and a custom Webpack configuration. To enhance user experience, I have modified the default action in manifest.json so that clicking on t ...

"Manipulating values in an array with a union type: a guide to setting and

I am currently working on creating an array that can have two different value types: type Loading = { loading: true } type Loaded = { loading: false, date: string, value: number, } type Items = Loading | Loaded const items: Items[] = ...