Reputation: 2969
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 -
Here how can I set model to checkboxes and achieve above functionality.
Upvotes: 1
Views: 8576
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
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