ngFor用于角度的嵌套对象

时间:2020-10-06 19:10:08

标签: javascript json angular typescript ecmascript-6

我有一个来自服务器的对象:

{
  "12312412": {
    "id": "12312412",
    "something": {
      "54332": {
        "id": "54332",
        "nextNode": {
          "65474": {
            "id": "65474",
            "data": "any"
          },
          "235235": {
            "id": "235235",
            "data": "any"
          },
          "543524": {
            "id": "543524",
            "data": "any"
          }
        }
      }
    }
  },
  "23242434": {
    "id": "23242434",
    "something": {
      "3234234": {
        "id": "3234234",
        "nextNode": {
          "645636": {
            "id": "645636",
            "data": "any"
          },
          "1543534": {
            "id": "1543534",
            "data": "any"
          },
          "12312412": {
            "id": "12312412",
            "data": "any"
          }
        }
      }
    }
  }
}

我需要用角度9的ngfor遍历所有嵌套对象。

我应该进行多重循环并将其设置为数组吗?我正在寻找最佳性能的解决方案。谢谢

1 个答案:

答案 0 :(得分:1)

您可以制作一个递归组件,并使用keyvalue管道来实现您的目标。如下所示的组件应该可以处理它:

import { Component, Input, OnInit } from "@angular/core";

@Component({
  selector: "app-key-value-display",
  styleUrls: ["./key-value-display.component.css"],
  template: `
    <div>
      <div
        *ngFor="let item of (obj | keyvalue)"
        [style.margin-left.px]="margin"
      >
        {{ item.key }} :
        <span *ngIf="isPrimitive(item.value); else complex"></span>
        <ng-template #complex>
          <app-key-value-display
            [obj]="item.value"
            [margin]="margin + 4"
          ></app-key-value-display>
        </ng-template>
      </div>
    </div>
  `
})
export class KeyValueDisplayComponent implements OnInit {
  @Input() obj: any;
  @Input() margin = 0;
  constructor() {}

  ngOnInit() {}

  isPrimitive(obj: any) {
    return typeof obj !== "object";
  }
}

Stackblitz