Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrimeNG Tree - select TreeNode programmatically

I am using the PrimeNG Tree component to enable the users to select some values based on a tree structure. The selected nodes will be later stored in a database and when the user visits the edit dialog again these nodes should be pre selected.

Is there any way to achieve this with the current PrimeNG version? Alternatively it would be nice if you can tell me another angular2 tree component which supports checkbox selection and pre-selection of nodes as well.

like image 558
Chris S. Avatar asked Mar 01 '17 07:03

Chris S.


2 Answers

In selectionMode="checkbox" selected nodes stored in [(selection)]="selectedNodesArray" property.

You can put values from database into selectedNodesArray and this nodes will be selected.

like image 154
Aleksandr Petrovskij Avatar answered Sep 25 '22 08:09

Aleksandr Petrovskij


Here is method to select nodes programmatically:

HTML

<p-tree 
  [value]="list['Entities']" 
  [(selection)]="data['Entities']" 
  selectionMode="checkbox">  
</p-tree>

Method

const selectNodes = (tree: TreeNode[], checkedNodes: TreeNode[], keys: string[]) => {
  // Iterate through each node of the tree and select nodes
  let count = tree.length;
  for (const node of tree) {
    // If the current nodes key is in the list of keys to select, or it's parent is selected then select this node as well
    if (keys.includes(node.key) || checkedNodes.includes(node.parent)) {
      checkedNodes.push(node);
      count--;
    }

    // Look at the current node's children as well
    if (node.children)
      selectNodes(node.children, checkedNodes, keys);
  }

  // Once all nodes of a tree are looked at for selection, see if only some nodes are selected and make this node partially selected
  if (tree.length > 0 && tree[0].parent) tree[0].parent.partialSelected = (count > 0 && count != tree.length);
}

Call to the Method

const keysToBeSelected = [2,3,4]
selectNodes(this.list.Entities, this.filterData.Entities, keysToBeSelected);
like image 41
Nishant Avatar answered Sep 22 '22 08:09

Nishant