Home > Net >  How I can *ngFor for nested json in angular and get data?
How I can *ngFor for nested json in angular and get data?

Time:11-24

I am trying below array to display

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

I am trying to read a json file and trying to display in angular template

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

It shows below error enter image description here

CodePudding user response:

First of all you missed the "let" *ngFor="let i of myData.data.ZSLatencies"

ZSLatencies is a object , so you cannot use ngFor in this

Add public before myData and keep it in class not any function in ts file

public myData = {

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

Let approve the answer , If your issue is Fixed Thanks

CodePudding user response:

If you don't want to clutter your html with multiple nested ngFor, you can do this transformation in your component ts file.

let allLatencyValues = myData["data"]["ZSLatencies"]["Recharging API Latency"].map(x => x).reduce((acc, val) => acc.concat(val), []);

Then you ngFor would become simpler. Also note the let keyword.

<p *ngFor="let val of allLatencyValues; let i = index">
    {{i   1}}. {{ val }}
</p>

CodePudding user response:

Hi All Thanks for helping me, I have managed to fix I had couple of error, complete fix is below

<div >
    <table  *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>

However, the json file I am using a bit large and complex for me.
  • Related