代码之家  ›  专栏  ›  技术社区  ›  userx

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

  •  0
  • userx  · 技术社区  · 7 年前

    我在用 Angular Material6 Tree component 带复选框。

    Original Example ,我们只能向父节点添加新的子节点。 如果我想在 leaf node .

    1 回复  |  直到 7 年前
        1
  •  1
  •   userx    7 年前

    我通过在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);
            }
          }
    
    推荐文章