首页 > 解决方案 > Angular *ngFor 在根目录中显示键和值,但不显示子数据

问题描述

我有一些看起来像这样的数据:

data = {
    title: 'some title',
    name: 'some name',
    active: false,
    extra: [
        {
            title: 'some data'
        }
    ]
  };

And I've displaying the key and values using:

<ul class="list-group" *ngFor="let item of data | keyvalue">
    <li class="list-group-item">{{ item.key }}:{{ item.value }}</li>
</ul>

这个问题是它没有显示子数据,例如,extra: [];

我只是得到对象

我怎样才能解决这个问题?

标签: angular

解决方案


你可以使用这样的东西

<ul class="list-group">
  <ng-container *ngFor="let item of data | keyvalue">
    <li class="list-group-item" *ngIf="isNested(item.value)">
      {{ item.key }}
      <ul class="list-group">
        <ng-container *ngFor="let nestedVal of item.value">
          <li class="list-group-item" *ngFor="let nestedKeyVal of nestedVal | keyvalue">
            {{ nestedKeyVal.key }}: {{ nestedKeyVal.value }}
          </li>
        </ng-container>
      </ul>
    </li>
    <li class="list-group-item" *ngIf="!isNested(item.value)">
      {{ item.key }}:{{ item.value }}
    </li>
  </ng-container>
</ul>

where isNested 可以这么简单

isNested(value) {
  return typeof(value) === 'object';
}

推荐阅读