syncfusion-angular-treegrid

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Syncfusion Angular TreeGrid

Syncfusion Angular TreeGrid

Complete guide to implementing and customizing the Syncfusion Angular TreeGrid component for hierarchical data visualization.
这是一份在Angular中实现和自定义Syncfusion Angular TreeGrid组件以展示层级数据的完整指南。

Table of Contents

目录

When to Use This Skill

何时使用该技能

Use this skill when you need to:
  • Display hierarchical or tree-structured data in a grid format
  • Implement advanced data manipulation (sorting, filtering, searching, editing)
  • Configure pagination, virtual scrolling for large datasets
  • Add export functionality (PDF, Excel)
  • Customize appearance with themes and CSS
  • Handle selection, aggregates, and state management
  • Support mobile/responsive design
  • Implement row/column freezing
在以下场景中使用该技能:
  • 以网格格式展示层级或树形结构的数据
  • 实现高级数据操作(排序、筛选、搜索、编辑)
  • 为大型数据集配置分页、虚拟滚动
  • 添加导出功能(PDF、Excel)
  • 通过主题和CSS自定义外观
  • 处理选择、聚合和状态管理
  • 支持移动端/响应式设计
  • 实现行/列冻结

Mandatory Rules

强制规则

Rule 1: childMapping is MANDATORY for Hierarchical Data

规则1:childMapping是层级数据的必填项

Severity: 🔴 CRITICAL - Grid will not expand/collapse without this
Requirement:
typescript
// ✅ REQUIRED - Must match data property name exactly
<ejs-treegrid 
  [dataSource]='data'
  childMapping='subtasks'>  // Property name is case-sensitive
</ejs-treegrid>

// ❌ WRONG - Will not work
<ejs-treegrid 
  [dataSource]='data'>
  <!-- No expansion possible without childMapping -->
</ejs-treegrid>
Data Format:
typescript
// ✅ CORRECT - childMapping matches 'subtasks' property
public data = [
  {
    TaskID: 1,
    TaskName: 'Parent',
    subtasks: [  // Must match childMapping value
      { TaskID: 2, TaskName: 'Child' }
    ]
  }
];
Exception: Use
idMapping
+
parentIdMapping
for flat parent-child structure:
typescript
// Alternative: Flat structure with parent IDs
<ejs-treegrid 
  [dataSource]='flatData'
  idMapping='TaskID'
  parentIdMapping='ParentID'
  hasChildMapping='isParent'>
</ejs-treegrid>

严重程度:🔴 关键 - 不设置该属性,网格将无法展开/折叠
要求
typescript
// ✅ 必填 - 必须与数据属性名称完全匹配
<ejs-treegrid 
  [dataSource]='data'
  childMapping='subtasks'>  // 属性名称区分大小写
</ejs-treegrid>

// ❌ 错误 - 无法正常工作
<ejs-treegrid 
  [dataSource]='data'>
  <!-- 没有childMapping则无法展开 -->
</ejs-treegrid>
数据格式
typescript
// ✅ 正确 - childMapping与'subtasks'属性匹配
public data = [
  {
    TaskID: 1,
    TaskName: '父级任务',
    subtasks: [  // 必须与childMapping的值匹配
      { TaskID: 2, TaskName: '子任务' }
    ]
  }
];
例外情况:对于扁平的父子结构,使用
idMapping
+
parentIdMapping
typescript
// 替代方案:带父ID的扁平结构
<ejs-treegrid 
  [dataSource]='flatData'
  idMapping='TaskID'
  parentIdMapping='ParentID'
  hasChildMapping='isParent'>
</ejs-treegrid>

Rule 2: Data Type Matching is MANDATORY

规则2:数据类型匹配是必填项

Severity: 🟠 IMPORTANT - Type mismatches cause rendering/sorting issues
Requirement:
typescript
// ✅ CORRECT - Type matches column definition
public data = [
  {
    TaskID: 1,              // number type
    TaskName: 'Planning',   // string type
    StartDate: new Date(),  // Date object for date columns
  }
];

