Using ng-template in ContentChildren causes the component to throw an ExpressionChangedAfterItHasBeenCheckedError

I've encountered the

ExpressionChangedAfterItHasBeenCheckedError
error while working on an Angular project, and this time I'm stuck on how to resolve it.

The component I'm dealing with has child components utilizing @ContentChild and @ContentChildren. These child components contain a list of children that are rendered using *ngTemplateOutlet.

To illustrate this issue, I've created a scenario based on a TableComponent with a HeaderComponent containing multiple HeaderItemComponent elements, along with a QueryList of RowItem.

To see the error firsthand, you can check out the full code on StackBlitz:

https://stackblitz.com/edit/angular-6ieqh7

What puzzles me is that the error only occurs when the header is present in the table structure, even though the header items are rendered in a similar fashion to the rows.

Error occurs:

<table>
  <table-header>
    <table-header-item>Id</table-header-item>
    <table-header-item>Name</table-header-item>
    <table-header-item>Status</table-header-item>
  </table-header>

  <table-row *ngFor="let row of tableData">
    <table-row-item>{{ row.id }}</table-row-item>
    <table-row-item>{{ row.name }}</table-row-item>
    <table-row-item>{{ row.status }}</table-row-item>
  </table-row>
</table>

No errors:

<table>
  <table-row *ngFor="let row of tableData">
    <table-row-item>{{ row.id }}</table-row-item>
    <table-row-item>{{ row.name }}</table-row-item>
    <table-row-item>{{ row.status }}</table-row-item>
  </table-row>
</table>

The error message points to line 2 of header.component.html:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngTemplateOutlet: undefined'. Current value: 'ngTemplateOutlet: [object Object]'.

Answer №1

To resolve the error, you can rectify it by enclosing your headers item within setTimeOut

To learn more about this issue, visit:

ngAfterContentInit(): void {
    setTimeout(()=>{
         this.headerItems = this.inputHeaderItems.toArray();
        this.inputHeaderItems.changes.subscribe((value: QueryList<HeaderItemComponent>) => {
          this.headerItems = value.toArray();
          this.cdr.detectChanges();
        });
      })

      }

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

What is the correct way to specify the data type for the useState hook when I intend to store an array of objects?

My dilemma involves storing an array of objects using the useState hook, but I am struggling with the syntax required to describe the expected type. The type that I want to store is Array<Updates>. Below is the code I have: const [messages, setMessa ...

Issue with data propagation in Angular 2 RC5 when using ngStyle in parent component

Here is a basic Angular 2 application setup I am working with: import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Test</h1> <test-component [Height] = "30 ...

Issue during Firebase production: emptyChildrenSingleton isn't recognized

In my nextjs project, I am using React v18.1.0 and Firebase Realtime Database for handling notifications. The notifications work fine in development mode but fail in the production environment. The errors I encountered are as follows: ReferenceError: empt ...

Verify the type of email domain (personal or corporate)

Here's an example: isPersonalEmail("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aea1ada580a7ada1a9aceea3afad">[email protected]</a>") // true isPersonalEmail("<a href="/cdn-cgi/l/email- ...

Retrieve the current step index in Angular Material Design Stepper

In my endeavors to retrieve the selected step within a component utilizing Angular Material Design stepper, I am encountering some issues. My current approach involves using the selectedIndex property, but it consistently returns "1" instead of the desire ...

Misunderstanding the concept of always being right

Here is a code snippet that raises an error in TypeScript: class Status { constructor(public content: string){} } class Visitor { private status: Status | undefined = undefined; visit(tree: Tree) { if (tree.value > 7) { this.status = new ...

Specify the key type when using the syntax "key in ObjectName"

I need assistance in setting the key type of an object. Here is what I have tried: type TypeSample = { [key: string]: string } In addition, I want to specify that the keys should come from an enum like this: enum EnumSample { 'ok' = &a ...

Can a constructor function be utilized as a parameter type in another function within TypeScript?

Recently, I came across TypeScript and after watching some video reviews, I see great potential in it. It seems to offer better code completion, implicit code documentation, and enhanced type safety for JavaScript. I'm currently in the process of con ...

Unable to start Angular application, encountering errors while running ng serve

The challenge at hand As I delve into a new project, I've successfully cloned the repository onto my local machine. After utilizing npm install to fetch the necessary packages, running ng serve triggers a series of errors. Despite the application fai ...

Incorporate an Array of Objects into the UseState hook with an initial value

I have encountered an issue with the following error message: "Error: Objects are not valid as a React child (found: object with keys {fzfvhv76576, user }). If you meant to render a collection of children, use an array instead." I have been attem ...

The elements on the webpage are spilling over with content

I encountered an issue while creating a dashboard with a sidebar on the left side. When adding content to the page, some of it ended up hidden behind the sidebar. I tried using overflow-x:auto and this was the result: https://i.stack.imgur.com/5qHJY.jpg Be ...

Layout your Angular components with a column design using Flex Layout

Is there a way to adjust the width of a child component in an fxLayout set to column? Take this example for reference: https://stackblitz.com/edit/angular-fxlayout-custom-breakpoints?file=app%2Ftest.component.ts In the provided example, there are three f ...

How can I display a sessionStorage string in an Angular 8 HTML view?

I'm looking to show the data stored in sessionStorage on my angular view. This is my current session storage: sessionStorage.getItem('username'); In my dashboard.ts file, I have: export class DashboardComponent implements OnInit { curr ...

Issue NG0203 encountered during material import attempt

I've been encountering an issue with importing material. Despite using code similar to the examples on material.angular.io, I keep running into the ""inject() must be called from an injection context..." error. My goal is to create a simple table ...

Challenges arise in communicating between parents and children in Angular 6

I seem to be encountering an issue with parent/child communication in Angular 6. The code appears to be functioning correctly, but I am running into an error in Karma. Here is the specific error message: Failed: Template parse errors: Can't bind to & ...

What is the best way to reorganize Discord channels based on numerical order when interacting with the application?

Whenever someone submits an application for the server, a designated channel is created at the top of the server (view example here). However, responding to these applications in a consistent order has proven challenging due to various factors. Once I resp ...

After a duration of 4 minutes, an ERR_EMPTY_RESPONSE is thrown in response to the

My angular 5 node app involves sending a request to the server and waiting for a response. There are instances where the response takes around 5-6 minutes to arrive. However, an ERR_EMPTY_RESPONSE error is triggered by the http method after just 4 minutes ...

What is the best way to arrange this script?

I am currently working on a Javascript script that automatically scrolls down and loads a new URL when it reaches the bottom of the page. However, I would like to add a delay of 30 seconds before the new URL is loaded. Although I am relatively new to Java ...

The plugin "proposal-numeric-separator" was not found. Please make sure that there is a corresponding entry for it in the ./available-plugins.js file

{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "myProjects", "projects": { "uniqueApp": { "projectType": "web-app", "schematics": {}, "root": "", "sourceRoot": "src", ...

Guide on stubbing Google gapi global variable in component tests with Karma

I am currently facing a challenge in setting up tests for a service in my Angular 4 project that utilizes Google gapi. The issue arises from the fact that the variable is globally declared but not mocked, leading to an error when running the tests: Refe ...