tree - Angular5 自定义树组件
解决方案
基本上你需要递归调用一个组件。这是一个简单的例子:
节点模型.ts
export class Node {
children: Node[];
text: string;
}
树.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);
}
这是一个没有样式的堆栈闪电战,但您会理解其中的逻辑。
推荐阅读
- jquery - jQuery 事件委托不适用于下拉菜单
- android - 使用 cp -r 意外覆盖了 android 项目目录之间的共享文件
- google-chrome-extension - 将 Chrome 应用程序与 Chrome 扩展程序通信
- linux - pthread_once() 是否支持“链接”另一个 init_routine?
- python - 芹菜运行错误
- php - OneToMany 不保存更改
- android - RxJava2 结合了不同类型的 Observable
- typescript - 图像下载卡在 Angular Firestorage 中的循环中
- regex - 如何捕获正则表达式中的空格
- tensorflow - Tensorflow 错误 - logits 和标签的维度必须相同