// Column definition must match data types
<e-columns>
  <e-column field='TaskID' headerText='ID' type='number'></e-column>
  <e-column field='TaskName' headerText='Task' type='text'></e-column>
  <e-column field='StartDate' headerText='Date' type='date' format='yMd'></e-column>
</e-columns>

// ❌ WRONG - Type mismatch
public data = [
  {
    TaskID: '1',            // String instead of number
    StartDate: '02/03/2024' // String instead of Date object
  }
];
严重程度:🟠 重要 - 类型不匹配会导致渲染/排序问题
要求
typescript
// ✅ 正确 - 类型与列定义匹配
public data = [
  {
    TaskID: 1,              // 数字类型
    TaskName: '规划',   // 字符串类型
    StartDate: new Date(),  // 日期列使用Date对象
  }
];

// 列定义必须与数据类型匹配
<e-columns>
  <e-column field='TaskID' headerText='ID' type='number'></e-column>
  <e-column field='TaskName' headerText='任务' type='text'></e-column>
  <e-column field='StartDate' headerText='日期' type='date' format='yMd'></e-column>
</e-columns>

// ❌ 错误 - 类型不匹配
public data = [
  {
    TaskID: '1',            // 使用字符串而非数字
    StartDate: '02/03/2024' // 使用字符串而非Date对象
  }
];

Inbuilt properties, events and Methods

内置属性、事件和方法

📄 Read: references/api-reference.md
  • Complete property reference
  • Methods and events documentation
  • Column and editing interfaces
  • Common data structures

📄 阅读references/api-reference.md
  • 完整的属性参考
  • 方法和事件文档
  • 列和编辑接口
  • 常见数据结构

Documentation Navigation Guide

文档导航指南

Getting Started & Setup

入门与设置

📄 Read: references/getting-started-guide.md
  • Complete installation and setup
  • Module configuration
  • Project initialization
  • First TreeGrid component
📄 阅读references/getting-started-guide.md
  • 完整的安装和设置步骤
  • 模块配置
  • 项目初始化
  • 第一个TreeGrid组件

Data Management

数据管理

Data Binding & Adapters 📄 Read: references/data-binding.md
  • Local and remote data binding
  • ORM and custom adaptor implementation
  • Loading data from various sources
Observables Data 📄 Read: references/observables.md
  • RxJS observables integration
  • Async data binding patterns
  • Observable-based event handling
  • Async operators and pipelines
CRUD Operations & Validation 📄 Read: references/persisting-data-in-server.md
  • Server-side data persistence
  • CRUD operation management
  • Batch operations and transactions
  • Offline sync patterns
数据绑定与适配器 📄 阅读references/data-binding.md
  • 本地和远程数据绑定
  • ORM和自定义适配器实现
  • 从多种数据源加载数据
可观察对象数据 📄 阅读references/observables.md
  • RxJS observables集成
  • 异步数据绑定模式
  • 基于Observable的事件处理
  • 异步操作符和管道
CRUD操作与验证 📄 阅读references/persisting-data-in-server.md
  • 服务端数据持久化
  • CRUD操作管理
  • 批量操作和事务
  • 离线同步模式

Column Configuration

列配置

📄 Read: references/column.md
  • Column definition and width management
  • Custom column templates and rendering
  • Column reordering and freezing
📄 阅读references/column.md
  • 列定义和宽度管理
  • 自定义列模板和渲染
  • 列重排序和冻结

Column Spanning

列合并

📄 Read: references/column-spanning.md
  • Multi-column spanning configuration
  • Cell spanning across columns
  • Dynamic span calculation
📄 阅读references/column-spanning.md
  • 多列合并配置
  • 跨列单元格合并
  • 动态合并计算

Command Columns

命令列

📄 Read: references/command-column.md
  • Command column with action buttons
  • Edit, Delete, and Cancel buttons
  • Custom command implementations
📄 阅读references/command-column.md
  • 带操作按钮的命令列
  • 编辑、删除和取消按钮
  • 自定义命令实现

Column Menu

列菜单

📄 Read: references/column-menu.md
  • Column header context menu
  • Sort, group, and filter menu items
  • Custom column menu options
