2

I need to show a tree from a flat array of data using Angular and I'm open to use any package to render the tree. as a user, I should be able to click on a node and find out details such as node ID and title. the tree should be expanded on load but users should be able to collapse parent nodes as they wish. my node data model looks like below:

export class Node {
    nodeID: number;
    title: string;
    parentNodeID: number;
}

and my data looks like this:

public Nodes: Node[] = [
    {
        nodeID: 1;
        title: parent1;
        parentNodeID: null;
    },
    {
        nodeID: 2;
        title: child1;
        parentNodeID: 1;
    },
    {
        nodeID: 3;
        title: child2;
        parentNodeID: 1;
    }
]

2 Answers 2

0

you need a recursive algorithm that looks loops through your flat array and maps parentNodeID to Node to generate tree structure and then use a tree component, for example angular-tree-component, to render your tree. I made a demo on stackblitz. have a look and let me know if it helped. https://stackblitz.com/github/ramin-ahmadi/Flat-Tree

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

Comments

0

There is plenty of package that could do the job, for example This one. I did not tried it but seems easy to use. If you can, change your keys in your array. Else, then just map your items into another array, something like:

const newArray = array.map(item =>({
      id: item.nodeID,
      name: item.title,
      children: array.filter(el => el.parentNodeID === parentId), // Not sure about that, but this is the idea
    })
  );

newArray wil be the data provided to your three.

2 Comments

Thanks Quentine. what is the complexity of your solution?
What do you mean by complexity ? As I said i didn't tried it, but it look kinda easy. Look at the doc here: angular2-tree.readme.io/docs. Now, it was an example, find the tree builder that suits your needs :)

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.