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

时间:2018-05-29 09:49:28

标签: angular angular-material angular-material2 angular-material-5 angular-cdk

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

Original Example中,我们只能将新子节点添加到父节点。 如果我想将新的孩子添加到leaf node,该怎么办?

2 个答案:

答案 0 :(得分:1)

我通过向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);
        }
      }

答案 1 :(得分:1)

虽然这是个老问题,但我会为那些再次询问如何做的人回答。

首先,在叶子节点上添加+按钮:

<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();
      });