使用自定义模板渲染无限树

Rendering an infinite tree with custom template

这可能是一个 common/simple 问题,但我是 angular 的新手。所以,我陷入了这个。

我正在尝试构建一个应用程序,该应用程序需要从无限嵌套的数据结构中呈现列表(无限嵌套是指未知数量的嵌套)。在遵循 this article 之后,我已经能够在 html 代码中进行递归。

因此,基本思路是提供一个数据和一个递归键,并将组件标签放在组件模板本身中。 (基本递归)

但我想创建一个通用组件,其中可以在 application/implementation 级别定义单元格布局。

到目前为止我构建了什么 -

novo-rec-list-view.component

<div *ngIf="dataSource.length">
<div *ngFor="let item of dataSource">
    <ng-template [ngTemplateOutlet]="itemTemplate" [ngTemplateOutletContext]="{ $implicit: item }"></ng-template>
    <novo-rec-list-view [recursionKey]="recursionKey" [dataSource]="item[recursionKey]"></novo-rec-list-view>
</div>

并且我将此组件用作 -

<novo-rec-list-view 
        id="change-log-list" 
        [recursionKey]="recursionKey"
        [dataSource]="treeNodeList">
    <ng-template #itemTemplate let-item="$implicit" let-i="index">
      <change-log-cell [item]="item">
      </change-log-cell>
    </ng-template>
</novo-rec-list-view>

其中 change-log-cell 包含单元格的布局。

这在angular4中可以实现吗?有人可以为我提供一些有关如何执行此操作的指示吗?

基于上述代码的最小工作应用程序 - https://stackblitz.com/edit/angular-snub7u?embed=1&file=src/app/app.component.ts

PS - 无法实现递归,因此不会显示内部元素。

根据您上面的回答,我将为您提出 2 个想法。不确定两者是否都能满足您的需求。如果没有,我可以集思广益并编辑此答案。

如果您需要一个基本的通用组件并且需要根据项目输入中的某些细节修改它周围的样式,您可以使用 ngClass 或任何其他方法来动态更改样式绑定。我将您链接到下面一篇非常有用的文章:

https://scotch.io/tutorials/the-many-ways-to-use-ngclass

根据对 html 的更改的复杂程度,您可以做的另一件事是在 change-log-cell 中创建多个模板(我不确定您是否想这样做)和然后使用 ngSwitch 关闭项目输入中需要的任何内容,以确定要在 html 中呈现的切换情况。将您指向有关其工作原理的官方 Angular 文档:

https://angular.io/api/common/NgSwitch