使用2个不同的* ngFor填充表

Nil*_*ade 5 html-table ngfor angular

以下是我的JSON对象数组:

{
  "tagFrequency": [
    {
      "value": "aenean",
      "count": 1,
      "tagId": 251
    },
    {
      "value": "At",
      "count": 1,
      "tagId": 249
    },
    {
      "value": "faucibus",
      "count": 1,
      "tagId": 251
    },
    {
      "value": "ipsum",
      "count": 1,
      "tagId": 251
    },
    {
      "value": "lobortis",
      "count": 1,
      "tagId": 194
    },
    {
      "value": "molestie",
      "count": 1,
      "tagId": 251
    },
    {
      "value": "unde tempor, interdum ut orci metus vel morbi lorem. Et arcu sed wisi urna sit egestas fringilla, at erat. Dolor nunc.",
      "count": 1,
      "tagId": 199
    },
    {
      "value": "Vestibulum",
      "count": 1,
      "tagId": 251
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想显示这些属性,即。表中的值,计数和tagName(使用tagId获取)。对于前两个属性,我正在使用ngFor。但是,我也想打印我正在使用tagId并将其存储在tagNames数组中的tagName。以下是我的组件代码:

frequencies: any;
tagNames: string[] = [];

ngOnInit() {
    if (this.route.snapshot.url[0].path === 'tag-frequency') {
      let topicId = +this.route.snapshot.params['id'];

      this.tagService.getTagFrequency(topicId)
        .then(
            (response: any) => {
          this.frequencies = response.json().tagFrequency
          for(let tagFrequency of this.frequencies) {
            this.getTagName(tagFrequency.tagId)
          }
        }
        )
        .catch(
            (error: any) => console.error(error)
        )
    }
}

  getTagName(tagId: number): string {
    return this.tagService.getTag(tagId)
    .then(
        (response: any) => {
          this.tagNames.push(response.name)
        }
    )
    .catch(
      (error: any) => {
        console.error(error)
      }
    )
  }
Run Code Online (Sandbox Code Playgroud)

这就是我试图在UI上打印它们的方式:

<table>
  <thead>
    <tr>
      <th>{{ 'word' }}</th>
      <th>{{ 'tag-name' }}</th>
      <th>{{ 'frequency' }}</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
      <ng-container *ngFor="let name of tagNames">
        <tr *ngFor="let frequency of frequencies; let i=index">
          <td>{{ frequency.value }}</td>
          <td>{{ name }}</td>
          <td>{{ frequency.count }}</td>
        </tr>
      </ng-container>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

但是我在列标记名下得到了[object object]。有人可以帮我解决这个问题吗?

我尝试如上所述使用ng-container,但结果在UI上看起来像这样: 标签名称问题

哪有错 我只需要前1,2行,行3的标签名分别为“ Subtag 3”,“ Zeit1”,“ Tag 1”。

提前致谢。

小智 5

您可以使用索引变量,在 *ngFor 中迭代频率数组并将其索引用于 tagNames

<tr *ngFor="let frequency of frequencies; let i=index">
      <td>{{ frequency.value }}</td>
      <td>{{ tagNames[i] }}</td>
      <td>{{ frequency.count }}</td>
  </tr>
Run Code Online (Sandbox Code Playgroud)

确保您已初始化 tagNames:

标签名称:字符串[] = [];