Is there a way to make an angular component reuse itself within its own code?

I am dealing with a parent and child component scenario where I need to pass data from the parent component to the child component. The aim is to display parentData.name in the child component when parentData.isFolder===false, and if parentData.isFolder===true, then reusing the child component until there are no more instances of parentData.isFolder===true.

However, my attempts have resulted in an error message:

Error: Maximum call stack size exceeded

Here's a StackBlitz example that I tried.

If this approach is incorrect, is there another way to achieve the desired outcome?

parent-component.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent-component',
  templateUrl: './parent-component.component.html',
  styleUrls: ['./parent-component.component.css'],
})
export class ParentComponentComponent implements OnInit {
  public parentData;
  constructor() {}

  ngOnInit() {
    this.parentData = [
      {
        name: 'Example file 1',
        isFolder: true,
        Id: '111',
      },
      {
        name: 'Example file 2',
        isFolder: false,
        Id: '222',
      },
      {
        name: 'Example file 3',
        isFolder: false,
        Id: '333',
      },
    ];
  }
}

parent-component.component.html

<ng-container *ngFor="let item of parentData">
  <app-child-component [parentData]="item"></app-child-component>
</ng-container>

child-component.component.ts

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-child-component',
  templateUrl: './child-component.component.html',
  styleUrls: ['./child-component.component.css'],
})
export class ChildComponentComponent implements OnInit {
  @Input() public parentData;

  constructor() {}

  ngOnInit() {}

}

child-component.component.html

<!-- Display names when isFolder === false -->

<ng-container *ngIf="parentData.isFolder === false">
  <ul>
    <li>{{ parentData.name }}</li>
  </ul>
</ng-container>

<!-- Reuse the app-child-component if isFolder === true -->
<ng-container *ngIf="parentData.isFolder === true">
  <app-child-component [parentData]="parentData"> </app-child-component>
</ng-container>

Answer №1

The reason you encountered the error "Error: Maximum call stack size exceeded" is due to not handling the parentData properly when it evaluates as true, causing an infinite recursion.

It seems like you are attempting to create a tree structure.

To address this issue, I made some modifications to your code:

  • parent.component.html - Modified the HTML to pass an array instead of just an object to the child component.
  • parent.component.ts - Added a subFolders array within the parentData to simulate subfolders for the tree UI. You can rename subFolders to parentData for clarity.
  • child.component.html - Restructured the HTML by iterating over the parentData array received from the parent component to display folder names. The child component calls itself recursively until isFolder property is false.
  • child.component.ts - No changes made here.

I also created a modified version on StackBlitz based on your initial project.

parent.component.ts

// Code for Parent Component
// Initialization and assignment of data

parent.component.html

<app-child-component [parentData]="parentData"></app-child-component>

child.component.ts

// Code for Child Component
// Input declaration and initialization

child.component.html

<ng-container *ngFor="let item of parentData">
  <ul>
    <li>{{ item.name }}</li>
    <app-child-component [parentData]="item.subFolders" *ngIf="item.subFolders"></app-child-component>
  </ul>
</ng-container>

Outcome:

https://i.stack.imgur.com/DwXSp.png

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 reason for TestBed using waitForAsync in beforeEach instead of directly using async/await to compileComponents?

UPDATE: I submitted a problem report to Angular and they have since made changes to the documentation: https://github.com/angular/angular/issues/39740 When working on Angular tests, it is common practice to set up the beforeEach method like this: befo ...

Spring Boot fails to recognize path variable data sent from Angular

