基本上你需要递归调用一个组件。这是一个简单的例子:
node.model.ts
export class Node {
children: Node[];
text: string;
}
tree.component.ts
@Component({
selector: 'tree',
template: `<h1>Tree component</h1>
<div *ngFor="let node of tree">
<node [node]="node"></node>
</div>
<button (click)="addNodeTo()">add node</button>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class TreeComponent implements OnInit {
tree: Node[] = [];
ngOnInit(){
let firstNode = {
children: [],
text: 'first'
}
this.tree.push(firstNode);
}
addNodeTo(){
let newNode = {
children: [],
text: 'newNode',
}
this.tree.push(newNode);
}
和node.component.ts,递归调用:
@Component({
selector: 'node',
template: `
{{node.text}} <button (click)="addChildren(node)">Add children</button>
<div *ngFor="let children of node.children">
<node [node]='children'></node>
</div>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class NodeComponent implements OnInit {
@Input() node: Node;
ngOnInit(){
}
addChildren(node: Node){
let newNode = {
children: [],
text: node.text + `'s child`
}
node.children.push(newNode);
}
这是一个没有风格的stackblitz,但你会理解逻辑。