📄 阅读references/column-menu.md
  • 列头上下文菜单
  • 排序、分组和筛选菜单项
  • 自定义列菜单选项

Column Chooser

列选择器

📄 Read: references/column-chooser.md
  • Column visibility toggle UI
  • Show/hide columns dynamically
  • Column chooser dialog configuration
📄 阅读references/column-chooser.md
  • 列可见性切换UI
  • 动态显示/隐藏列
  • 列选择器对话框配置

Row Configuration

行配置

📄 Read: references/row.md
  • Row templates and detail rows
  • Row drag-drop functionality
  • Row spanning and customization
📄 阅读references/row.md
  • 行模板和详情行
  • 行拖拽功能
  • 行合并和自定义

Cell-Level Features

单元格级特性

📄 Read: references/cell.md
  • Cell styling and formatting
  • Cell templates and tooltips
  • Custom CSS and HTML content
📄 阅读references/cell.md
  • 单元格样式和格式化
  • 单元格模板和提示框
  • 自定义CSS和HTML内容

Module System & Architecture

模块系统与架构

📄 Read: references/modules.md
  • Module imports and dependencies
  • Required service providers
  • Angular version compatibility
  • Library setup and initialization
📄 阅读references/modules.md
  • 模块导入和依赖
  • 所需的服务提供者
  • Angular版本兼容性
  • 库的设置和初始化

Editing

编辑

📄 Read: references/editing.md
  • Cell, inline, dialog, row, and batch editing
  • Data validation and error handling
  • Custom editors and validation rules
📄 阅读references/editing.md
  • 单元格、内联、对话框、行和批量编辑
  • 数据验证和错误处理
  • 自定义编辑器和验证规则

Sorting

排序

📄 Read: references/sorting.md
  • Single and multi-column sorting
  • Custom sort comparers
  • Sort order and keyboard navigation
📄 阅读references/sorting.md
  • 单列和多列排序
  • 自定义排序比较器
  • 排序顺序和键盘导航

Filtering

筛选

📄 Read: references/filtering.md
  • Filter bar and menu modes
  • Excel-like filtering
  • Custom filters and predicates
📄 阅读references/filtering.md
  • 筛选栏和菜单模式
  • 类Excel筛选
  • 自定义筛选和谓词

Searching

搜索

📄 Read: references/searching.md
  • Global and column-level search
  • Case-sensitive searching
  • Text highlighting
📄 阅读references/searching.md
  • 全局和列级搜索
  • 区分大小写的搜索
  • 文本高亮

Selection

选择

📄 Read: references/selection.md
  • Row, cell, and checkbox selection modes
  • Selection events and APIs
  • Programmatic selection
📄 阅读references/selection.md
  • 行、单元格和复选框选择模式
  • 选择事件和API
  • 程序化选择

Paging

分页

📄 Read: references/paging.md
  • Pagination configuration
  • Server-side paging
  • Page navigation APIs
📄 阅读references/paging.md
  • 分页配置
  • 服务端分页
  • 页面导航API

Scrolling

滚动

📄 Read: references/scrolling.md
  • Virtual scrolling for large datasets
  • Infinite scroll and lazy loading
  • Height/width management and scroll positioning
📄 阅读references/scrolling.md
  • 大型数据集的虚拟滚动
  • 无限滚动和懒加载
  • 高度/宽度管理和滚动定位

Frozen Columns

冻结列

📄 Read: references/frozen-columns.md
  • Freeze rows and columns
  • Fixed visibility configuration
  • Performance optimization
📄 阅读references/frozen-columns.md
  • 冻结行和列
  • 固定可见性配置
  • 性能优化

Aggregations

聚合

📄 Read: references/aggregates.md
  • Summary calculations (Sum, Avg, Min, Max, Count)
  • Footer templates and child aggregates
  • Aggregate events
📄 阅读references/aggregates.md
  • 汇总计算(求和、平均值、最小值、最大值、计数)
  • 页脚模板和子级聚合
  • 聚合事件

Export & Print

导出与打印

📄 Read: references/print.md
  • Print functionality and modes
  • Page setup and column visibility
  • Custom print templates
