NG-ZORRO中tree组件的getCheckedNodeList怎么使用

在 NG-ZORRO(Ant Design for Angular) 的 Tree 组件 中,getCheckedNodeList 方法用于获取当前选中的节点列表(包括半选状态节点)。以下是具体用法和示例:

  1. 基本用法
    首先,确保你已通过 ViewChild 获取了 Tree 组件的实例(通常是 NzTreeComponent 或 NzTreeSelectComponent)。

模板中定义 Tree

html 复制代码
<nz-tree
  #tree
  [nzData]="nodes"
  nzCheckable
  [(nzCheckedKeys)]="checkedKeys"
  (nzCheckBoxChange)="onCheckboxChange($event)"
></nz-tree>

组件中调用方法

typescript 复制代码
import { Component, ViewChild } from '@angular/core';
import { NzTreeComponent, NzTreeNode } from 'ng-zorro-antd/tree';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.html'
})
export class YourComponent {
  @ViewChild('tree') tree!: NzTreeComponent; // 获取 Tree 实例
  nodes: NzTreeNode[] = [ /* 你的树节点数据 */ ];
  checkedKeys: string[] = []; // 选中的节点 key 数组

  // 获取所有选中的节点(包括半选节点)
  getCheckedNodes(): void {
    const checkedNodes: NzTreeNode[] = this.tree.getCheckedNodeList();
    console.log('Checked Nodes:', checkedNodes);
  }

  // 如果需要仅获取全选节点(忽略半选节点)
  getFullyCheckedNodes(): void {
    const fullyCheckedNodes: NzTreeNode[] = this.tree.getCheckedNodeList(true);
    console.log('Fully Checked Nodes:', fullyCheckedNodes);
  }
}
  1. 方法参数说明
    getCheckedNodeList(includeHalfChecked?: boolean): NzTreeNode[]

includeHalfChecked(可选,默认 false):

false:仅返回 全选节点(用户明确勾选的节点)。

true:返回 全选 + 半选节点(例如父节点因部分子节点被选中而半选)。

  1. 关键注意事项
    节点数据格式

确保 nzData 中的节点数据正确绑定,且每个节点有唯一的 key。例如:

typescript 复制代码
nodes = [
  new NzTreeNode({
    title: 'Parent',
    key: '1',
    children: [
      { title: 'Child 1', key: '1-1' },
      { title: 'Child 2', key: '1-2' }
    ]
  })
];

动态更新问题

如果节点是异步加载的,调用 getCheckedNodeList 前需确保数据已渲染(可在 setTimeout 或数据加载完成的回调中调用)。

与 nzCheckedKeys 的区别

nzCheckedKeys 是双向绑定的选中 key 数组,而 getCheckedNodeList 返回的是完整的节点对象(包含 title、children 等属性)。

  1. 完整示例
typescript 复制代码
// 模板
<button (click)="logCheckedNodes()">打印选中节点</button>

// 组件
logCheckedNodes(): void {
  const allChecked = this.tree.getCheckedNodeList(); // 全选 + 半选
  const fullyChecked = this.tree.getCheckedNodeList(true); // 仅全选
  console.log('All Checked Nodes:', allChecked);
  console.log('Fully Checked Nodes:', fullyChecked);
}

通过以上方法,你可以轻松获取 Tree 组件的选中状态。如果需要进一步处理节点数据,可以通过 NzTreeNode 的 API(如 getParentNode()、getChildren() 等)操作节点关系。

相关推荐
Jing_Rainbow5 小时前
【 前端三剑客-37 /Lesson61(2025-12-09)】JavaScript 内存机制与执行原理详解🧠
前端·javascript·程序员
UIUV6 小时前
模块化CSS学习笔记:从作用域问题到实战解决方案
前端·javascript·react.js
Kakarotto6 小时前
使用ThreeJS绘制东方明珠塔模型
前端·javascript·vue.js
donecoding6 小时前
TypeScript `satisfies` 的核心价值:两个例子讲清楚
前端·javascript
Van_Moonlight6 小时前
RN for OpenHarmony 实战 TodoList 项目:顶部导航栏
javascript·开源·harmonyos
技术狂小子6 小时前
前端开发中那些看似微不足道却影响体验的细节
javascript
用户12039112947266 小时前
使用 Tailwind CSS 构建现代登录页面:从 Vite 配置到 React 交互细节
前端·javascript·react.js
花归去7 小时前
echarts 柱状图曲线图
开发语言·前端·javascript
老前端的功夫7 小时前
TypeScript 类型魔术:模板字面量类型的深层解密与工程实践
前端·javascript·ubuntu·架构·typescript·前端框架
Nan_Shu_6147 小时前
学习: Threejs (2)
前端·javascript·学习