"Exploring the use of *ngFor for iterating through nested JSON data in Angular to retrieve the necessary information

I have been attempting to showcase the following array:

  myData = {
    "data": {
      "ZSLatencies": {
        "Recharging API Latency": [
          [
            "<200ms",
            2320
          ],
          [
            ">200ms",
            4
          ],
          [
            ">500ms",
            0
          ],
          [
            ">1000ms",
            0
          ],
          [
            ">2000ms",
            0
          ],
          [
            ">3000ms",
            0
          ]
        ]
      }
    }
  }

My aim is to parse a JSON file and display it using an Angular template

<div *ngFor="i of myData.data.ZSLatencies" >
    <p *ngFor="let d of i">
        {{d}}
    </p>
</div>

An error message is displayed as shown below: enter image description here

Answer №1

Firstly, don't forget to include the "let" keyword in your *ngFor directive:

*ngFor="let i of myData.data.ZSLatencies"

ZSLatencies is an object, so using ngFor on it may not work as intended.

Make sure to add "public" before myData and define it within a class, not within any function in the TypeScript file.

public myData = {

<div *ngFor="let i of myData.data.ZSLatencies.Recharging API Latency">
    {{i | json}}
</div>

If this solves your issue, please confirm the answer. Thank you!

Answer №2

To avoid cluttering your HTML code with multiple nested ngFor loops, you can streamline the process in your component TypeScript file.

const latencyValues = myData["data"]["ZSLatencies"]["Recharging API Latency"].flatMap(x => x).reduce((acc, val) => acc.concat(val), []);

By doing this transformation, your ngFor loop will become more straightforward. Pay attention to the use of the 'let' keyword as well.

<p *ngFor="let value of latencyValues; let index = index">
    {{index + 1}}. {{ value }}
</p>

Answer №3

After fixing a couple of errors, I have successfully completed the fix as detailed below:

<div class="container">
    <table class="table table-striped " *ngFor="let item of myData | keyvalue" style="width:  auto">
        <ng-container *ngFor="let innerkey of item.value| keyvalue">
            <ng-container *ngFor="let innerkey2 of innerkey.value| keyvalue">
                <thead>
                    <tr>
                        <th scope="col">{{innerkey2.key}}</th>
                        <th scope="col">{{innerkey2.key}}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let row of innerkey2.value | keyvalue">
                        <td>{{row.value}}</td>
                        <td>{{row.value}}</td>
                    </tr>
                </tbody>
            </ng-container>
    
        </ng-container>
    </table>
</div>

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

The ngModelChange and change events are not activated when using md-select

Here is the code snippet I am working with: <md-select [(ngModel)]="model" (change)="updateModel()" (ngModelChange)="model=$event;updateModel()"> [...] <md-select> However, I am encountering an issue where when I update the model programmati ...

Error: Unable to dispatch a Redux-thunk action with additional arguments in React

Currently, I am attempting to work with TypeScript alongside Redux-Thunk and Redux. My goal is to pass an object to any action (I am utilizing dependency injection and need to pass either an object service or a string). However, I encountered the followin ...

Error in Angular Universal: KeyboardEvent is not defined

I have inserted the word "domino" into the server.ts file and updated the webpack.server.config.js as follows: module: { rules: [ { test: /\.(ts|js)$/, loader: 'regexp-replace-loader', options: { match: { pattern: '&bs ...

Dynamic Color Changes on Highcharts Sunburst Based on Hierarchy Levels

Is there a way to dynamically adjust the color of layers in a sunburst chart when changing levels? Take a look at our example chart: https://i.sstatic.net/6cEdg.png When clicking on a continent like Asia, the chart should display like this: https://i.sst ...

Chakra UI - The "Open Modal" button is disabled from being clicked repeatedly

Encountering an issue with Chakra UI modal dialog in Next.js. Attempting to utilize the code below in pages/index.tsx for displaying a modal dialog. import type { NextPage } from "next"; import { Modal, ModalOverlay, ModalContent, Moda ...

What is the best way to confirm that every element within an array consists of a single type of character?

Here is an illustration: {1, 1, 11, 1111, 1111111} This set demonstrates a valid pattern as each element solely consists of the digit 1. Conversely, {11, 101, 1111, 11111} does not meet the criteria and is deemed invalid due to incorporating both 0 and 1 ...

Error Detection during Subject() Pipe Access Unit Test

I encountered an issue while writing a test case, where it is showing an error stating that pipe is not a function. The specific error message is: this.panelService.outputEmitter.pipe is not a function Below is the relevant code snippet in TypeScript an ...

How can we convert multiple arrays into a single JSON object?

I have multiple arrays like the ones shown below: var a=[1,2,3,4,5,6,7,8,9]; var b=["a","b","c","d","e","f","g","h","i","j"]; However, I need to convert these arrays into an array object structured like this: ab=[ ["1","a"], ...

Meteor - The dependency specified in [email protected] or [email protected] is unmet

I am facing an issue with my meteor project using angular2. When I try to install the package rxjs5.0.0-beta.11 using 'meteor npm install', it gives me the following message: @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

I am looking to direct traffic to an external Angular application by sending query parameters, which will then be used to construct and access a specific URL

I have two applications, a primary one and a secondary one, both built with Angular and sharing the same backend. I am looking to create a route from the main application to the secondary application while passing some query parameters along. Currently, m ...

What is the reason behind the lack of output in Javascript .filter() when using an active filter (== or ===) compared to the successful operation with the boolean logic type of != or !==?

import React from "react"; import productsData from "./products.js"; import Product from "./Product.js"; function App() { const importedProductsArray = productsData.map((item) => ( <Product id={item.id} ...

Encountering a situation where the data retrieved from Firestore in Angular TypeScript is returning as

I am encountering an issue with retrieving the eventID value from my Events collection in Firestore. Although I am able to successfully display all the events in my app, I require the eventID for additional functionalities. As someone new to TypeScript an ...

Issue with Typescript in react: JSX element lacks construct or call signatures

After upgrading TypeScript, I encountered the error mentioned above in one of my components. In that component's render method, I have the following code: render() { const Tag = props.link ? 'a' : 'div'; return ( < ...

Angular2 and ES6 Promise in JavaScript - tackling the issue of undefined variables

I am working with an array of objects like the one shown below: let PAGES = [ new BasePage( 'home', 'test') ]; let pagesPromise = Promise.resolve(PAGES); My goal is to retrieve a BasePage object by calling the following met ...

Ways to print several tabs at once in Angular 4

In my Angular 4 application, I have implemented a feature with 4 tabs ('tab1', 'tab2', 'tab3', 'tab4') on the screen. Each tab corresponds to an Angular component that is dynamically loaded. When a user lands on the ...

Looking for a way to search for contacts by number in Nativescript? Learn how to use the `getContactsByNumber(number

Using the nativescript-contacts plugin with nativescript 5.0, Angular, and webpack. Is there a way to retrieve the contact name based on the phone number? The main issue is that I want to display a list of recent phone calls, but there is one problem. L ...

Diverse method of reaching an array within another array in PHP

I'm struggling to access a two dimensional array in PHP. The traditional method ($myarray[0][0]) is not working for me because I need to create a recursive function that can delve deeper into the array with each call (starting at $myarray[0], then mov ...

Sending a JSON payload to update a resource in Rails via an API

The Problem: After spending nearly 6 hours today trying to resolve this issue, I am stuck on sending a POST request to an API endpoint and making modifications to that resource using Rails. Can someone provide some guidance based on the following details ...

What is the best way to implement custom JSON serializers for both parent and child classes independently?

Within this example, there exists a primary class called A and a subclass called B: public class A { public final String primaryKey; A(String primaryKey) { this.primaryKey = primaryKey; } } public class B extends A { public final ...

The link button appears unselected without a border displayed

I am facing an issue with a link button in my code. Here is the snippet: <div class="col-2"> <a type="button" routerLink="auto-generate-schedules/generate" class="btn btn-primary mb-2">Generate Sche ...