Assuming I have a TreeTable provided by PrimeNg for Angular2. How can I expand a particular node in code (for example in onNodeSelect
callback)?
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);
}
}
}
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 ];
}
}
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);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With