在 NG-ZORRO(Ant Design for Angular) 的 Tree 組件 中,getCheckedNodeList 方法用于獲取當前選中的節點列表(包括半選狀態節點)。以下是具體用法和示例:
- 基本用法
首先,確保你已通過 ViewChild 獲取了 Tree 組件的實例(通常是 NzTreeComponent 或 NzTreeSelectComponent)。
模板中定義 Tree
<nz-tree#tree[nzData]="nodes"nzCheckable[(nzCheckedKeys)]="checkedKeys"(nzCheckBoxChange)="onCheckboxChange($event)"
></nz-tree>
組件中調用方法
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);}
}
- 方法參數說明
getCheckedNodeList(includeHalfChecked?: boolean): NzTreeNode[]
includeHalfChecked(可選,默認 false):
false:僅返回 全選節點(用戶明確勾選的節點)。
true:返回 全選 + 半選節點(例如父節點因部分子節點被選中而半選)。
- 關鍵注意事項
節點數據格式
確保 nzData 中的節點數據正確綁定,且每個節點有唯一的 key。例如:
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 等屬性)。
- 完整示例
// 模板
<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() 等)操作節點關系。