You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PrimeNG p-treeTable需双击才能展开问题求助

解决PrimeNG p-treeTable点击两次才展开的问题

问题根源

你同时绑定了onLazyLoad和onNodeExpand到同一个方法,且开启了dynamic="true"动态加载模式。第一次点击时,onLazyLoad触发加载子节点数据,但节点的展开状态未同步更新;第二次点击时数据已加载完成,才会触发节点展开的UI变化,导致需要两次点击才能生效。

解决方案

  1. 移除重复事件绑定
    动态加载模式下,onLazyLoad会在节点首次点击展开时自动触发,无需再绑定onNodeExpand到同一个方法,否则会造成逻辑冲突。修改后的HTML代码:
<p-treeTable *ngIf="treeNode?.length > 0" [value]="treeNode" dynamic="true" (onLazyLoad)="editNodeExpand($event)">
  <ng-template pTemplate="header">
    <tr>
      <th>Crop Name</th>
      <th>CCE Planned</th>
      <th>CCE Completed </th>
      <th>State Approved </th>
      <th>Central Approved </th>
      <th>Average Yield (Kg/Ha) </th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-rowNode let-rowData="rowData">
    <tr class="addColor" [ttRow]="rowNode">
      <td>
        <p-treeTableToggler *ngIf="rowNode.node.children || !rowNode.node.leaf" [rowNode]="rowNode"></p-treeTableToggler>
        {{rowNode?.node?.label}}
      </td>
      <td>{{rowNode?.node?.plannedCCE}}</td>
      <td>{{rowNode?.node?.completedCCECount}}</td>
      <td>{{rowNode?.node?.totalStateApproval}}</td>
      <td>{{rowNode?.node?.totalCentralApproval}}</td>
      <td>{{rowNode?.node?.averageYield}}</td>
    </tr>
  </ng-template>
</p-treeTable>
  1. 修改editNodeExpand方法,同步节点展开状态
    加载完子节点数据后,手动设置当前节点的expanded为true,并用不可变方式更新treeNode数组,确保Angular检测到变化并更新UI:
editNodeExpand(event: any) {
  const node = event.node;
  // 替换为实际的子节点加载请求
  this.yourDataService.getChildNodes(node.key).subscribe((childNodes) => {
    node.children = childNodes;
    // 手动标记节点为展开状态
    node.expanded = true;
    // 不可变更新数组,触发Angular变更检测
    this.treeNode = [...this.treeNode];
  });
}
  1. 规范节点结构
    给每个节点明确设置leaf属性:叶子节点(无下级节点)设leaf: true,非叶子节点设leaf: false,让PrimeNG能准确识别节点是否可展开,避免交互异常。

内容的提问来源于stack exchange,提问作者Sourabh Bisht

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 19:47:14