Exploring the depths of a nested object by traversing through an array of its

Trying to iterate through a nested object structure with Angular TS:

{
        "stringKey1": {
            "child": [
                {
                    "stringKey2": {
                        "child": []
                    }
                },
                {
                    "stringKey3": {
                        "child": []
                    }
                },
                {
                    "stringKey4": {
                        "child": [
                            {
                                "stringKey5": {
                                    "child": []
                                }
                            },
                            {
                                "stringKey6": {
                                    "child": []
                                }
                            }
                        ]
                    }
                }
            ]
        }
    }
    

Each "node" consists of a string key and an object {"child" : []} that may have multiple children with the same structure.

Attempts were made using *ngFor with pipe, and *ngIf to check if it is an array. However, it's difficult to predict the depth of the structure dynamically.

Tried various methods found online but still facing issues. Maybe overlooking something important.

Any suggestions or assistance would be greatly appreciated.

Thank you!

Answer №1

It's always best to avoid complicated template logic involving nested object loops. This can make your code hard to read and troubleshoot. Instead, try simplifying the data in your TypeScript code first, and then manipulate it in the template.

One useful technique is using the | keyvalue pipe to loop over Objects with *ngFor. By utilizing the ng-template and *ngTemplateOutlet, you can create recursion in your templates.

<ng-template #recursiveList let-array>
  <li *ngFor="let item of array | keyvalue">
    {{item.key}} {{item.value}}
    <ul *ngIf="item.value"> 
      <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.value }"></ng-container>
    </ul>
  </li>
</ng-template>

<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: object }"></ng-container>

If you'd like to see a working example, check out this link: https://stackblitz.com/edit/angular-nested-ngfor-in-table-4nqhve?file=src%2Fapp%2Fapp.component.html

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

Tips for using the arrow keys to navigate the cursor/caret within an input field

I am trying to create a function that allows the cursor/caret to move inside an input field character by character using the arrow keys (ArrowLeft, ArrowRight) on a keydown event. Current Approach: const handleKeyDown = (e: KeyboardEvent<HTMLInputEle ...

Having trouble with Next.js 13 GitHub OAuth integration - it keeps redirecting me to Discord instead of signing me in

There's a perplexing issue troubling my application... The implementation of OAuth 2 with GitHub, Discord, and Google is causing some trouble. While Google and Discord authentication works smoothly, attempting to sign in via GitHub redirects me to Di ...

Difficulty modifying the background color of a bar graph in Chart.js within an Ionic 2 Angular2 environment

I've been working with Chart.js in an Ionic2 and Angular2 hybrid app to create a stacked bar graph. However, I'm facing an issue where I can't seem to change the background color or fill color of the bars in the graph. Despite trying out all ...

What is the process for generating a dynamic array in typescript?

Looking to create a TypeScript dynamic array with the desired format: const display = [ { id: 1, displayName: "Abc1" }, { id: 2, displayName: "Abc2" }, { id: 3, displayName: "Abc3" } ] Attempted the following code ...

Getting started with testing in Angular 2

When I first started coding my app, unit tests were not on my mind. Now, I realize the importance and need to write them. However, while attempting to write tests using Jasmine only, I encountered an error when trying to import components - "system is no ...

How can I handle custom validation in Angular 6 template-driven forms if there is "no provider" available?

I am currently following the instructions outlined in the documentation found at https://angular.io/guide/form-validation#custom-validators After using the ng generate command, I have successfully added a new directive to my project. import { Directive} ...

A clever approach to toggling the visibility of elements in Angular2 using complex conditions

My webpage includes 10-12 buttons and a few other input fields. Depending on user roles and types, I need to control the visibility of these buttons and inputs. For instance: If user type = a, then hide 3 buttons and 2 inputs. If user type = b, and user ...

Issue with Angular 2's ngModelChange function in the second dropdown causing it to malfunction

I am facing an issue with two dropdown menus that have different ngModelChange methods: <div class="mb-40"> <div class="tit03 mb-20">Type of Healthpros</div> <select class="form-control" [(ngModel)]="pros" (ngModelChange)="onSelec ...

The importance of using constructors when injecting a service into an Angular2 component

As I continue to learn Angular2 using https://angular.io, I have encountered a confusion in the "Service" chapter. After importing the service in the component, there is a code snippet: constructor(private heroService: HeroService) { } I am unsure why we ...

Underwhelming scroll speed when working with 9 columns in react-virtualized

I am currently utilizing react-virtualized in conjunction with material-ui table cells to establish a table featuring virtual scrolling. Although everything appears to be functioning correctly, I am experiencing intermittent performance slowdowns when navi ...

What is the best way to verify if the ReactDOM.render method has been invoked with a React component as an argument

Here's the code snippet: index.tsx: import React, { Component } from 'react'; import ReactDOM from 'react-dom'; export function Loading(props) { return <div {...props}>loading...</div>; } export class MyComponent e ...

I am looking to store a collection of objects in Firebase using a single request, and I want Firebase to generate a unique key for each object without using array

I am looking to store a set of objects in Firebase using a single request with a unique key generated by Firebase (without using array indexes as keys). let object_list = { '0': { 'title':'title 1', 'time&apos ...

The importance of displaying doughnut chart tooltips in Angular 5 console

Is there a way to consistently display tooltips for a doughnut chart? This code snippet might help: Chart.pluginService.register({ beforeRender: function(chart) { if (chart.config.options.showAllTooltips) { // create an array of tooltips // we ...

Avoiding Maximum Call Stack Size Exceeded in Observables: Tips and Tricks

After filtering, I have a list stored in the variable filteredEvents$: public filteredEvents$ = new BehaviorSubject([]); I also have a method that toggles the checked_export property and updates the list: public checkAll(): void { this.filteredEve ...

Unit Testing Angular with Jasmine: Simulating the response of an HTTP Request made in a service invoked by a component

Greetings everyone: I am currently working on writing unit tests for a modification to a component that involves changing the order in which objects are retrieved from a service. I'm facing difficulties in figuring out how to mock the http request for ...

Using TypeScript with Vue in a non-component-based architecture

Recently, I've been facing a challenge while developing an application. I'm using Vue + Vuetify with typescript, but I'm trying to steer clear of creating a single-page application or using webpack to handle .vue components. My goal is to cr ...

Conditionally setting a property as optional in Typescript

Imagine a scenario where I have a type defined as interface Definition { [key: string]: { optional: boolean; } } Can we create a type ValueType<T extends Definition> that, given a certain definition like { foo: { optional: true } ...

Does the React memo function modify the component's prop type?

I've come across a strange issue where defining two components causes compilation errors when written separately but not when written in the same file. test3.tsx import React from "react"; type ValueType = number[] | string[] | number | st ...

Having trouble getting Angular ngIf to work with multiple matches?

I am facing an issue with my ngIf directive that has got me puzzled. Initially, my ngIf statement was functioning flawlessly like this. ngIf="this.offerFormGroup.get('identityTypeId').value == 4 However, now I need to extend it by adding mo ...

Retrieving an array using Mongoose and Typegoose by specifying the start and end index

Is there a way to retrieve a specific array slice directly from MongoDB? I am attempting to achieve something similar to this: Model.find({filter: option}, startindex, endindex. Currently, the only method I have discovered is as follows: let result = await ...