How do I map the my JSON data to Angular component .HTML table

Viewed 236

I'm trying to map some JSON data to an Angular component. Here's the data I am trying to use:

[
   {
      "P1": [
         {
            "pc1": "XYZ",
            "pn1": "Testp",
            "pv1": 123,
            "m1": [
               {
                  "mn1": "XYZ",
                  "ma1": 12,
                  "mv1": 123456
               },
               {
                  "mn1": "Testm",
                  "ma1": 23,
                  "mv1": 22565
               },
               {
                  "mn1": "Testmn",
                  "ma1": 34,
                  "mv1": 234567
               }
            ]
         }
      ]
   }
]

And here's the HTML table I am trying to render:

    <table class='table table-striped' aria-labelledby="tableLabel" *ngIf="apiValues">
      <thead>
        <tr>
          <th>PC1</th>
          <th>PN1</th>
          <th>PV1</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let apiValue of apiValues">
          <td> {{ apiValue.pc1 }} </td>
          <td> {{ apiValue.pn1 }} </td>
          <td> {{ apiValue.pv1 }} </td>
        </tr>
      </tbody>
    </table>

I'm trying to map some JSON data to an Angular component. Here's the data I am trying to use.

2 Answers

it looks like most of the code is in place, so it's a little confusing on what the issue is, but I'm going to take a stab at it.

... It might be as easy as changing "apiValues" to "P1" ... ???

Lets assume we have a component called testComponent, you should have 2 files. testComponent.ts and testComponent.html.

Since you're referencing a variable called "apiValues" in the HTML file it would assume that there is a public variable in the .ts file called "apiValues" however, it looks like your variable you want to use is called P1 in the json..

So again, maybe it's as easy as renaming "apiValues" to "P1".

Or in the corresponding .ts file you could publicly declare the "apiValues" variable.

public apiValues: any = [
         {
            "pc1": "XYZ",
            "pn1": "Testp",
            "pv1": 123,
            "m1": [
               {
                  "mn1": "XYZ",
                  "ma1": 12,
                  "mv1": 123456
               },
               {
                  "mn1": "Testm",
                  "ma1": 23,
                  "mv1": 22565
               },
               {
                  "mn1": "Testmn",
                  "ma1": 34,
                  "mv1": 234567
               }
            ]
         }
      ]

That way the corresponding .HTML file can access the "apiValues" variable in its template.

It worked for me by updating this line to and then I was able to read all the values : let position of positions; let i = index

Related