Search code examples
vmware-clarity

Checkbox tree-view


I am new to clarity design. I am trying to implement checkbox treeview. But I am not able to read the values which user selects in treeview i.e, not able to achieve 2-way binding. I am trying to do it using ngModel and ngValue. Can you please help?


Solution

  • It seems like you are trying to implement <clr-tree-node [(clrSelected)]="selected"> feature.

    If you implement it like shown in the docs with something like the permissions: data for the docs for Selected Tree your HTML will look like this:

    <clr-tree-node
        *ngFor="let permission of permissions"
        [(clrSelected)]="permission.selected">
            {{permission.type}}
        <ng-template [(clrIfExpanded)]="permission.expanded">
            <clr-tree-node *ngFor="let right of permission.rights" [(clrSelected)]="right.enable">
                {{right.name}}
            </clr-tree-node>
        </ng-template>
    </clr-tree-node>
    

    You can add/use de-sugared syntax for the clrSelected @Output like this to check which tree-node was selected

    <clr-tree-node [clrSelected]="selected" (clrSelectedChange)="checkForChanges()">
    

    And reduce your permissions down to only the selected nodes in checkForChanges().

    Update

    For the permissions array it is easy to filter out the non-selected nodes with this line:

    permissions.filter(item => item.selected);
    

    So, for example lets assume you have a selected property in your component selected: Array<any> = [];

    Then, your check for changes might look like this

    checkForChanges() {
        this.selected.length = 0; // clear the selected array
        this.selected = permissions.filter(item => item.selected); // Reduce the array to only selected items.
    }