Using ngFor directive to iterate through nested objects in Angular

Receiving data from the server:

{
  "12312412": {
    "id": "12312412",
    "something": {
      "54332": {
        "id": "54332",
        "nextNode": {
          "65474": {
            "id": "65474",
            "data": "any"
          },
          "235235": {
            "id": "235235",
            "data": "any"
          },
          "543524": {
            "id": "543524",
            "data": "any"
          }
        }
      }
    }
  },
  "23242434": {
    "id": "23242434",
    "something": {
      "3234234": {
        "id": "3234234",
        "nextNode": {
          "645636": {
            "id": "645636",
            "data": "any"
          },
          "1543534": {
            "id": "1543534",
            "data": "any"
          },
          "12312412": {
            "id": "12312412",
            "data": "any"
          }
        }
      }
    }
  }
}

Now, looking to loop through nested objects using ngfor in Angular 9. Wondering if creating multiple loops and converting it into an array would optimize performance. Any suggestions for a more efficient solution? Thank you.

Answer №1

If you want to achieve your goal, consider creating a recursive component and utilizing the keyvalue pipe. Below is an example of how a component can be structured to handle this:

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

@Component({
  selector: "app-key-value-display",
  styleUrls: ["./key-value-display.component.css"],
  template: `
    <div>
      <div
        *ngFor="let item of (obj | keyvalue)"
        [style.margin-left.px]="margin"
      >
        {{ item.key }} :
        <span *ngIf="isPrimitive(item.value); else complex"></span>
        <ng-template #complex>
          <app-key-value-display
            [obj]="item.value"
            [margin]="margin + 4"
          ></app-key-value-display>
        </ng-template>
      </div>
    </div>
  `
})
export class KeyValueDisplayComponent implements OnInit {
  @Input() obj: any;
  @Input() margin = 0;
  constructor() {}

  ngOnInit() {}

  isPrimitive(obj: any) {
    return typeof obj !== "object";
  }
}

Check out Stackblitz for more information.

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

Change the format into a PHP array

In my workplace, I am confronted with a frustrating system that generates the following output: { party:"bases", number:"1", id:"xx_3039366", url:"systen01-ny.com", target:"_self", address:"Ch\u00e3o as Alminhas-Medas,Uteiros ...

Trouble displaying AngularJS $scope.data in the HTML code

I'm experiencing an issue where the data received from a POST request is being logged in the console, but is not displaying on the HTML page. Despite having a controller set up, the {{user}} variable is not appearing on the HTML page. While I can se ...

Issue with VueJS where the data list cannot be accessed from one template in another template

I'm facing an issue with my setup where there is a crash occurring on the v-for construct of the table-component. The error message displayed is: "Property or method "tablesList" is not defined on the instance but referenced during render". Strangely, ...

instructions on how to exclusively close a bracket within a double bracket in a regular expression match

const input = "example(1)(2)example(3)example(4)(5)example(6)(7)example(8)example(9)" const regexp = new RegExp(????) // <-- need help with this input.match(regexp) result: [example(1)(2), example(3), example(4)(5), example(6)(7), example(8), example( ...

Customize your click event with conditional styling in React

When the onClick event is triggered, I am attempting to modify a class by calling my function. It appears that the function is successfully executed, however, the class does not update in the render output. Below is the code snippet: import React from &ap ...

Exploring Specific Locations with AmCharts 5 Zoom Feature

Just starting to use AmCharts 5 and I'm struggling to trigger a simple zoom into a location on a map. No matter which tutorial I follow, I can't seem to replicate the results others are getting. If you want to take a look at my Codepen setup to ...

The Vercel error indicates that the file or directory '/var/task/node_modules/shiki/themes/one-dark-pro.json' does not exist

import { serialize } from 'next-mdx-remote/serialize'; import readingTime from 'reading-time'; import remarkGfm from 'remark-gfm'; import rehypeSlug from 'rehype-slug'; import rehypeAutolinkHeadings from 'rehype ...

Use the res.json method in express.js to automatically generate a predefined response structure

I'm looking for guidance on how to properly use res.json in my code. I want to establish a default response structure that includes a message and error, while also being able to include additional data when necessary. For example, when I use res.statu ...

Securely transfer data between objects using a for loop

Description I have two similar types that are not identical: type A = { a?: number b?: string c?: boolean } type B = { a?: number b?: string c?: string } I am looking to create an adapter function f() that can convert type A to type B, with ...

What is the process for displaying all indexes of a Mongo Collection using MongoDB Node native?

I am curious about how to retrieve all indexes from a specific collection in mongodb. I've tried using listIndexes, indexes, and indexInformation, but these methods only return empty values (arrays and objects). However, when I run db.getCollection(&a ...

Console error detected, yet content still appears on web browser

I encountered an issue in my Angular app where I am getting the ERROR TypeError: Cannot read property 'name' of undefined, even though the projects.name is successfully displaying. How do I troubleshoot this error appearing in the console.log? Th ...

Comparing two string dates in mongoose: A guide

I am trying to retrieve data between two specific dates in my Schema. transactionDate : String Here is the function I am using to get data between two dates: async getLogsByDate(start, end) { return await this.logModel .find({ date: { $gte: sta ...

Including a link in PHP results in the creation of a new cookie each time the include statement is executed

Issue: I am facing a problem while trying to retrieve JSON data after logging in with a previous login link. Before I can access the JSON data, I need to log in using the following link: '...server.net/System?action=login&user=ro&password=12& ...

When using var_dump, the function file_get_contents("php://input") returns a null value

file_get_contents("php://input"); function is not functioning as expected. $data=$_GET['json']; is operational and producing the desired output. The URL that I am working with is shown below: http://localhost/demo/plainjson.php?json={"order_ ...

Guide to counting the number of image tags within a parent div and selectively removing them starting from a specific position

My dynamic image tag <img> is generated inside a div from the database using fetching. Here is how my HTML looks: <div class='forimgbox'> <p class='palheading'>Pals</p> <img src='userpic/2232323.p ...

Tips for ensuring a document stays at the top of my collection when performing an update

Whenever I make changes to a document, it always ends up at the bottom of my collection. Is there a way to prevent this from happening? try { await Card.update({_id: fixedUrl}, {$push:{'comments': data}}) } catch (err) { console.log(err ...

Sending form data to PHP script following Javascript verification

After implementing basic validation for a contact form, I encountered an issue where the form would not submit to the PHP file responsible for sending emails. Despite setting the button type as "submit" and defining the form action as "contactform.php", th ...

How to format dates when exporting Excel from Kendo Grid in Angular 2

When attempting to export data from the Kendo UI Grid for Angular, there seems to be an issue with formatting the date column. The actual date value is not being displayed correctly in the exported file. Below is a snippet of the code: <kendo-excelexpo ...

The Background Geolocation feature is throwing an error: "Subscribe method is not present in the Promise<any> type."

I am currently using Ionic 4 to build an app that tracks the user's location every hour using GPS. To achieve this, I utilized the Ionic 4 Background Location plugin as per their official documentation. I followed the code to install the plugin which ...

When executing npm run build for production, the resulting build does not include distribution for

I am encountering an issue with my Angular project, specifically during the build process. After running ng build, the dist folder is created with the correct build. However, when I run the command: ng build --prod it generates the production build as e ...