syncfusion-angular-treeview

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Implementing TreeView in Angular

在Angular中实现TreeView

The TreeView component displays hierarchical data in a tree-like structure with built-in support for interactive features including checkboxes, drag-and-drop, in-place editing, multi-selection, filtering, sorting, templating, and keyboard navigation. It's ideal for displaying file systems, organizational charts, category hierarchies, navigation menus, and any nested data structure.
TreeView组件以树形结构展示层级数据,内置支持多种交互功能,包括复选框、拖放、就地编辑、多选、筛选、排序、模板化和键盘导航。它非常适合展示文件系统、组织结构图、分类层级、导航菜单以及任何嵌套数据结构。

When to Use This Skill

何时使用本技能

  • Building hierarchical UIs: Displaying parent-child data relationships
  • File/folder browsers: Showing directory structures with expand/collapse
  • Navigation structures: Creating menu systems or site hierarchies
  • Data organization: Displaying categorized or nested data
  • Interactive selection: Implementing multi-selection or checkbox-based selection
  • Drag-and-drop interfaces: Reorganizing tree data by dragging nodes
  • Search/filter functionality: Finding nodes in large tree structures
  • Customized appearances: Styling nodes per level or with templates
  • 构建层级UI:展示父子数据关系
  • 文件/文件夹浏览器:显示带有展开/折叠功能的目录结构
  • 导航结构:创建菜单系统或站点层级
  • 数据组织:展示分类或嵌套数据
  • 交互式选择:实现多选或基于复选框的选择
  • 拖放界面:通过拖动节点重新组织树形数据
  • 搜索/筛选功能:在大型树形结构中查找节点
  • 自定义外观:按层级设置节点样式或使用模板

Navigation Guide

导航指南

Choose your task below to navigate to the relevant reference documentation:
选择以下任务,跳转到对应的参考文档:

Getting Started

快速入门

📄 Read: references/getting-started.md
When to read: Setting up TreeView for the first time, installing packages, importing modules, basic component initialization, CSS imports, theme selection, creating your first tree.
📄 阅读: references/getting-started.md
适用场景:首次设置TreeView、安装包、导入模块、基础组件初始化、CSS导入、主题选择、创建第一个树形结构。

Data Binding & Hierarchies

数据绑定与层级结构

📄 Read: references/data-binding.md
When to read: Connecting data sources to TreeView, binding hierarchical or self-referential data, using DataManager, loading data from remote APIs, implementing lazy loading (load on demand), dynamically updating tree data.
📄 阅读: references/data-binding.md
适用场景:将数据源连接到TreeView、绑定层级或自引用数据、使用DataManager、从远程API加载数据、实现懒加载(按需加载)、动态更新树形数据。

Node Selection & Checkboxes

节点选择与复选框

📄 Read: references/node-selection.md
When to read: Enabling checkboxes, managing checkbox states (checked/unchecked/tri-state), implementing multi-selection vs single-selection, using selection events, getting selected node IDs, disabling checkboxes, removing parent checkboxes.
📄 阅读: references/node-selection.md
适用场景:启用复选框、管理复选框状态(选中/未选中/半选)、实现多选与单选、使用选择事件、获取选中节点ID、禁用复选框、移除父节点复选框。

Node Editing & Manipulation

节点编辑与操作

📄 Read: references/node-editing.md
When to read: Enabling in-place editing, adding/removing/updating nodes programmatically, validating edited text, moving nodes, using node manipulation methods (addNodes, removeNodes, updateNode, moveNodes).
📄 阅读: references/node-editing.md
适用场景:启用就地编辑、以编程方式添加/删除/更新节点、验证编辑文本、移动节点、使用节点操作方法(addNodes、removeNodes、updateNode、moveNodes)。

Drag and Drop

拖放功能

📄 Read: references/drag-and-drop.md
When to read: Enabling drag-and-drop functionality, restricting drops on specific nodes, handling drag events, customizing drop indicators, preventing invalid operations.
📄 阅读: references/drag-and-drop.md
适用场景:启用拖放功能、限制在特定节点上放置、处理拖动事件、自定义放置指示器、阻止无效操作。

