Search code examples
arraysangulartreeflat

how to create tree from flat array using in Angular


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

Solution

  • 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