When working with Angular 7, I encountered a situation where I needed to pass a value from the service class of Angular. Here is how I achieved it: executeHelloWorldBeanServiceWithPathVariable(name){ console.log("name coming from here"+name); retu ...

Developing Your Own Angular 2 Material Style Themes

Currently, I am delving into Angular 2 alongside Angular Material with the intention of crafting a unique theme to incorporate custom colors for components. Despite following the Angular documentation, I am facing difficulties in getting it up and running ...

Why is my root page not dynamic in Next.js 13?

I am currently working on a website using Next.js version 13.0. After running the next build command, I noticed that all pages are functioning properly except for the root page. The issue is that it's being generated as a static page instead of dynami ...

React Native is throwing an error message saying that the Component cannot be used as a JSX component. It mentions that the Type '{}' is not assignable to type 'ReactNode'

Recently, I initiated a new project and encountered errors while working with various packages such as React Native Reanimated and React Navigation Stack. Below is my package.json configuration: { "name": "foodmatch", "version ...

Issue encountered with express-jwt and express-graphql: TypeScript error TS2339 - The 'user' property is not found on the 'Request' type

Implementing express-jwt and graphql together in typescript has been a challenge for me. import * as express from 'express' import * as expressGraphql from 'express-graphql' import * as expressJwt from 'express-jwt' import s ...

Encountering a problem when attempting to utilize AngularFire's Cloud Messaging Angular module due to missing configuration values for the app

Working with Firebase Cloud Messaging in my Angular application using AngularFire2 has presented a challenge. I am facing an error when attempting to retrieve the user's current token. I have already set up the "firebase-messaging-sw.js" and "manifes ...

Exploring ways to list interface keys in order to create a new interface where the value is determined by the corresponding key

How can we iterate through interface keys to create a new interface where the value is dependent on the key? type IParse<T> = { [K in keyof T as K extends string ? K : never]: string // How can we specify that if K === 'a', the type sho ...

Tips for setting up a personalized preview mode in Sanity Studio using Next.js

I am facing an issue displaying the preview mode because the URL must contain specific parameters such as "category" and "slug" (as shown in the image below). Here is the error URL with undefined parameters Therefore, I am unable to retrieve the paramete ...

Ways to incorporate Bootstrap components into an Angular application without relying on external modules

I'm attempting to activate Bootstrap 5.3 Tooltips within my Angular 17 application. Within angular.json, I've added bootstrap.bundle.min.js, which includes PopperJS. "scripts": [ "node_modules/bootstrap/dist/js/bootstrap.bundle. ...

Detecting the State of the Keyboard in Ionic 2

Seeking an easy way to determine if the mobile device keyboard has been opened or closed using Ionic2 and Angular2. Is there a 'keyboard-open' or 'keyboard-close' class that Ionic sends to the body/html? ...

Enhancing Web Service Calls with Angular 2 - The Power of Chaining

I am currently facing an issue where I need to make multiple web service calls in a sequence, but the problem is that the second call is being made before the .subscribe function of the first call executes. This is causing delays in setting the value of th ...

Adding Rows Dynamically to Material Data Table in Angular 7

Is there a way to dynamically add data from a service into my table? I am receiving data from AuthenticationService dialog and attempted using this.dataSource.push(this.transaction);, but it did not work as expected. This is the code snippet where I trie ...

Long loading times observed for larger datasets in Angular4 Datatable

I am currently experiencing slow loading times for my datatable when trying to display the data. The script is being called within the component like so: ngAfterViewInit() { $.getScript('./assets/js/datatables/datatable-basic.js'); } T ...

Ensure that the hook component has completed updating before providing the value to the form

Lately, I've encountered an issue that's been bothering me. I'm trying to set up a simple panel for adding new articles or news to my app using Firebase. To achieve this, I created a custom hook to fetch the highest current article ID, which ...

`How can I incorporate typography into my Angular Material design?`

For my angular app, I am developing a custom theme and incorporating bootstrap's reboot to establish a basic starting point for non-material elements. To avoid conflicts with material variables, I converted the reboot into a mixin. In this mixin, I pa ...

Implementing TypeScript module resolution with Cucumber-js can be a bit tricky

Currently, I am in the process of creating a Proof of Concept for Cucumber-js using TypeScript. Everything is going smoothly except for one issue - I am facing difficulties when it comes to configuring the module resolution while utilizing tsconfig-paths. ...

Having difficulty implementing canDeactivate or canActivate in Angular

I am currently trying to integrate the canDeActivate and canActivate functions in my Angular 4 project. However, I seem to be encountering a no provider error. Can someone please guide me on what might be wrong with my implementation or suggest a cleaner a ...

Encountering a TypeError in Angular2 and Ionic2: 'Pst.Base64.decode' is not defined when evaluating the object

After upgrading to Ionic2 RC0 from Beta11, which uses ng2 final, I encountered an error while building for ios. The error message states: "EXCEPTION: undefined is not an object (evaluating 'Pst.Base64.decode')." 0 949421 error EXCEPTION ...

combine two separate typescript declaration files into a single package

Can anyone help me figure out how to merge two typescript definition packages, @types/package-a and @types/package-b, into one definition package? package-a.d.ts [export package-a {...}] package-b.d.ts [exports package-b {...}] package-mine.d.ts [ export ...