📄 Read: references/pdf-export.md
  • PDF export with styling
  • Headers, footers, and watermarks
  • Server-side export
📄 Read: references/excel-export.md
  • Excel export configuration
  • Cell styling and formatting
  • Merged cells and custom data
📄 Read: references/csv-export.md
  • CSV export configuration
  • Custom data formatting for export
  • Dynamic file naming
  • Export events and callbacks
  • Selected records export
📄 阅读references/print.md
  • 打印功能和模式
  • 页面设置和列可见性
  • 自定义打印模板
📄 阅读references/pdf-export.md
  • 带样式的PDF导出
  • 页眉、页脚和水印
  • 服务端导出
📄 阅读references/excel-export.md
  • Excel导出配置
  • 单元格样式和格式化
  • 合并单元格和自定义数据
📄 阅读references/csv-export.md
  • CSV导出配置
  • 导出的自定义数据格式化
  • 动态文件名
  • 导出事件和回调
  • 选中记录导出

User Interface & Interaction

用户界面与交互

📄 Read: references/toolbar.md
  • Built-in toolbar items
  • Custom toolbar items and alignment
  • Toolbar event handling
📄 Read: references/clipboard.md
  • Copy/paste operations
  • Custom clipboard formats
  • Clipboard event handling
📄 Read: references/context-menu.md
  • Context menu configuration
  • Built-in and custom menu items
  • Menu event handling
📄 阅读references/toolbar.md
  • 内置工具栏项
  • 自定义工具栏项和对齐方式
  • 工具栏事件处理
📄 阅读references/clipboard.md
  • 复制/粘贴操作
  • 自定义剪贴板格式
  • 剪贴板事件处理
📄 阅读references/context-menu.md
  • 上下文菜单配置
  • 内置和自定义菜单项
  • 菜单事件处理

Appearance & Responsiveness

外观与响应式

📄 Read: references/adaptive.md
  • Responsive and adaptive design
  • Mobile optimization
  • Breakpoints and device detection
📄 Read: references/styling.md
  • Built-in themes (Material, Bootstrap, Fabric, Tailwind)
  • CSS customization and overrides
  • Row/cell conditional styling
📄 阅读references/adaptive.md
  • 响应式和自适应设计
  • 移动端优化
  • 断点和设备检测
📄 阅读references/styling.md
  • 内置主题(Material、Bootstrap、Fabric、Tailwind)
  • CSS自定义和覆盖
  • 行/单元格条件样式

Performance

性能

📄 Read: references/performance-optimization.md
  • Virtual scrolling and lazy loading
  • Pagination for large datasets
  • Column virtualization and rendering optimization
  • Query optimization strategies
📄 阅读references/performance-optimization.md
  • 虚拟滚动和懒加载
  • 大型数据集的分页
  • 列虚拟化和渲染优化
  • 查询优化策略

State Management

状态管理

📄 Read: references/state-persistence.md
  • Save and restore grid state
  • LocalStorage integration
  • Custom state management
📄 阅读references/state-persistence.md
  • 保存和恢复网格状态
  • LocalStorage集成
  • 自定义状态管理

Foreign-key

外键

📄 Read: references/foreign-keys.md
  • Foreign key column configuration
  • Display text mapping for FK values
  • Dropdown editors for FK fields
  • Cascading foreign key relationships
  • Remote data binding for FK data
📄 阅读references/foreign-keys.md
  • 外键列配置
  • FK值的显示文本映射
  • FK字段的下拉编辑器
  • 级联外键关系
  • FK数据的远程数据绑定

Row Drag and Drop

行拖拽

📄 Read: references/row-drag-drop.md
  • Hierarchical drag-and-drop operations
  • Parent-child relationship updates
  • Circular hierarchy prevention
  • Drop event validation and constraints
  • Visual feedback during drag operations
📄 阅读references/row-drag-drop.md
  • 层级拖拽操作
  • 父子关系更新
  • 循环层级预防
  • 拖放事件验证和约束
  • 拖拽过程中的视觉反馈

Custom Editors

