使用 ngFor 递归地迭代对象的对象

Iterating over n object of objects using ngFor recursivley

我有一个 Angular 项目,我需要在其中显示服务器的文件夹结构。 我有 json 这种形式的数据(演示名称):

{
    "dirPath": "file:///C:/dev/gallery/filesFromApp/",
    "folderName": "filesFromApp",
    "fileNames": [
        "firmwareUpdate101.txt",
        "keyboard_output.txt",
        "screen-locks.txt"
    ],
    "dirInfoList": [
        {
            "dirPath": "file:///C:/dev/gallery/filesFromApp/Beta1/",
            "folderName": "Beta1",
            "fileNames": [
                "beta1Ubdate.txt"
            ],
            "dirInfoList": []
        },
        {
            "dirPath": "file:///C:/dev/gallery/filesFromApp/Beta2/",
            "folderName": "Beta2",
            "fileNames": [
                "Beta2UPDATE!.txt"
            ],
            "dirInfoList": [
                {
                    "dirPath": "file:///C:/dev/gallery/filesFromApp/Beta2/omaewa/",
                    "folderName": "omaewa",
                    "fileNames": [
                        "nani.txt"
                    ],
                    "dirInfoList": []
                }
            ]
        }
    ]
}

我需要做的是在 Angular Material 扩展面板中显示每个文件夹:

<mat-expansion-panel *ngIf="dirInfos !== undefined">
  <mat-expansion-panel-header>
    <mat-panel-title>
      {{dirInfos.folderName}}
    </mat-panel-title>
    <mat-panel-description>
      {{dirInfos.dirPath}}
    </mat-panel-description>
  </mat-expansion-panel-header>
  <mat-expansion-panel *ngFor="let dir of dirInfos.dirInfoList">
    <mat-expansion-panel-header>
      <mat-panel-title>
        {{dir.folderName}}
      </mat-panel-title>
      <mat-panel-description>
        {{dir.dirPath}}
      </mat-panel-description>
    </mat-expansion-panel-header>
  </mat-expansion-panel>
  <p *ngFor="let file of dirInfos.fileNames">{{file}}</p>
</mat-expansion-panel>

Image to Visual example

我的问题是文件结构可以很深,即 25 个文件夹。我不知道如何递归检查它,然后生成所需的 HTML,有什么想法吗? ngFor 可能会有帮助,但我不知道有什么方法可以让这项工作生效,即使我在对象上使用 Object.Keys。

您可以使用 keyvalue 管道迭代循环。这样您就可以遍历对象。

所以我们在这里实现的逻辑是当你在 json 中有对象时使用 keyvalue 管道当它是数组时使用简单的 *ngFor 而没有 keyvalue 管道。

<mat-expansion-panel *ngIf="dirInfos !== undefined">
  <mat-expansion-panel-header>
    <mat-panel-title>
      {{dirInfos.folderName}}
    </mat-panel-title>
    <mat-panel-description>
      {{dirInfos.dirPath}}
    </mat-panel-description>
  </mat-expansion-panel-header>
  <mat-expansion-panel *ngFor="let dir of dirInfos.dirInfoList | keyvalue">
    <mat-expansion-panel-header>
      <mat-panel-title>
        {{dir | json}} 
<!-- HERE YOU WILL GET THE DATA WHICH IS SEPARATED INTO IN TO KEY VALUE PAIR   -->
      </mat-panel-title>
      <mat-panel-description>
        {{dir.dirPath}}
      </mat-panel-description>
    </mat-expansion-panel-header>
  </mat-expansion-panel>
  <p *ngFor="let file of dirInfos.fileNames">{{file}}</p>
</mat-expansion-panel>

您可以针对您的用例使用递归模板设计模式。就像 here.

demo