在d3js树中添加/创建新的子节点

时间:2018-07-25 07:13:43

标签: d3.js

我使用下面的代码创建一个节点。但是,在添加新节点时,整个树都在刷新。我需要刷新新添加的节点。

    if (parentNode._children != null) {
        parentNode.children = parentNode._children;
        parentNode._children = null;
    }
    if (parentNode.children == null) { parentNode.children = []; } 
    parentNode.data.children.push({ 'name': 'title', 'children': [], '_children': null });
    scope.root = d3.hierarchy(scope.data, function (datachild: any) {
    return datachild.children;
    });
    scope.root.x0 = parentNode.x0;
    scope.root.y0 = parentNode.y0;
    update(scope.root); 

1 个答案:

答案 0 :(得分:0)

如果每个都有父级,我设法更新了每个的深度。

if (parentNode._children != null) {
              parentNode.children = parentNode._children;
              parentNode._children = null;
            }
            if (parentNode.children == null) {
              parentNode.children = [];
            }

            const nodeData = {
              'name': 'title',
              'children': [],
              '_children': null,
              'depth': 0
            };

            const newNode = d3.hierarchy(nodeData);
            newNode.parent = parentNode;

            parentNode.children.push(newNode);
            parentNode.data.children.push(nodeData);
            scope.inEditMode = true;

            update(parentNode, true);

功能更新(源,addNewNode){

  // Assigns the x and y position for the nodes
  const treeData = scope.tree(scope.root);

  // Compute the new tree layout.
  const nodes = treeData.descendants(),
    links = treeData.descendants().slice(1);

  // Normalize for fixed-depth.
  nodes.forEach(function (d: any, i: any) {
    if (addNewNode && d.parent) {
  // Here you can update.
      d.depth = d.parent.depth + 1;
    }
    d.y = d.depth * 280;

  });

}