Angular5自定义树组件

问题描述 投票:2回答:1

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

enter image description here

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

tree angular5
1个回答
2
投票

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

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,但你会理解逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.