Templating & Styling Nodes

节点模板与样式

📄 Read: references/templating.md
When to read: Creating custom node templates, using dynamic icons, styling nodes based on level, customizing expand/collapse icons, showing tooltips, handling multi-line nodes, CSS customization.
📄 阅读: references/templating.md
适用场景:创建自定义节点模板、使用动态图标、按层级设置节点样式、自定义展开/折叠图标、显示工具提示、处理多行节点、CSS自定义。

Filtering & Sorting

筛选与排序

📄 Read: references/filtering-sorting.md
When to read: Filtering nodes by text, implementing search functionality, sorting nodes globally or per level, organizing tree display order.
📄 阅读: references/filtering-sorting.md
适用场景:按文本筛选节点、实现搜索功能、全局或按层级排序节点、调整树形显示顺序。

Context Menu Integration

上下文菜单集成

📄 Read: references/context-menu.md
When to read: Adding context menu for node operations, handling right-click actions, implementing add/edit/delete via menu, creating custom menu items.
📄 阅读: references/context-menu.md
适用场景:为节点操作添加上下文菜单、处理右键点击操作、通过菜单实现添加/编辑/删除功能、创建自定义菜单项。

Accessibility, Advanced Features & API Migration

无障碍访问、高级功能与API迁移

📄 Read: references/accessibility-advanced.md
When to read: Keyboard navigation (arrow keys, Enter, Space), ARIA attributes and accessibility compliance, RTL (right-to-left) support, getting child nodes, accordion behavior, advanced methods, migrating from EJ1 to EJ2, performance optimization.
📄 阅读: references/accessibility-advanced.md
适用场景:键盘导航(方向键、Enter、Space)、ARIA属性与无障碍合规、RTL(从右到左)支持、获取子节点、手风琴行为、高级方法、从EJ1迁移到EJ2、性能优化。

Quick Start Example

快速入门示例

Here's a minimal TreeView implementation with static hierarchical data:
typescript
import { Component } from '@angular/core';
import { TreeViewModule } from '@syncfusion/ej2-angular-navigations';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-tree-view',
  standalone: true,
  imports: [FormsModule, TreeViewModule],
  template: `
    <ejs-treeview 
      id="treeView"
      [fields]="treeFields"
      [allowMultiSelection]="true">
    </ejs-treeview>
  `
})
export class TreeViewComponent {
  // Hierarchical data structure
  treeData = [
    {
      id: '01',
      name: 'Documents',
      hasChild: true,
      expanded: true,
      subChild: [
        { id: '01-01', name: 'Work Files' },
        { id: '01-02', name: 'Personal' }
      ]
    },
    {
      id: '02',
      name: 'Downloads',
      hasChild: true,
      subChild: [
        { id: '02-01', name: 'Images' },
        { id: '02-02', name: 'Videos' }
      ]
    }
  ];

  // Field mapping configuration
  treeFields = {
    dataSource: this.treeData,
    id: 'id',
    text: 'name',
    child: 'subChild',
    hasChildren: 'hasChild',
    expanded: 'expanded'
  };
}
以下是使用静态层级数据实现的最简TreeView示例:
typescript
import { Component } from '@angular/core';
import { TreeViewModule } from '@syncfusion/ej2-angular-navigations';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-tree-view',
  standalone: true,
  imports: [FormsModule, TreeViewModule],
  template: `
    <ejs-treeview 
      id="treeView"
      [fields]="treeFields"
      [allowMultiSelection]="true">
    </ejs-treeview>
  `
})
export class TreeViewComponent {
  // Hierarchical data structure
  treeData = [
    {
      id: '01',
      name: 'Documents',
      hasChild: true,
      expanded: true,
      subChild: [
        { id: '01-01', name: 'Work Files' },
        { id: '01-02', name: 'Personal' }
      ]
    },
    {
      id: '02',
      name: 'Downloads',
      hasChild: true,
      subChild: [
        { id: '02-01', name: 'Images' },
        { id: '02-02', name: 'Videos' }
      ]
    }
  ];

