Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand PrimeNg TreeTable by code

Assuming I have a TreeTable provided by PrimeNg for Angular2. How can I expand a particular node in code (for example in onNodeSelect callback)?

like image 448
user4401 Avatar asked Jun 03 '16 14:06

user4401


3 Answers

I guess the OP no longer needs the answer, but for anyone who reaches here and finds no answer -

There is a property expanded for TreeNode, all you need to do is just set it to true

selectedNode.expanded=true;

And if you want the tree to be shown all expanded, just traverse the TreeNodes and set expanded on each. Which will be something similar to this

  expandChildren(node:TreeNode){
    if(node.children){
      node.expanded=true;
      for(let cn of node.children){
        this.expandChildren(cn);
      }
    }
  }
like image 66
prajeesh kumar Avatar answered Nov 10 '22 22:11

prajeesh kumar


Once the code mentioned by prajeesh kumar is executed, to get the tree table refreshed, please add the following line of code:

this.treeNodeData = [...this.treeNodeData];

You can call the expandChildren() method like this:

  expandTreeNodes() {
    if (this.treeNodeData) {
      this.treeNodeData.forEach(x => this.expandChildren(x));

      // Below line is important as it would refresh the TreeTable data,
      // which would force automatic update of nodes and since expanded
      // has been set to true on the expandChildren() method.

      this.treeNodeData = [...this.treeNodeData ]; 
    }
  }
like image 20
Sharath Avatar answered Nov 10 '22 21:11

Sharath


Using above I just wrote function for expanding/collapsing entire treatable nodes.

In my template I am passing entire treetable json to exapandORcollapse

<button type="button" (click)="exapandORcollapse(basicTreeTable)">Collapse /Expand all</button>
 <p-treeTable [value]="basicTreeTable" selectionMode="single" [(selection)]="selectedPortfolio" (onNodeSelect)="nodeSelect($event)"
            (onNodeUnselect)="nodeUnselect($event)" (onRowDblclick)="onRowDblclick($event)" scrollable="true">

In my component.ts file

 exapandORcollapse(nodes) {
    for(let node of nodes) 
  { 
    if (node.children) {
        if(node.expanded == true)
          node.expanded = false;
          else
          node.expanded = true;
        for (let cn of node.children) {
            this.exapandORcollapse(node.children);
        }
    }
  }
}
like image 1
PPB Avatar answered Nov 10 '22 23:11

PPB