html - 如何将我的 JSON 数据映射到 Angular 组件 .HTML 表

标签 html json angular typescript

我正在尝试将一些 JSON 数据映射到 Angular 组件。这是我尝试使用的数据:

[
   {
      "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
               }
            ]
         }
      ]
   }
]

这是我要呈现的 HTML 表格:

    <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>

我正在尝试将一些 JSON 数据映射到 Angular 组件。这是我尝试使用的数据。

最佳答案

看起来大部分代码都已到位,所以问题是什么有点令人困惑,但我会尝试一下。

...可能就像将“apiValues”更改为“P1”一样简单...???

假设我们有一个名为 testComponent 的组件,您应该有 2 个文件。 testComponent.ts 和 testComponent.html。

由于您在 HTML 文件中引用了一个名为“apiValues”的变量,因此它会假定 .ts 文件中有一个名为“apiValues”的公共(public)变量,但是,看起来您要使用的变量名为 P1在 json 中..

再说一遍,也许就像将“apiValues”重命名为“P1”一样简单。

或者在相应的 .ts 文件中,您可以公开声明“apiValues”变量。

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
               }
            ]
         }
      ]

这样相应的 .HTML 文件就可以访问其模板中的“apiValues”变量。

关于html - 如何将我的 JSON 数据映射到 Angular 组件 .HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64763263/

相关文章:

html - 如何在 IE10 中用 css 覆盖不可选择的 ="on"?

html - 我的标题字体将不适用,我的 p 字体将适用

javascript - 如何使用JSONP?

python - 在Python中使用for循环生成动态嵌套JSON

jquery - HTML jQuery treeTable 自动刷新闪烁

javascript - 调用 Web API - 无法读取未定义的属性 'filter'

javascript - 错误类型错误 : Cannot read property 'invalid' of undefined while trying to list FormArray of FormGroups in Angular

javascript - css 缩放在 ie11 中不起作用

javascript - html webview android 中的 Cookie

angular - 获取选择一个菜单的默认值