【问题标题】:PrimeNG Tree - select TreeNode programmaticallyPrimeNG 树 - 以编程方式选择 TreeNode
【发布时间】:2017-07-20 10:30:00
【问题描述】:

我正在使用 PrimeNG Tree 组件使用户能够基于树结构选择一些值。选定的节点稍后将存储在数据库中,当用户再次访问编辑对话框时,应预先选择这些节点。

目前的 PrimeNG 版本有什么方法可以实现这一点吗?或者,如果您能告诉我另一个支持复选框选择和节点预选的 angular2 树组件,那就太好了。

【问题讨论】:

    标签: angular typescript tree primeng


    【解决方案1】:

    selectionMode="checkbox" 中选择的节点存储在[(selection)]="selectedNodesArray" 属性中。

    您可以将数据库中的值放入selectedNodesArray,然后将选择此节点。

    【讨论】:

    • 感谢您的回答,现在可以了!刚刚学习 Angular2,却忘记了它应该以这种方式工作。甚至将其用于自定义组件...:D
    • 如何将树存储在数据库中?当我使用 post 存储并运行 Json.stringify () 时遇到问题,由于父母和孩子,我收到循环引用错误。
    • 这在父子模型中如何工作?我的意思是如果一个节点有 2 个子节点,1 个被选中而另一个没有,那么父节点应该在哪个数组上?
    • 这让我们可以选择一个节点,但是您不能取消选择该节点。有什么办法可以以编程方式删除选择?
    • @JayeshDhandha 问题是关于 PrimeNG 而你链接的问题是 Primefaces 票。他们不一样
    【解决方案2】:

    这是以编程方式选择节点的方法:

    HTML

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

    方法

    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);
    }
    

    调用方法

    const keysToBeSelected = [2,3,4]
    selectNodes(this.list.Entities, this.filterData.Entities, keysToBeSelected);
    

    【讨论】:

    • 但是 node.parent 来自哪里?在初始数据集中,此属性为空,但在填充树后“神奇地”填充。第一次调用您的代码时, node.parent 将未定义,并且不会检查父母。你能解释一下你是如何解决这个问题的吗?
    【解决方案3】:

    找到了在 PrimeNG Tree 中预选多个复选框(以编程方式)的解决方法。你可以在这里找到工作示例:https://github.com/jigneshkhatri/primeng-treenode-preselect

    【讨论】:

      【解决方案4】:

      使用“复选框”设置 selectionMode 属性,如下所示:

      <p-tree
       selectionMode="checkbox"
       [(selection)]="selectedNodes"
        ></p-tree>
      

      selectedNodes 变量包含选定的节点。在此变量中添加您要选择的所有节点。

      【讨论】:

        猜你喜欢
        • 2019-07-18
        • 2018-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-05
        • 2011-09-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多