自定义编辑器

📄 Read: references/custom-editors.md
  • Custom editor component creation
  • Editor lifecycle management
  • Validation in custom editors
  • Custom editor templates
  • Complex data input patterns
📄 阅读references/custom-editors.md
  • 自定义编辑器组件创建
  • 编辑器生命周期管理
  • 自定义编辑器中的验证
  • 自定义编辑器模板
  • 复杂数据输入模式

Validation

验证

📄 Read: references/validation.md
  • Built-in and custom validation rules
  • Async validation against server
  • Cross-field validation patterns
  • Server-side validation strategies
  • Error display and highlighting
  • Conditional validation rules
📄 阅读references/validation.md
  • 内置和自定义验证规则
  • 针对服务端的异步验证
  • 跨字段验证模式
  • 服务端验证策略
  • 错误显示和高亮
  • 条件验证规则

Globalization

全球化

📄 Read: references/globalization.md
  • Localization and language support
  • RTL (Right-to-Left) support
  • Cultural formatting and date/number formats
📄 阅读references/globalization.md
  • 本地化和语言支持
  • RTL(从右到左)支持
  • 区域格式化和日期/数字格式

Loading Animation

加载动画

📄 Read: references/loading-animation.md
  • Loading spinner configuration
  • Custom loading templates
  • Loading animation customization
📄 阅读references/loading-animation.md
  • 加载 spinner 配置
  • 自定义加载模板
  • 加载动画自定义

Accessibility & Compliance

可访问性与合规性

📄 Read: references/accessibility.md
  • WCAG 2.1 Level AA conformance
  • ARIA labels and attributes
  • Keyboard navigation and screen reader support
  • Focus management and visual indicators
  • Accessibility testing guidance
📄 阅读references/accessibility.md
  • 符合WCAG 2.1 Level AA标准
  • ARIA标签和属性
  • 键盘导航和屏幕阅读器支持
  • 焦点管理和视觉指示器
  • 可访问性测试指南

Quick Start Example

快速入门示例

typescript
import { Component, ViewChild } from '@angular/core';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { PageService, SortService, FilterService, EditService } from '@syncfusion/ej2-angular-treegrid';

@Component({
  selector: 'app-treegrid',
  template: `
    <ejs-treegrid 
      #treegrid
      [dataSource]='data'
      [childMapping]='childMapping'
      [allowPaging]='true'
      [allowSorting]='true'
      [allowFiltering]='true'
      <e-columns>
        <e-column field='TaskID' headerText='Task ID' width='90' isPrimaryKey='true'></e-column>
        <e-column field='TaskName' headerText='Task Name' width='200'></e-column>
      </e-columns>
    </ejs-treegrid>
  `,
  providers: [PageService, SortService, FilterService, EditService]
})
export class AppComponent {
  @ViewChild('treegrid') treegrid!: TreeGridComponent;

  public data: Object[] = [
    {
      TaskID: 1,
      TaskName: 'Planning',
      subtasks: [
        { TaskID: 2, TaskName: 'Scope', Duration: 4, Progress: 100 },
        { TaskID: 3, TaskName: 'Budget', Duration: 4, Progress: 100 }
      ]
    }
  ];
  
  public childMapping: string = 'subtasks';
  
  public editSettings = { mode: 'Cell', allowEditing: true, allowDeleting: true, allowAdding: true };
}
typescript
import { Component, ViewChild } from '@angular/core';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { PageService, SortService, FilterService, EditService } from '@syncfusion/ej2-angular-treegrid';

@Component({
  selector: 'app-treegrid',
  template: `
    <ejs-treegrid 
      #treegrid
      [dataSource]='data'
      [childMapping]='childMapping'
      [allowPaging]='true'
      [allowSorting]='true'
      [allowFiltering]='true'
      <e-columns>
        <e-column field='TaskID' headerText='任务ID' width='90' isPrimaryKey='true'></e-column>
        <e-column field='TaskName' headerText='任务名称' width='200'></e-column>
      </e-columns>
    </ejs-treegrid>
  `,
  providers: [PageService, SortService, FilterService, EditService]
})
export class AppComponent {
  @ViewChild('treegrid') treegrid!: TreeGridComponent;