  // Field mapping configuration
  treeFields = {
    dataSource: this.treeData,
    id: 'id',
    text: 'name',
    child: 'subChild',
    hasChildren: 'hasChild',
    expanded: 'expanded'
  };
}

Key TreeView Methods

TreeView核心方法

MethodPurpose
addNodes(nodes, target?, index?, preventTargetExpand?)
Add collection of nodes at target position
removeNodes(nodeIds)
Remove nodes by ID
updateNode(target, newText)
Replace node text (requires allowEditing enabled)
moveNodes(sourceNodes, target, index?, preventTargetExpand?)
Move nodes to new parent and index position
getTreeData(nodeId?)
Get all tree data or specific node data
getAllCheckedNodes()
Get all checked node IDs including child nodes whether loaded or not
checkAll(nodes?)
Check all or specific nodes
uncheckAll(nodes?)
Uncheck all or specific nodes
beginEdit(nodeId)
Start editing a node
expandAll(nodes?, level?, excludeHiddenNodes?, preventAnimation?)
Expand all or specific nodes, optionally by level
collapseAll(nodes?, level?, excludeHiddenNodes?)
Collapse all or specific nodes, optionally by level
ensureVisible(nodeId)
Scroll to make node visible
disableNodes(nodeIds)
Disable specific nodes
enableNodes(nodeIds)
Enable specific nodes
getNode(nodeId)
Get HTML element of node
destroy()
Destroy TreeView component
方法用途
addNodes(nodes, target?, index?, preventTargetExpand?)
在目标位置添加节点集合
removeNodes(nodeIds)
通过ID移除节点
updateNode(target, newText)
替换节点文本(需启用allowEditing)
moveNodes(sourceNodes, target, index?, preventTargetExpand?)
将节点移动到新的父节点和位置
getTreeData(nodeId?)
获取所有树形数据或特定节点数据
getAllCheckedNodes()
获取所有选中的节点ID,包括已加载和未加载的子节点
checkAll(nodes?)
选中所有或特定节点
uncheckAll(nodes?)
取消选中所有或特定节点
beginEdit(nodeId)
开始编辑节点
expandAll(nodes?, level?, excludeHiddenNodes?, preventAnimation?)
展开所有或特定节点,可按层级展开
collapseAll(nodes?, level?, excludeHiddenNodes?)
折叠所有或特定节点,可按层级折叠
ensureVisible(nodeId)
滚动到节点使其可见
disableNodes(nodeIds)
禁用特定节点
enableNodes(nodeIds)
启用特定节点
getNode(nodeId)
获取节点的HTML元素
destroy()
销毁TreeView组件

Key TreeView Events

TreeView核心事件

EventTriggered When
created
TreeView component is created
dataBound
Data source binding is complete
dataSourceChanged
Tree data is modified (add/remove/update)
nodeClicked
User clicks on a node
nodeSelected
Node is selected
nodeSelecting
Before node selection (can prevent)
nodeChecked
Checkbox state changes
nodeChecking
Before checkbox changes (can prevent)
nodeExpanding
Before node expansion
nodeExpanded
Node is expanded
nodeCollapsing
Before node collapse
nodeCollapsed
Node is collapsed
nodeEditing
Before node text editing
nodeEdited
After node text is edited
nodeDragStart
Drag operation begins
nodeDragging
Node is being dragged
nodeDragStop
Drag ends before drop
nodeDropped
Node is dropped successfully
drawNode
Before rendering each node (customize appearance)
keyPress
User presses keyboard key
destroyed
TreeView component is destroyed
事件触发时机
created
TreeView组件创建完成时
dataBound
数据源绑定完成时
dataSourceChanged
树形数据被修改(添加/删除/更新)时
nodeClicked
用户点击节点时
nodeSelected
节点被选中时
nodeSelecting
节点选中前触发(可阻止选中)
nodeChecked
复选框状态改变时
nodeChecking
复选框状态改变前触发(可阻止改变)
nodeExpanding
节点展开前触发
nodeExpanded
节点展开后触发
nodeCollapsing
节点折叠前触发
nodeCollapsed
节点折叠后触发
nodeEditing
节点文本编辑前触发
nodeEdited
节点文本编辑完成后触发
nodeDragStart
拖动操作开始时
nodeDragging
节点正在被拖动时
nodeDragStop
拖动结束但未放置时
nodeDropped
节点成功放置时
drawNode
每个节点渲染前触发(可自定义外观)
keyPress
用户按下键盘按键时
destroyed
TreeView组件被销毁时

