如何用ngFor显示嵌套数组?

问题描述 投票:0回答:1
html arrays json angular
1个回答
1
投票

假设您有以下数据结构:

fields = [
  {
    name: 'Item 1',
    value: [
      {
        name: 'Sub-item 1.1',
        value: [
          { name: 'Sub-sub-item 1.1.1', value: 'Value 1.1.1' },
          { name: 'Sub-sub-item 1.1.2', value: 'Value 1.1.2' },
        ],
      },
      {
        name: 'Sub-item 1.2',
        value: 'Value 1.2',
      },
    ],
  },
  {
    name: 'Item 2',
    value: 'Value 2',
  },
];

模板实现

<div *ngFor="let item of fields; let i = index">
  <div>
    i: {{ i }} {{ item.name }} - {{ item.value }}
  </div>
  <!-- Check if value is an array -->
  <div *ngIf="item.value && item.value.length" style="margin-left: 20px;">
    <div *ngFor="let subItem of item.value; let j = index">
      <div>
        j: {{ j }} {{ subItem.name }} - {{ subItem.value }}
      </div>
      <!-- Check if value is an array -->
      <div *ngIf="subItem.value && subItem.value.length" style="margin-left: 20px;">
        <div *ngFor="let subSubItem of subItem.value; let k = index">
          <div>
            k: {{ k }} {{ subSubItem.name }} - {{ subSubItem.value }}
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.