  public data: Object[] = [
    {
      TaskID: 1,
      TaskName: '规划',
      subtasks: [
        { TaskID: 2, TaskName: '范围定义', Duration: 4, Progress: 100 },
        { TaskID: 3, TaskName: '预算编制', Duration: 4, Progress: 100 }
      ]
    }
  ];
  
  public childMapping: string = 'subtasks';
  
  public editSettings = { mode: 'Cell', allowEditing: true, allowDeleting: true, allowAdding: true };
}

Best Practices

最佳实践

  1. Performance Optimization
    • Use virtual scrolling for large datasets (10,000+ records)
    • Implement server-side operations (sorting, filtering, paging)
    • Use frozen columns sparingly to avoid layout shifts
  2. Data Management
    • Always provide a primary key (isPrimaryKey='true')
    • Use ChildMapping for hierarchical data
    • Implement proper error handling for API calls
  3. User Experience
    • Provide loading indicators during data fetch
    • Implement search and filter for data discovery
    • Show validation messages for editing errors
    • Support keyboard navigation and accessibility
  4. Customization
    • Use themes for consistent styling
    • Create reusable cell templates for common patterns
    • Style conditional rows for user guidance
    • Implement responsive design for mobile devices
  5. State Management
    • Enable state persistence for user preferences
    • Save sort, filter, and column settings
  1. 性能优化
    • 对于大型数据集(10000+条记录)使用虚拟滚动
    • 实现服务端操作(排序、筛选、分页)
    • 谨慎使用冻结列以避免布局偏移
  2. 数据管理
    • 始终提供主键(isPrimaryKey='true')
    • 对于层级数据使用ChildMapping
    • 为API调用实现适当的错误处理
  3. 用户体验
    • 在数据获取过程中提供加载指示器
    • 实现搜索和筛选功能以方便数据查找
    • 显示编辑错误的验证消息
    • 支持键盘导航和可访问性
  4. 自定义
    • 使用主题保持样式一致
    • 为常见模式创建可复用的单元格模板
    • 为行设置条件样式以引导用户
    • 实现响应式设计以适配移动设备
  5. 状态管理
    • 启用状态持久化以保存用户偏好
    • 保存排序、筛选和列设置

Key Props Summary

关键属性汇总

PropTypeDefaultUse Case
dataSource
DataManager|Object[]nullSet grid data source
childMapping
stringnullProperty for child records (must be explicitly set)
allowPaging
booleanfalseEnable pagination
allowSorting
booleanfalseEnable sorting
allowFiltering
booleanfalseEnable filtering
editSettings
EditSettings{}Configure edit mode
enableVirtualization
booleanfalseEnable virtual scrolling
属性类型默认值使用场景
dataSource
DataManager|Object[]null设置网格数据源
childMapping
stringnull子记录的属性名(必须显式设置)
allowPaging
booleanfalse启用分页
allowSorting
booleanfalse启用排序
allowFiltering
booleanfalse启用筛选
editSettings
EditSettings{}配置编辑模式
enableVirtualization
booleanfalse启用虚拟滚动

Module Injection

模块注入

Must inject required services:
typescript
import { PageService, SortService, FilterService, EditService, ExcelExportService, PdfExportService,
  PrintService, AggregateService, ToolbarService } from '@syncfusion/ej2-angular-treegrid';

@Component({
  providers: [
    PageService, 
    SortService, 
    FilterService, 
    EditService,
    ExcelExportService,
    PdfExportService,
    PrintService,
    AggregateService,
    ToolbarService
  ]
})
必须注入所需的服务:
typescript
import { PageService, SortService, FilterService, EditService, ExcelExportService, PdfExportService,
  PrintService, AggregateService, ToolbarService } from '@syncfusion/ej2-angular-treegrid';

@Component({
  providers: [
    PageService, 
    SortService, 
    FilterService, 
    EditService,
    ExcelExportService,
    PdfExportService,
    PrintService,
    AggregateService,
    ToolbarService
  ]
})