【问题标题】:Create a dynamic Table out of JSON Object using Angular 5 directives使用 Angular 5 指令从 JSON 对象创建动态表
【发布时间】:2018-10-18 14:05:42
【问题描述】:

是否可以使用 Angular 5 指令/或借助 jQuery 创建基于 JSON 对象的动态表(动态列)?如果有怎么办?

假设我从 REST API 得到这个 JSON 响应:

{
      name: "Ferrari"
      country: "Italy",
      creater: "Enzo Ferrari"
      cars: [
        {
          modell: "Ferrari 488",
          price: "215.683€"
        },
        {
          modell: "Ferrari Portofino",
          price: "189.704€"
        }
     ]
    }

现在我想用这个数据创建一个应该如下所示的表:

+-----------+----------+--------------+--------------+------------+--------------------+-------------+
| Name      | Country  | Creater      | Modell       | Price      | Modell             | Price       |
+-----------+----------+--------------+--------------+------------+----------------------------------+
|  Ferrari  | Italy    | Enzo Ferrarie| Ferrarie 488 | 189.704€   | Ferrarie Portofino | 189.704€    |
+-----------+----------+--------------+--------------+------------+--------------------+-------------+

解决此问题的最佳方法是什么?我只是想不通如何解决这个问题?非常感谢任何帮助。

【问题讨论】:

标签: javascript html angular typescript html-table


【解决方案1】:

如果表中只有一个对象(即一个标题行和一个数据行),您可以执行以下操作:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Country</th>
      <th>Creater</th>
      <ng-template ngFor [ngForOf]="data.cars">
        <th>Modell</th>
        <th>Price</th>
      </ng-template>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{{ data.name }}</td>
      <td>{{ data.country }}</td>
      <td>{{ data.creater }}</td>
      <ng-template ngFor let-car [ngForOf]="data.cars">
        <th>{{ car.modell }}</th>
        <th>{{ car.price }}</th>
      </ng-template>
    </tr>
  </tbody>

</table>

您可以使用 ng-template 和 ngFor 指令来遍历汽车。

重要提示:如果您有多个数据行,则需要确保转换数据,以便始终显示相同数量的列,否则 html 将被破坏。

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 2017-04-10
    • 2023-02-09
    • 2016-01-09
    • 1970-01-01
    • 2020-01-17
    • 2019-10-28
    • 1970-01-01
    • 2017-05-04
    相关资源
    最近更新 更多