Common Patterns

常见模式

Pattern 1: Checkbox-Based Selection

模式1:基于复选框的选择

Enable checkboxes for multi-selection with hierarchical checkbox states:
typescript
treeFields = {
  dataSource: this.treeData,
  id: 'id',
  text: 'name',
  child: 'subChild',
  hasChildren: 'hasChild'
};

showCheckBox = true;  // Enable checkboxes
autoCheck = true;     // Parent/child auto-check
启用复选框实现多选,并支持层级复选框联动:
typescript
treeFields = {
  dataSource: this.treeData,
  id: 'id',
  text: 'name',
  child: 'subChild',
  hasChildren: 'hasChild'
};

showCheckBox = true;  // 启用复选框
autoCheck = true;     // 父/子节点自动联动选中

Pattern 2: File Browser with Drag-and-Drop

模式2:带拖放的文件浏览器

Create an interactive file browser with node reorganization:
typescript
<ejs-treeview 
  [fields]="treeFields"
  [allowDragAndDrop]="true"
  [allowMultiSelection]="true"
  (nodeDragging)="onNodeDragging($event)"
  (nodeDropped)="onNodeDropped($event)">
</ejs-treeview>
创建可交互的文件浏览器,支持节点重组织:
typescript
<ejs-treeview 
  [fields]="treeFields"
  [allowDragAndDrop]="true"
  [allowMultiSelection]="true"
  (nodeDragging)="onNodeDragging($event)"
  (nodeDropped)="onNodeDropped($event)">
</ejs-treeview>

Pattern 3: Search and Filter

模式3:搜索与筛选

Implement real-time filtering of tree nodes:
typescript
<input 
  type="text" 
  (keyup)="filterTree($event.target.value)" 
  placeholder="Search nodes...">

<ejs-treeview 
  #treeView
  [fields]="filteredFields">
</ejs-treeview>
实现树形节点的实时筛选:
typescript
<input 
  type="text" 
  (keyup)="filterTree($event.target.value)" 
  placeholder="搜索节点...">

<ejs-treeview 
  #treeView
  [fields]="filteredFields">
</ejs-treeview>

Pattern 4: Editable Tree

模式4:可编辑树形结构

Enable in-place node editing with validation:
typescript
<ejs-treeview 
  [fields]="treeFields"
  [allowEditing]="true"
  (nodeEditing)="onNodeEditing($event)"
  (nodeEdited)="onNodeEdited($event)">
</ejs-treeview>
启用节点就地编辑并支持验证:
typescript
<ejs-treeview 
  [fields]="treeFields"
  [allowEditing]="true"
  (nodeEditing)="onNodeEditing($event)"
  (nodeEdited)="onNodeEdited($event)">
</ejs-treeview>

Key TreeView Properties

TreeView核心属性

