首页 > 解决方案 > Angular5 自定义树组件

问题描述

如何在 Angular 中创建自定义树组件 5.我是 Angular 的初学者。我不知道。

在此处输入图像描述

“+”按钮创建新节点,“添加路由”按钮创建子节点。每个节点包含两个下拉列表以选择值。

标签: treeangular5

解决方案


基本上你需要递归调用一个组件。这是一个简单的例子:

节点模型.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);
  }

这是一个没有样式的堆栈闪电战,但您会理解其中的逻辑。


推荐阅读