如何更新 mat-tree 以处理将 children 节点添加到叶节点(将叶节点转换为 parents)

How to update mat-tree to handle add children nodes to leaf nodes (convert leaf nodes to parents)

我正在使用 Angular Material6 Tree component 和复选框。

Original Example中,我们只能添加新的child到parent节点。 如果我想向 leaf node 添加一个新的 child 怎么办?

我通过向 insertItem 和 addNewItem 函数添加几行来解决这个问题。 stackblitz fork

     addNewItem(node: TodoItemFlatNode) {
        const parentNode = this.flatNodeMap.get(node);
        /*** this block will be used to determine wither we should expand the subtree or not.      **/ 
        let isParentHasChildren: boolean = false;
        if (parentNode.children)
          isParentHasChildren = true;
        /** end of the block **/
        this.database.insertItem(parentNode!, '');
        // expand the subtree only if the parent has children (parent is not a leaf node)
        if (isParentHasChildren)
          this.treeControl.expand(node);
      }

      insertItem(parent: TodoItemNode, name: string) {
        const child = <TodoItemNode>{ item: name };
        if (parent.children) { // parent already has children
          parent.children.push(child);
          this.dataChange.next(this.data);
        }
        else { // if parent is a leaf node
          parent.children = [];
          parent.children.push(child);
          this.dataChange.next(this.data);
        }
      }

虽然是个老问题了,还是给大家答一下,再问怎么办。

首先,将+按钮添加到叶节点:

<button mat-icon-button (click)="addNewItem(node)"><mat-icon>add</mat-icon></button>

然后,使用一个小技巧来刷新树。

refreshTree() {
    let _data = this.dataSource.data;
    this.dataSource.data = [];
    this.dataSource.data = _data;
  }

我在数据更改订阅中添加了对 refreshTree 函数的调用:

_database.dataChange.subscribe(data => {
        this.dataSource.data = data;
        this.refreshTree();
      });