Excessive recursive template causing call stack overflow in tree

By utilizing this particular gist, I am able to effortlessly showcase a tree structure.

https://i.sstatic.net/yUNyw.png

The aspect I aim to alter is how the first level is presented, as illustrated below:

https://i.sstatic.net/Wg7JG.png

Despite attempting various adjustments, I continuously encounter a call stack limit exceeding issue. Here's an example of this scenario:

<h1>Angular 2 Recursive List</h1>
<ul>

    <li *ngFor="let item of list">
      {{item.title}} - LEVEL 0
      <ul *ngIf="item.children.length > 0">

        <ng-template #recursiveList let-list>
          <li *ngFor="let child of item.children">
            {{child.title}}
            <ul *ngIf="child.children.length > 0">
              <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: child.children }"></ng-container>
            </ul>
          </li>
        </ng-template>
        <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: child }"></ng-container>


      </ul>
    </li>
</ul>

Error:

preview-d2335ca5bdb955611c1cb.js:1 ERROR RangeError: Maximum call stack size exceeded
    at NgForOf.ngDoCheck (ng_for_of.ts:212)
    at checkAndUpdateDirectiveInline (provider.ts:215)
    at checkAndUpdateNodeInline (view.ts:429)
    at checkAndUpdateNode (view.ts:389)
    at debugCheckAndUpdateNode (services.ts:431)
    at debugCheckDirectivesFn (services.ts:392)
    at Object.eval [as updateDirectives] (AppComponent.html:9)
    at Object.debugUpdateDirectives [as updateDirectives] (services.ts:386)
    at checkAndUpdateView (view.ts:359)
    at callViewAction (view.ts:615)

Explore Stackblitz here

Answer №1

In an effort to streamline the process, I made a decision to simplify things.

I devised a dedicated list-item component to easily identify any mistakes.

list-item.component.ts

@Input() title: string;
@Input() children: any[];
@Input('index') levelOfNesting = 0;

list-item.component.html

<p [ngStyle]="{ 'margin-left': levelOfNesting + 'rem' }>
{{ title }}
</p>

<ng-container *ngIf="children.length">
<app-list-item
*ngFor="let item of children"
[children]="item.children"
[title]="item.title"
[index]="levelOfNesting + 1"
></app-list-item>
</ng-container>

Lastly, here is your list container:

<ul>
<app-list-item 
*ngFor="let item of list"
[title]="item.title"
[children]="item.children"
></app-list-item>
</ul>

Check out StackBlitz for more details.

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

Is it possible to implement websockets with inversify-express-utils?

We are attempting to integrate websockets into our typescript application built on inversify-express-utils, but so far we have had no success: import 'reflect-metadata'; import {interfaces, InversifyExpressServer, TYPE} from 'inversify-expr ...

The error "modules[moduleId] is undefined" occurs when running `ng build --watch

Currently, I am experimenting with the ng build --watch feature in Angular to make changes to my views without manually rebuilding each time. Although I encountered no errors when initiating it, upon accessing my website, I faced different console errors ...

Execution issue with Typescript function

In my Nativescript project, I have the following TypeScript file: import { Observable } from 'tns-core-modules/data/observable'; import { isIOS } from "tns-core-modules/platform"; import { Color } from "tns-core-modules/color"; import { request, ...

There is an issue with the type candidate in the Notion API, resulting in

In this instance, the troublesome code causing issues is displayed below: import {Client, LogLevel} from "@notionhq/client"; const notion = new Client({ auth: process.env.NOTION_TOKEN, logLevel: process.env.NODE_ENV !== 'product ...

What is the best way to run tests on this method using Jest?

import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns"; export class DateService { public getDaysInMonth(month?: Date) { return getDaysInMonth(month || new Date()); } What is the best way to test this func ...

Is it a commonly recommended method to nest fxLayout containers?

Recently, I ventured into using Angular Flex for the first time and I find myself a bit unsure about the nesting of layout containers. The issue arises when dealing with a navigation tag that triggers an angular-material sidenav opening to the left, pushin ...

Issues arise when attempting to extract data from a data provider using JSON within the context of the Ionic framework

Hey there! I'm relatively new to the world of Angular and Ionic, and I've embarked on a project to create a pokedex app. My approach involves using a JSON file containing an array of "pocket monsters". However, my current challenge lies in extrac ...

put two elements next to each other in a single row

This specific section contains an image positioned at the top, followed by two other components (within <ItemsContainer/>) at the bottom which display as separate rows. I am trying to place these two items (a grid and a chart) side by side within the ...

Is there a way to specifically call the last promise in a loop?

I'm new to promises and could use some help. I have a situation where promises are resolving randomly, how can I ensure that the last promise in the loop is resolved after the full loop executes? For example, if this.selectedValues has 4 values, som ...

CAUTION: cleaning unsecure style value background-color

Incorporating Angular, I am retrieving data from Firebase to enable user chat messages to display in a color chosen by the user, specifically using item.color. However, encountering an issue where for a user who selects blue as their color, a warning messa ...

Error in Template Syntax for External Pug Templates: Component template must have a root element, not just plain text

I've been struggling to make Pug templates work with Vue class-based components using a separate file for the pug template. The documentation suggests that adding this code should do the trick: // webpack.config.js -> module.rules { test: /&bsol ...

Discovering and Implementing Background Color Adjustments for Recently Modified or Added Rows with Errors or Blank Cells in a dx-data-grid

What is the process for detecting and applying background color changes to the most recently added or edited row in a dx-data-grid for Angular TS if incorrect data is entered in a cell or if there are empty cells? <dx-data-grid [dataSource]="data ...

When I try to pass a formControl to a child component in Angular, it throws a "no value

What could be causing the error message "no value accessor for form control with unspecified name" to appear? I am working with the edit-component: Here is the code in HTML: <mat-form-field> <input [formControl]="formControl"> </mat-f ...

Outputting data stored in Firestore object

Is there a way to display the content of a Firestore object in Angular Firebase? I am working on a project where I need to retrieve and print the name of a document stored in Firestore. In my Firestore database, I have a parent collection called "nforms" w ...

Tips for configuring the cookie expiration date using the ngx-cookie-service library

Can anyone offer assistance with setting the expire date for cookies in my Angular 5 app using ngx-cookie-service? Here is what I have tried: setCookies($event){ this.cookieService.set( 'retailAppCookies', "true", 30 ); this.cook ...

When restarting the React application, CSS styles disappear from the page

While developing my React application, I encountered a problem with the CSS styling of the Select component from Material UI. Specifically, when I attempt to remove padding from the Select component, the padding is successfully removed. However, upon refre ...

A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form formKeyValues https://i.stack.imgur.com/nRfiu.png form https://i.stack.imgur.com/eDpid.png I am looking to extract only the keys and values from formKeyValues and place them in ...

A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation: interface Time { hours: number; minutes: numbe ...

The base class is invoking a function from its child class

There are two classes, a base class and a derived one, each with an init function. When constructing the derived class, it should: Call its base constructor which: 1.1. Calls its init function Call its own (derived) init function. The issue is that ...

Executing a function when a user chooses to exit a webpage using the @HostListener('window:beforeunload') method

Utilizing @HostListener('window:beforeunload') allows me to detect when a user navigates away from the page, prompting a dialog window to open. I wish for an event to be triggered or a method to be executed if the user chooses to leave the page. ...