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

Syncfusion Angular TreeGrid:如何编程式在指定索引添加多行

解决Syncfusion TreeGrid多行插入指定索引位置的问题

原代码中paste方法用push把复制行追加到数据源末尾,要实现插入到指定位置,可按以下方式修改:

核心调整

  • 先获取目标插入索引(示例以当前选中行的索引作为插入位置,可按需自定义)
  • 用数组splice方法替代push,实现批量插入到指定位置

修改后的完整代码

copy() {
    this.MultiSelect = true;
    const allselected = this.treegrid.getSelectedRecords();
    const rows = this.treegrid.getSelectedRows();
    this.copiedRow = rows;
    const crows = allselected.map(record => record['taskData']);
    this.copiedRows = crows;
    this.copiedRow.forEach(x => {
      x.setAttribute('style', 'background:pink;');
    });
}

paste() {
    if(this.copiedRows.length === 0) return;

    const tree = document.getElementsByClassName("e-treegrid")[0]['ej2_instances'][0];
    const temp = tree.dataSource.slice();
    // 获取目标插入索引:这里取当前选中行的第一个索引,如需插入到选中行下方可改为 targetIndex + 1
    const targetIndex = this.treegrid.getSelectedRowIndexes()[0] || 0;

    // 反向遍历保证插入后行顺序和复制时一致
    [...this.copiedRows].reverse().forEach(data => {
        temp.splice(targetIndex, 0, data);
    });

    this.treegrid.dataSource = temp;
    this.dataService.pushData(this.treegrid.dataSource);
    
    this.copiedRow.forEach(x => {
        x.setAttribute('style', 'background:white;');
    });
    this.copiedRows = [];
}

关键说明

  1. 若需自定义插入位置,直接修改targetIndex的值即可,比如固定插入到第3行就写const targetIndex = 2(数组索引从0开始)
  2. 反向遍历复制行是因为splice插入会让后续元素后移,反向插入能保证最终行顺序和复制的顺序一致
  3. 如果是带层级的树形结构,需要额外处理插入行的父节点ID等关联字段,确保树形渲染正常

内容的提问来源于stack exchange,提问作者Nirav Rathod

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:54:18