1、数据结构(TypeScript)
tree: any[] = [
{
name: 'root',
children: [
{ name: 'child1', children: [] },
{ name: 'child2', children: [] },
{ name: 'child3', children: [] }
// ......
]
}
]
2、HTML
<div>
<ng-template #treeList let-list>
<li *ngFor="let item of list">
<!-- 父元素属性值 -->
<span>{{item.name}}</span>
<!-- ....... -->
<!-- 递归渲染子元素 -->
<ul *ngIf="item.children">
<ng-container *ngTemplateOutlet="treeList; context:{$implicit: item.children}"></ng-container>
</ul>
</li>
</ng-template>
<!-- 调用模板,开始渲染子元素, context 为根节点结构 -->
<ul>
<ng-container *ngTemplateOutlet="treeList; context:{$implicit: tree}"></ng-container>
</ul>
</div>