我想构建一个显示列表中项目的 UI,并在列表中的其他列中显示其他详细信息。当某个项目包含子项目时,我可以展开该项目,并将额外的行插入到表中,并且项目的名称将缩进,但其余列正常显示。
挑战在于,树结构通常是递归完成的。但是您不能让节点作为子行的父节点,否则会破坏表格。
我能够获得概念证明,如下所示:
<table>
<thead>
<th>Item Name</th>
<th>Summary</th>
<th>Priority</th>
</thead>
<ng-template ngFor let-root [ngForOf]="['a','b','c']">
<tr>
<td style="padding-left: 0;">{{root}}</td>
<td>Summary for {{root}}</td>
<td>None</td>
</tr>
<ng-template ngFor let-child [ngForOf]="['1','2','3']">
<tr>
<td style="padding-left: 1em;">{{child}}</td>
<td>Summary for {{child}}</td>
<td>None</td>
</tr>
</ng-template>
</ng-template>
</table>
这有效是因为 <ng-template>
不呈现为 DOM 中的节点。
接下来我尝试创建一个组件来表示这个概念:
<tr>
<td style="padding-left: calc({{depth}}*1em);">
{{item.nodeName()}}
</td>
<td *ngIf="details">{{item.summary}}</td>
<td *ngIf="details">{{item.priority_name}}</td>
</tr>
<tr *ngIf="loading">
<td *ngIf="details" style="padding-left: calc({{depth+1}}*1em);" colspan=3>Loading...</td>
<td *ngIf="! details" style="padding-left: calc({{depth+1}}*1em);">Loading...</td>
</tr>
<ng-template ngFor let-child [ngForOf]="item.children">
<item-node [item]="child" depth="depth+1" [details]="details"></item-node>
</ng-template>
不幸的是,这不起作用,因为 <item-node>
在 DOM 中创建一个破坏表格的节点。
有没有一种方法可以做到这一点,并且不会在 DOM 中插入无关的节点?
最佳答案
解决方案是使用<ng-template>
和<ng-container>
,创建一个递归模板,如下所示:
<ng-template #node>
<tr><!-- current node --></tr>
<ng-container *ngIf="expanded">
<ng-container ngFor let-child [ngForOf]="children">
<ng-container *ngTemplateOutlet="node; context:child"></ng-container>
</ng-container>
</ng-container>
</ng-template>
<table>
<thead><!-- column headers --></thead>
<ng-container *ngTemplateOutlet="node; context: root"></ng-container>
</table>
还有更多细节需要解决,比如如何让缩进起作用(你需要跟踪深度,并添加根据深度缩进的样式),你必须传入变量但根本问题,即如何避免 DOM 中出现不必要的元素,可以使用 <ng-container>
解决。并且子节点是通过使用递归来处理的 <ng-template>
代替独立组件。
阅读<ng-template>
和<ng-container>
了解详情。
关于javascript - 如何在表的列中嵌入树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46975824/