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

Using Ajax on a WordPress webpage

I am currently experimenting with this piece of Ajax jQuery code within a WordPress page: 1. <script> 2. $(document).ready(function(){ 3. $("button").click(function(){ 4. $.ajax({ 5. method: 'GET', 6. ...

The Joi validate() function will return a Promise instead of a value when used within an asynchronous function

Trying to understand how async functions and the Joi.validate() function behave. Below is a function used for validating user input. const Joi = require("joi"); const inputJoiSchema= Joi.object().keys({ name: Joi.string(), email: Joi.string().require ...

Customize Your Lightbox Fields with DHXScheduler

In my JSP application for exam timetabling, I have integrated DHXScheduler and customized the lightbox to display additional information about exams using my own fields. The EventsManager class is responsible for managing events by saving, creating, and r ...

The ng-repeat function is failing to show any data on the HTML view, instead only displaying a row for each property present

HTML Code: <div ng-repeat="addr in addrShipData"> <input type="radio" name="resp1" ng-checked='true'/> {{addr.addressLine1 +","+addr.addressLine2+", "+addr.city+ ","+addr.state+", "+addr.country+", "+addr.zipCode+","+addr ...

Creating an HTML table from dynamic JSON data - A comprehensive guide

I am in need of a solution to transform JSON data into an HTML table format quickly and easily. Can anyone provide guidance on effectively utilizing PartialView to recursively render tables, ensuring that most details are visible? ...

Getting the location of a mouse click and adding tags (marks) on an image: a simple guide

Is there a way to incorporate images with tagged marks similar to Facebook's image tagging feature? How can I retrieve the X and Y coordinates of tags on the image itself (not the screen) and display them in a responsive manner? ...

Select box failing to display default value

I am dealing with a specific data structure: $scope.personalityFields.traveller_type = [ {"id":1,"value":"Rude", "color":"red"}, {"id":2,"value":"Cordial", "color":"yellow"}, {"id":3,"value":"Very Friendly", "color":"green"}, ]; Also, there is a se ...

Any ideas on how to format a date for jQuery Datepicker?

Currently, I have implemented two different datepickers on my website, but I am interested in switching to jQuery's Datepicker for a more unified solution. Here is the current format that I am sending to our backend API: However, I would prefer to i ...

Find the value of a JavaScript string variable using an alternative name

My latest JavaScript function is designed to fetch JSON data from either a server or local files on any browser. This piece of code processes JSON from two sources: an XMLHttpRequest response, or a variable imported via script. In the case of the latter, ...

Instructions for transferring an object containing data from a subscribed subscription

In the UserDataService service, there is a getUser function where I fetch a token by calling the tokens function and pass it to another getUser function to retrieve a user by their id. getUser(id: number) { return this.sharedDataService.tokens.subscribe( ...

Error in Material UI when using the select component

CustomComponent.js:98 UI Error: The value undefined provided for the selection is out of range. Please make sure to select a value that matches one of the available options or ''. The available options are: `All`, `Software Development`, `Qualit ...

Simulating a mobile device screen size using an embedded iframe

Imagine this scenario: What if instead of adjusting the browser window size to showcase a responsive web design, we could load the site into an IFRAME with the dimensions of a mobile screen. Could this concept actually work? Picture having an IFRAME like ...

What is the best way to perform a redirect in Node.js and Express.js following a user's successful login

As I work on developing an online community application with nodejs/expressjs, one persistent issue is arising when it comes to redirecting users to the correct page after they have successfully signed in. Despite reading several related articles and attem ...

displaying a PDF file in Safari

Is there a way to display a PDF document within an HTML page without encountering a missing plugin error? I attempted to use the following code, but the error persists. Interestingly, if I drag the same PDF file directly into my browser, it displays perfe ...

Guide on accessing and displaying data table values in console.log using Vue.js and vuetify

Hello, I am new to Vue.js and I am trying to work with data tables. I have copied some code from the Vuetify website and I am attempting to call the desserts' names from a sample table using console.log. Below is the code snippet: <template> ...

Tips for sending and retrieving parameters using the POST technique

Currently, I am in the process of building a user authentication form for my website using Javascript. I am utilizing Vue JS on the client-side and NodeJS with ExpressJS on the server-side. For the server-side functionality, I have implemented the followi ...

Import statements cannot be used outside of a module when working with a private npm package in cucumber.js

Utilizing cucumberjs to test various components of my project has been successful. However, I encountered an issue in one step where I utilize a zod schema that is defined within a private npm module: // within the private npm package: // constant.js impor ...

Acquiring a collection of objects retrieved from a set of URLs using rxjs and typescript

I have an item to work with: let DataObject = { 'item1' : './someitem1.json', 'item2' : './someitem2.json',.. }; I want to fetch all items using RxJS and notify the subscriber only after all items have been fe ...

Issue: Using the command 'typings search' successfully locates a package, however, when attempting to install it using 'typings install', the process fails

I am currently attempting to install the Google Auth2 typings using 'typings': > typings search gapi.auth2 This command returns: NAME SOURCE HOMEPAGE DESCRIPTION VERSIONS UPDATED gapi.auth2 d ...

The world of coding comes alive with Quartz Composer JavaScript

Seeking assistance as I navigate through a challenging project. Any help would be greatly appreciated. Thanks in advance! I have a Quartz Composition where I aim to incorporate a Streetview from Google Maps and control the navigation, but I'm unsure ...