* ng用于遍历包含对象的数组

时间:2019-10-07 06:52:51

标签: angular typescript

gemItems:

{
 A: [
{id: 5, commonName: "Abalone Pearls"},
{id: 3, commonName: "Abalone Shell"}
],
 B: [
{id: 41, commonName: "Barite"},
{id: 42, commonName: "Bastnaesite"}
]
}

HTML:

<div *ngFor = let items of gemItems>
<div>{{items.id}}</div>
</div>

请让我知道如何遍历gemItems。

2 个答案:

答案 0 :(得分:3)

首先,getItems的定义应如下:(问题中的json无效)

  getItems = [
    {
      A: [
        { id: 5, commonName: "Abalone Pearls" },
        { id: 3, commonName: "Abalone Shell" }
      ]
    },
    {
      B: [
        { id: 41, commonName: "Barite" },
        { id: 42, commonName: "Bastnaesite" }
      ]
    }
  ];

现在,通过使用keyvalue,您可以在模板中使用以下内容:

<div *ngFor="let items of getItems">
    <div *ngFor="let entry of items | keyvalue">
        <div *ngFor="let subEntry of entry.value">
            <div>{{subEntry.id}} : {{subEntry.commonName}}</div>
        </div>
    </div>
</div>

答案 1 :(得分:0)

使用ngFor周围的双引号可以起作用:

<div *ngFor="let items of gemItems">