【问题标题】:How to update mat-tree to handle add children nodes to leaf nodes (convert leaf nodes to parents)如何更新 mat-tree 以处理将子节点添加到叶节点(将叶节点转换为父节点)
【发布时间】:2018-05-29 09:49:27
【问题描述】:

我正在使用带有复选框的Angular Material6 Tree component

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

【问题讨论】:

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


    【解决方案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);
            }
          }
    

    【讨论】:

    • 如果立即向刚刚创建的子节点添加子节点,您知道如何使新的子节点可扩展吗?
    • 向叶子节点添加新项目时,它会折叠新节点。知道如何解决这个问题吗?
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      • 2013-10-26
      相关资源
      最近更新 更多