using ng-template
is the best solution to solve recursive DOM problems.
@Component({
selector: 'tree-node',
template: `
<ng-container *ngTemplateOutlet="tree;context:{node:node}">
</ng-container>
<ng-template #tree let-node="node">
<div>{{node.name}}</div>
<ul *ngIf="node.children && node.children.length > 0">
<ng-container *ngFor="let child of node.children">
<li>
<ng-container *ngTemplateOutlet="tree;context:{node:child}">
</ng-container>
</li>
</ng-container>
</ul>
</ng-template>
`
})
export class TreeNode {
@Input() node;
}
No needs to add the component to directives: []
in its @Component()
.
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<tree-node [node]="node"></tree-node>
</div>
`
})
export class App {
node = {
name: 'root', children: [
{ name: 'a', children: [] },
{
name: 'b', children: [
{ name: 'b-1', children: [] },
{
name: 'b-2', children: [
{ name: 'b-2-1', children: [] },
{ name: 'b-2-2', children: [] },
{ name: 'b-2-3', children: [] }
]
}
]
},
{
name: 'c', children: [
{ name: 'c-1', children: [] },
{ name: 'c-2', children: [] }
]
},
]
};
}
Output:
HTML:
<tree-node>
<div>root</div>
<ul>
<li>
<div>a</div>
</li>
<li>
<div>b</div>
<ul>
<li>
<div>b-1</div>
</li>
<li>
<div>b-2</div>
<ul>
<li>
<div>b-2-1</div>
</li>
<li>
<div>b-2-2</div>
</li>
<li>
<div>b-2-3</div>
</li>
</ul>
</li>
</ul>
</li>
<li>
<div>c</div>
<ul>
<li>
<div>c-1</div>
</li>
<li>
<div>c-2</div>
</li>
</ul>
</li>
</ul>
</tree-node>