Developer Thing
Developer Thing

Reputation: 2774

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

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?

Upvotes: 1

Views: 1786

Answers (1)

Džan Operta
Džan Operta

Reputation: 493

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

Upvotes: 3

Related Questions