Search code examples
angularprimengboost-propertytree

PrimeNG p-tree: How to hide certain node from ptree on basis of a boolean value coming from json file?


I am using primeng tree to display json data like this:

<p-tree [value]='dataToDisplayFromConfig' selectionMode='checkbox' [(selection)]='selectedData'>

The JSON data is being read into dataToDisplayFromConfig. I want to make certain nodes invisible on basis of visible property that comes from this json:

[
    {
        "label": "f",
        "children": [
            {
                "label": "",
                "visible": true,
                "data": "f"
            },
            {
                "label": "s",
                "visible": false,
                "data": "s"
            }            
        ]
    }
]

how can we achieve it?

Thanks, in advance.


Solution

  • TreeNode interface has no options to hide or show an item so you have to create a function that filter the children nodes and return the visible only

    I have update the interface to include the visible option like this

    export interface NewTreeNode extends TreeNode {
      visible?: boolean;
      children?: NewTreeNode[];
    }
    

    getValidTreeNodeItems method will loop throw the node and sub node and remove any node with visible equal false

      getValidTreeNodeItems(treeNodes: NewTreeNode[]): NewTreeNode[] {
        const validItems = treeNodes.filter(i => i.visible !== false);
    
        validItems.forEach(i => {
          if (i.children) {
            i.children = this.getValidTreeNodeItems(i.children);
          }
        });
    
        return validItem;
      }
    

    demo 🚀