如何通过代码扩展PrimeNg TreeTable

How to expand PrimeNg TreeTable by code

假设我有一个由 PrimeNg 为 Angular2 提供的 TreeTable。如何在代码中扩展特定节点(例如在 onNodeSelect 回调中)?

我想 OP 不再需要答案,但是对于到达这里却找不到答案的任何人 -

TreeNode有一个属性expanded,你只需要设置为true

selectedNode.expanded=true;

如果您希望树全部展开显示,只需遍历 TreeNodes 并在每个节点上设置展开。这将与此类似

  expandChildren(node:TreeNode){
    if(node.children){
      node.expanded=true;
      for(let cn of node.children){
        this.expandChildren(cn);
      }
    }
  }

使用上面我只是为 expanding/collapsing 整个可治疗节点编写函数。

在我的模板中,我将整个树表 json 传递给 exapandORcollapse

<button type="button" (click)="exapandORcollapse(basicTreeTable)">Collapse /Expand all</button>
 <p-treeTable [value]="basicTreeTable" selectionMode="single" [(selection)]="selectedPortfolio" (onNodeSelect)="nodeSelect($event)"
            (onNodeUnselect)="nodeUnselect($event)" (onRowDblclick)="onRowDblclick($event)" scrollable="true">

在我的 component.ts 文件中

 exapandORcollapse(nodes) {
    for(let node of nodes) 
  { 
    if (node.children) {
        if(node.expanded == true)
          node.expanded = false;
          else
          node.expanded = true;
        for (let cn of node.children) {
            this.exapandORcollapse(node.children);
        }
    }
  }
}

我做了同样的事情,但我将同一个树对象克隆到自身并且它起作用了。

this.treeData.forEach((node) => {this.expandRecursive(node, true);});
this.treeData = _.cloneDeep(this.treeData);

执行 prajeesh kumar 提到的代码后,要刷新树 table,请添加以下代码行:

this.treeNodeData = [...this.treeNodeData];

您可以像这样调用 expandChildren() 方法:

  expandTreeNodes() {
    if (this.treeNodeData) {
      this.treeNodeData.forEach(x => this.expandChildren(x));

      // Below line is important as it would refresh the TreeTable data,
      // which would force automatic update of nodes and since expanded
      // has been set to true on the expandChildren() method.

      this.treeNodeData = [...this.treeNodeData ]; 
    }
  }