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

userx picture userx · May 29, 2018 · Viewed 6.9k times · Source

I'm using Angular Material6 Tree component with check boxes.

In the Original Example, We only can add new child to parent Node. What If I want to add a new child to a leaf node.

Answer

userx picture userx · Jun 7, 2018

I solved this by adding few lines to insertItem and addNewItem functions. 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);
        }
      }