How can i uncheck the all parent nodes when i uncheck the child node checkbox in custom tree view

1.2k Views Asked by At

I have created a custom Tree View with a checkbox. Now I need to uncheck the corresponding parent level node when I uncheck the corresponding child node.

eg: in my case, let's check all checkbox then if I uncheck the node named "fifth-b" then all belong to the parent node such as "fourth", "third-b", "second-a", "first" checkboxes are needs to be unchecked automatically.

I want to develop a completely custom tree view with checkbox and collapsible hence no other plugin or Material design we can use.

Please find my code at -

https://stackblitz.com/edit/angular-7xcthz

snapshot

I appreciate your great help.

1

There are 1 best solutions below

0
On

You may try something like iterating over the entire tree to find the node, for example, you may write some function like:

  public unselectParents(searchNode: TreeNode, searchPivot: TreeNode): boolean {
    if (searchPivot === searchNode) return true;
    else if (searchPivot.children.length !== 0) {
      for (let i = 0; i < searchPivot.children.length; i++) {
        let value = this.unselectParents(searchNode, searchPivot.children[i]);
        if (value === true) {
          searchPivot.check = false;
          return true;
        }
      }
    }
    return false;
  }

And then call this method in selectNode method:

  public selectNode(node: TreeNode, value: boolean): void {
    this.check(node, value);
    if (value == false) {
      this.unselectParents(node, this.data.root);
    }
  }

Alternatively, you may also have a property 'parent:TreeNode' in 'TreeNode' interface.