Encountering an error of ExpressionChangedAfterItHasBeenCheckedError while trying to refresh the

I'm encountering an issue that I need help with:

https://i.stack.imgur.com/4M54x.png

whenever I attempt to update the view using *ngIf to toggle on an icon display.

This is what my .ts file looks like:

@Component({
    selector: 'app-orders',
    templateUrl: './orders.component.html',
    styleUrls: ['./orders.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class OrdersComponent implements OnInit, OnDestroy {

    loadedPendingOrders: Order[] = [];
    loadedProcessedOrders: Order[] = [];
    loadedDeliveredOrders: Order[] = [];
    loadedCancelledOrders: Order[] = [];
    pendingOrderTimelines: string[] = [];
    deliveredOrderTimelines: string[] = [];
    cancelledOrderTimelines: string[] = [];
    isDeliverySlotsActive: boolean;
    searchTerm: string;
    newOrderStatus: string;
    private subscription: Subscription;

    constructor(private ordersService: OrdersManagerService, private shopPreferencesService: ShopManagerService, private apiManager: ApiManagerService) {}

    ngOnInit(): void {
        this.subscription = timer(0, 5000).pipe(
            switchMap(() => this.apiManager.fetchShopOrders())
            ).subscribe(orders => {
                this.isDeliverySlotsActive = this.shopPreferencesService.isDeliverySlotsActive();
                const loadedOrders: OrdersList = orders;
                /* do something with orders */
        });
    }

    onNewOrderAdded(status: string){
        this.newOrderStatus = status;
    }
    ....
}

And here is my .html file:

<div id="tab-group">
    <mat-tab-group dynamicHeight animationDuration="400ms">
        <mat-tab>
            <ng-template mat-tab-label>
                <span>Pending</span>
                <img src="../../assets/my-orders/blue-tiny.svg" *ngIf="newOrderStatus == 'PENDING'">
            </ng-template>
            <app-orders-list
                [orders]="loadedPendingOrders"
                [timelines]="pendingOrderTimelines"
                [isDeliverySlotsActive]="isDeliverySlotsActive"
                [searchTerm]="searchTerm"
                (newOrderStatus)="onNewOrderAdded($event)"
            ></app-orders-list>
            ...
        </mat-tab>
    </mat-tab-group>
</div>

Although the view updates correctly, the error persists. Any ideas why?

Appreciate any assistance.

Answer №1

The reason for this behavior is due to the modification of newOrderStatus before the component lifecycle has finished. Initially, the value is set to undefined, then it gets updated in the child component and returns a new value back to the parent.

In Angular applications, this pattern is often considered a bad practice. The child component should not be responsible for dictating the parent's state, as the parent should manage its own state.

Here is an example illustrating this issue. The parent component passes a value to the child component, which then determines a string value, emits it back, and the parent uses it to decide which div to display. You can see the error

ExpressionChangedAfterItHasBeenCheckedError
in the console.

To resolve this problem, I suggest separating your state management and computation (such as status, orders, etc.) from your components (Orders and OrdersList components). Creating a service with functions to handle state manipulation and an observable for components to subscribe to would be a good approach.

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

Establishing a Recyclable Testing Rendering Method in redux toolkit version 2

In the era of Redux Toolkit v2, a noticeable change occurred with the absence of the EmptyObject type and the unavailability of the PreloadedState type in the @reduxjs/toolkit package. This has led to a requirement of defining all reducers inside the pre ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

Encountering "token_not_provided" error message on all GET routes in Laravel 5.3 with JWT authentication

I'm currently working on implementing authentication using Laravel 5.3 and Angular 2 with JWT. The authentication part is functioning properly, and I am able to successfully obtain the token. However, when attempting to navigate to any GET routes, an ...

Alerts created with the AlertController in Ionic 4 Angular are not displaying the message when the

After creating a reliable alert service for my Ionic 4 project, I encountered an issue when building the release version of the app. Despite functioning perfectly in other environments like "ionic serve" and "ionic cordova emulate", the message part of the ...

Utilizing the React TypeScript useContext hook with useReducer for state management

I'm struggling to identify the type error present in this code snippet import React from 'react'; interface IMenu { items: { title: string, active: boolean, label: string }[] } type Action = | { type: 'SET_ACTIVE&a ...

What is the best way to display suggested words from a given list of options?

Looking for a way to provide suggestions to users based on a list of words they enter in TypeScript while maintaining performance. How can this be achieved efficiently? ...

What is the method for accessing an anonymous function within a JavaScript Object?

Currently facing an issue with a Node.js package called Telegraf, which is a bot framework. The problem arises when trying to create typings for it in TypeScript. The package exports the following: module.exports = Object.assign(Telegraf, { Composer, ...

Is there a suitable alternative that supports TypeScript, particularly with Angular 6, as D3Js does not directly support TypeScript?

I am currently engaged in a new project focusing on HR Analytics, utilizing Python, R, MySQL, and Angular 6 for the front end user interface. In terms of Data Visualization, I am exploring the use of D3js. However, it is important to note that D3Js does no ...

Mapping JSON to interface in Angular 7: A step-by-step guide

I am currently working with angular7 and I have a requirement to map a json object to my interface. My goal is to create a function that can accurately map the fields of the json object to the corresponding properties in the interface. Additionally, if the ...

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...

Azure Static Web App does not retrieve the connection string value from environment.prod.ts

After deploying my Angular App to Azure as a Static Web App, everything seemed to be running smoothly. However, I encountered an issue with the file "environment.prod.ts" in the environments folder within my app that contains the following code: export co ...

Angular's Mysterious Pipe

When navigating to the indice page, I want to adjust the number formatting in the cours column to display two decimal places. For instance: 11345.654589 should be displayed as 11345.65. https://i.stack.imgur.com/tjvWb.png To achieve this, I have created ...

Encountering build issues with Next.js on Vercel and local environments

As I work on my first Next.js website, I encountered a build error that persists both locally and on Vercel. Interestingly, I managed to achieve a successful local build at one point, but it no longer works. Here is an excerpt from my package.json: ...

Link a YAML file with interfaces in JavaScript

I'm currently learning JavaScript and need to convert a YAML file to an Interface in JavaScript. Here is an example of the YAML file: - provider_name: SEA-AD consortiumn_name: SEA-AD defaults: thumbnail Donors: - id: "https://portal.brain ...

What is the best way to execute a function that retrieves data from a MySQL query and then sends it back as a result in Express.js?

How can I refactor my code to efficiently call a function that returns the result of a MySQL query and send it back in an Express.js response? I am attempting to streamline my SQL queries by exporting them into individual functions to eliminate duplicatio ...

Determine characteristics of object given to class constructor (typescript)

My current scenario involves the following code: abstract class A { obj; constructor(obj:{[index:string]:number}) { this.obj = obj; } } class B extends A { constructor() { super({i:0}) } method() { //I wan ...

Using redux action in the onPaginationChange function instead of setPaginationState in the given example for the TanStack table - is there a way to

Provided this sample Is there a way to utilize by dispatching a redux action rather than using useState - setPaginationState? onPaginationChange: state => dispatch(browseItemModalActions.setPagination(state)) An error is appearing in the console: ...

Using *ngFor to show subcategories within parent categories based on a condition

Trying to implement a feature to display subcategories under categories using JSON response in an angular 2 application. Utilizing ngIf to filter subcategories based on the parent_id field in the JSON string. JSON Data: [ { "id": "15", "parent_ ...

Unable to inject basic service into component

Despite all my efforts, I am struggling to inject a simple service into an Angular2 component. Everything is transpiling correctly, but I keep encountering this error: EXCEPTION: TypeError: Cannot read property 'getSurveyItem' of undefined Even ...

Refreshing the page does not trigger Angular callHooks

Encountering an issue with the proper invocation of F5 button or directive call URL from the address bar resulting in ngOnInit not being triggered correctly. Using a debugger to analyze the situation, it was noticed that callHook is not initiated after ngO ...