Anamika Yadav
Anamika Yadav

Reputation: 63

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.

Upvotes: 0

Views: 3796

Answers (2)

Chinmoy Acharjee
Chinmoy Acharjee

Reputation: 550

Based on the answer from @malbarmavi, You can hide certain node using styleClass property in TreeNode.

getTreeNode(treeNodes: any[]): TreeNode[] {
    return treeNodes.map(i => {
       i.styleClass = !!i.visible? '' : 'display-none';
       return i;
    }).map(i => {
        if (i.children) {
            i.children = this.getTreeNode(i.children);
        }
        return i;
    });

 }

and in style.css, add following css,

.display-none {
    display: none
}

So, you can still have the elements even after hiding them.

Thanks.

Upvotes: 3

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24464

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 🚀

Upvotes: 2

Related Questions