2

How to create a custom tree component in angular 5.I am a beginner in angular.I have no idea.

enter image description here

"+" Button create new node and "Add Route" Button create sub node. Each node contains two drop down to select values.

1 Answer 1

2

Basically you need to recursively call a component. Here is a simple example:

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);
  }

and the node.component.ts, which is called recursively :

@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);
  }

Here is a stackblitz without styles but you will understand the logic.

Sign up to request clarification or add additional context in comments.

5 Comments

In my api response children are not array.
"flow":{ "children":{ "2":{ "children":{}, "data":{"id":"ggfg"}, }, "4":{ "children":{ "7":{ "children":{}, "data":{"id":"effgfdv"}, } }, "data":{"id":"fgdfgdg"}, } }, "data":{"id":"fghhhj"}, },
Is any way to convert to json to array
Yes, you can do it front-end side, maybe using a recursive function too. You could have a look at lodash for Objects/Arrays handling.
Can you help me to do the same with netsted node, I am using nested JSON

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.