Saurabh Mahajan
Saurabh Mahajan

Reputation: 2969

Create Custom Checkbox tree view component Angular

I want to create Tree View component in Angular with checkbox. Please find my code at -

https://stackblitz.com/edit/angular-qvzr8c

Here I am able to render tree View on UI. But want to implement functionality -

  1. When Parent checkbox is checked then all its child check box should be checked automatically.
  2. When all child checkboxes checked then parent node chekbox should automatically selected.
  3. At the end want list of all selected checkboxes.

Here how can I set model to checkboxes and achieve above functionality.​

Upvotes: 1

Views: 8576

Answers (4)

Betrunkenmeister
Betrunkenmeister

Reputation: 1

This stackblitz from this question was useful for me

Upvotes: 0

Aman Gojariya
Aman Gojariya

Reputation: 1429

Please try with this plugin. It will works for you.

Upvotes: 0

Eliseo
Eliseo

Reputation: 58019

the first you need is add a new optional property to your TreeNode

interface TreeNode {
    label: string;
    check?:boolean; //<--this one
    children: TreeNode[];
  }

After you can use [ngModel] in the input, and (ngModelChange) to call a function "selectNode"

 <label class="node__label">
        <input type="checkbox" [ngModel]="node.check" 
          (ngModelChange)="selectNode(node,$event)"/>
    {{ node.label }}
</label>

the seletNode is a function that call a recursive function:

  public selectNode( node: TreeNode,value:boolean ) : void {
        this.check(node,value)
  }

  check(node:any,value:boolean)
  {
    node.check=value;
    node.children.forEach(x=>
    {
      this.check(x,value)
    })
  }

You can see in this stackblitz

But you can take account the suggest of @Dseroski and not re-invent the wheel :)

Upvotes: 4

dseroski
dseroski

Reputation: 31

Angular Material has a pretty good Tree module. This example is explicitly similar to what you need, aside from a few logic changes on checking a box.

https://stackblitz.com/angular/baxxqmgxmgq?file=src%2Fapp%2Ftree-checklist-example.ts

Upvotes: 0

Related Questions