How to find a node by id in the PrimeNg tree?

1.4k Views Asked by At

We are moving from Angular Tree Component to the PrimeNg Tree component. The tree selection is saved and restored when the application starts. We save the key field (folderId in our case).

Angular Tree Component exposes this method for finding the node:

const node = tree.treeModel.getNodeById(folderId);

After finding the node we can activate it by:

node.setActiveAndVisible();

I was unable to find a similar method for searching the node inside of the PrimeNg Tree. Does someone know what are the alternatives?

1

There are 1 best solutions below

0
On
getNodeWithKey(key: string, nodes: TreeNode[]): TreeNode | undefined {
   for (let node of nodes) {
     if (node.key === key) {
        return node;
     }

     if (node.children) {
       let matchedNode = this.getNodeWithKey(key, node.children);
       if (matchedNode) {
         return matchedNode;
       }
     }
   }
   return undefined;
}

used internally in primeng repository