Md Ratan Hossain
Md Ratan Hossain

Reputation: 1

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

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

Upvotes: 0

Views: 56

Answers (3)

Md Ratan Hossain
Md Ratan Hossain

Reputation: 1

I have managed to fix I had couple of error, complete fix is 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>

Upvotes: 0

Navoneel Talukdar
Navoneel Talukdar

Reputation: 4588

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>

Upvotes: 0

GouriSankar
GouriSankar

Reputation: 71

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

Upvotes: 1

Related Questions