user4401
user4401

Reputation: 446

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)?

Upvotes: 11

Views: 20657

Answers (4)

Sharath
Sharath

Reputation: 606

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

Upvotes: 3

Amey Rao
Amey Rao

Reputation: 1

I did the same but I cloned the same tree object to itself and it worked.

this.treeData.forEach((node) => {this.expandRecursive(node, true);});
this.treeData = _.cloneDeep(this.treeData);

Upvotes: 0

PPB
PPB

Reputation: 287

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

Upvotes: 1

prajeesh kumar
prajeesh kumar

Reputation: 1966

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

Upvotes: 23

Related Questions