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.
In selectionMode="checkbox"
selected nodes stored in [(selection)]="selectedNodesArray"
property.
You can put values from database into selectedNodesArray
and this nodes will be selected.
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);
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