PropertyTypePurpose
fields
ObjectConfigures data source mapping (id, text, child, parentID, hasChildren, expanded, isChecked, etc.)
dataSource
ArrayHierarchical or flat data array
allowMultiSelection
BooleanEnable multiple node selection
showCheckBox
BooleanDisplay checkboxes before nodes
autoCheck
BooleanAuto-check children when parent is checked (default: true)
allowDragAndDrop
BooleanEnable drag-and-drop functionality
allowEditing
BooleanEnable in-place node editing
loadOnDemand
BooleanLoad child nodes only when parent expands (default: true)
sortOrder
StringSort order: 'Ascending', 'Descending', or 'None'
cssClass
StringApply custom CSS class for styling
enableRtl
BooleanEnable right-to-left layout support
enablePersistence
BooleanSave and restore TreeView state (expanded nodes, selections)
checkedNodes
ArrayArray of node IDs that should be checked
selectedNodes
ArrayArray of node IDs that should be selected
nodeTemplate
TemplateCustom template for rendering nodes
animation
ObjectConfigure expand/collapse animations
allowKeyboardNavigation
BooleanEnable keyboard navigation (default: true)
属性类型用途
fields
对象配置数据源映射(id、text、child、parentID、hasChildren、expanded、isChecked等)
dataSource
数组层级或扁平数据数组
allowMultiSelection
布尔值启用多节点选择
showCheckBox
布尔值在节点前显示复选框
autoCheck
布尔值选中父节点时自动选中子节点(默认:true)
allowDragAndDrop
布尔值启用拖放功能
allowEditing
布尔值启用节点就地编辑
loadOnDemand
布尔值仅在父节点展开时加载子节点(默认:true)
sortOrder
字符串排序顺序:'Ascending'、'Descending'或'None'
cssClass
字符串应用自定义CSS类进行样式设置
enableRtl
布尔值启用从右到左布局支持
enablePersistence
布尔值保存和恢复TreeView状态(展开节点、选中状态)
checkedNodes
数组应被选中的节点ID数组
selectedNodes
数组应被选中的节点ID数组
nodeTemplate
模板用于渲染节点的自定义模板
animation
对象配置展开/折叠动画
allowKeyboardNavigation
布尔值启用键盘导航(默认:true)

Common Use Cases

常见使用场景

Organizational Chart: Display employee hierarchy with parent-child relationships and custom templates showing roles.
File/Folder Browser: Show directory structure with drag-and-drop to move files between folders.
Category Navigation: Multi-level product categories with checkboxes for filtering and multi-selection.
Settings Menu: Hierarchical preferences or configuration options organized by topic.
Knowledge Base: Nested documentation topics with search and expand/collapse navigation.
组织结构图:展示员工层级关系,使用自定义模板显示角色信息。
文件/文件夹浏览器:展示目录结构,支持拖放功能在文件夹间移动文件。
分类导航:多级产品分类,支持复选框筛选和多选。
设置菜单:按主题组织的层级偏好或配置选项。
知识库:嵌套的文档主题,支持搜索和展开/折叠导航。

Reference Files

参考文件

  • getting-started.md
    - Installation, setup, basic initialization
  • data-binding.md
    - Data sources, hierarchies, remote data, lazy loading
  • node-selection.md
    - Checkboxes, multi-select, selection events
  • node-editing.md
    - Editing, adding, removing, updating nodes
  • drag-and-drop.md
    - Drag-and-drop configuration and restrictions
  • templating.md
    - Custom templates, icons, styling, tooltips
  • filtering-sorting.md
    - Filter, search, and sort functionality
  • context-menu.md
    - Context menu integration and node operations
  • accessibility-advanced.md
    - Keyboard navigation, ARIA, RTL, advanced methods

Next Steps:
  1. Choose your use case from the navigation guide above
  2. Read the relevant reference file
  3. Adapt code examples to your data structure
  4. Test with your data source
  • getting-started.md
    - 安装、设置、基础初始化
  • data-binding.md
    - 数据源、层级结构、远程数据、懒加载
  • node-selection.md
    - 复选框、多选、选择事件
  • node-editing.md
    - 编辑、添加、删除、更新节点
  • drag-and-drop.md
    - 拖放配置与限制
  • templating.md
    - 自定义模板、图标、样式、工具提示
  • filtering-sorting.md
    - 筛选、搜索、排序功能
  • context-menu.md
    - 上下文菜单集成与节点操作
  • accessibility-advanced.md
    - 键盘导航、ARIA、RTL、高级方法

下一步:
  1. 从上方导航指南中选择你的使用场景
  2. 阅读对应的参考文件
  3. 根据你的数据结构调整代码示例
  4. 使用你的数据源进行测试