首页 > 解决方案 > 如何使用 Angular Tree 组件以编程方式将子节点添加到父节点的子节点

问题描述

我在使用角度树组件时遇到问题。我相信这个问题很简单,但我可以完全理解它。我似乎无法将子节点添加到父节点的子节点。那是根节点的孙子节点等等。我想添加曾孙等,但我仍在努力添加孙子。如果有人在lidorsystems 上看到integralUiTreeview。然后你就可以理解了。这是示例的链接https://www.lidorsystems.com/support/articles/angular/treeview/treeview-add-items-dynamically/ 我正在尝试做的事情。环顾整个互联网,我了解到这并不是很容易做到,但我正在使用角度树组件,我只想知道如何通过单击按钮来添加孩子。我已成功将子节点添加到根节点,但仅添加到第一个根节点。我想知道的是如何将孩子添加到我想要的任何节点,以及如何删除它。我相信我可以自己处理编辑部分。如果lidorsystems 是免费的,我会使用它。我怎样才能做到这一点?

这是我用来添加根节点的代码

createRootNode() {
  this.mainQuestion = this.surveyForm.get('firstQuestion').value;
  this.nodes.push({name: this.mainQuestion, children: []});
  console.log(this.nodes);
  this.tree.treeModel.update();
}

而这是第一个根的子节点。虽然这都是常规的:

  addNode(tree) {
    this.nodes[0].children.push({

      name: 'a new child',
      children: []

    });
    tree.treeModel.update();
  }

这是html:

  <div >
    <tree-root class="tree" #tree [nodes]="nodes"  [focused]="true" [options]="options">

      <ng-template #treeNodeTemplate let-node>
        <span title="{{node.data.name}}">{{ node.data.name }}</span>
        <span class="pull-right">{{ childrenCount(node) }}</span>
        <button (click)="addNode(tree)">add</button>
      </ng-template>
    </tree-root>
</div>

标签: treeviewangular7angular-tree-component

解决方案


对于任何想要使用 Angular 树组件来创建树视图的人来说,这是从树中添加和删除节点的基本过程:

添加-Ts文件:

    addNode(parent: TreeNode) {
   this.tree.treeModel.setFocus(true);
  const value = {
    name: 'a new child',
    children: []
  };
  if (parent) {
  parent.data.children.push(value);
  }
   this.tree.treeModel.update();
  }

html文件:

  <div >
<tree-root class="tree" #tree [nodes]="nodes"  [focused]="true" [options]="options">

  <ng-template #treeNodeTemplate let-node>
    <span title="{{node.data.name}}">{{ node.data.name }}</span>
    <span class="pull-right">{{ childrenCount(node) }}</span>
    <button  mat-icon-button (click)="addNode(node)" aria-label="Icon-button with an add icon">
        <mat-icon>add</mat-icon>
      </button>
      <button  mat-icon-button (click)="removeNode(node)" aria-label="Icon-button with a delete icon">
        <mat-icon>close</mat-icon>
      </button>
  </ng-template>
</tree-root>

对于删除节点:

    removeNode(node: TreeNode): void {
    if (node.parent != null) {
        node.parent.data.children.splice(node.parent.data.children.indexOf(node.data), 1);
        this.tree.treeModel.update();
    }
}

删除节点的Html写在上面。如果您对上面编写的儿童计数功能感到好奇,这里是代码:

   childrenCount(node: TreeNode): string {
    return node && node.children ? `(${node.children.length})` : '';
  }

您还可以访问https://github.com/500tech/angular-tree-component/issues/432浏览与添加和删除节点有关的问题。尽管社区不是很大或很活跃,但大多数解决方案都是在那里编写的。我希望这有帮助。如果我找到编辑的解决方案,我也会在这里发布。


推荐阅读