【问题标题】:How do I bind the tree structure UI using endless JSON - Angular 8如何使用无尽的 JSON 绑定树结构 UI - Angular 8
【发布时间】:2020-08-07 02:12:32
【问题描述】:

我有一个 JSON 结构。它包含每个对象的子数组。有些子数组可能有一个值,有时它没有。

我的问题是如何使用以下 JSON 创建树视图:

this.fileList = [
  {
    "name": "New Folder1",
    "children": [
      {
        "name": "New Folder4",
        "children": [
          {
            "name": "New File",
            "children": []
          },
          {
            "name": "New File",
            "children": []
          }
        ]
      },
      {
        "name": "New Folder7",
        "children": []
      }
    ]
  },
  {
    "name": "New Folder2",
    "children": [
      {
        "name": "File1",
        "children": []
      }
    ]
  },
  {
    "name": "New Folder3",
    "children": [
      {
        "name": "New Folder5",
        "children": [
          {
            "name": "New File",
            "children": []
          },
          {
            "name": "New File",
            "children": []
          }
        ]
      }
    ]
  },
  {
    "name": "File1",
    "children": []
  }
]

我的最终输出应该像这样显示在我的屏幕上。 (注意:那些箭头,等号等不是强制性的。它只是你的参考。我只需要树视图,没有任何材料。我需要通过使用ngFor,ngIf等其他一些条件来实现这一点,包括CSS) .

->Folder A
    =>Folder B
        --Folder C
        --Folder D
    =>Folder E
        --Folder F
->Folder G
    =>Folder H
        --Folder I
->Folder J
    =>Folder K
    =>Folder L

我希望你们明白我想要什么。请帮我解决这个问题。提前致谢:)

【问题讨论】:

    标签: angular binding treeview ngfor angular-ng-if


    【解决方案1】:

    在 Angular 中你可以使用模板引用来实现这个嵌套视图。这里是代码 sn-p 例如:

    <ng-template #folderTemplate let-folder>
    
        <-- BIND DATA OF FOLDER OBJECT-->
    
        <div *ngIf="folder.children" class="children-folder">
            <!-- Invoke the recursive template. -->
            <ng-template [ngTemplateOutlet]="folderTemplate"
                [ngTemplateOutletContext]="{ $implicit: folder.children }">
                <!--
                    HACK: The "$implicit" property of the ngFor context is what will
                    be made available to the template ref's implicit let-query binding.
                -->
            </ng-template>
        </div>
    </ng-template>
    <ng-template [ngTemplateOutlet]="folderTemplate" [ngTemplateOutletContext]="{ $implicit: rootFolderObject }">
    </ng-template>
    

    这里 rootFolderObject 将是您在每个子节点上的主要数据集,模板引用将被填充。您可以迭代子嵌套列表并将 foldetTemplate 中的数据与 folder 对象绑定。

    【讨论】:

    • 谢谢! .我集成了这段代码。我在哪里添加 JSON 结构?我无法得到它。你能解释一下吗。我将结构命名为 this.fileList。
    猜你喜欢
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 2015-07-20
    • 2015-01-19
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    相关资源
    最近更新 更多