jsonkendo-ui-angular2kendo-treeview

How to populate multilevel KendoTree view with nested JSON data in Angular 5


I am trying to populate nested JSON data into multilevel KendoTreeView.

public nodes: any[] = [{
      "moduleId": 1,
      "moduleName": "Mode",
      "features": [
        {
          "featureId": 2,
          "featureName": "F1",
          "subFeatures": [],
          "privileges": [
            {
              "privilegeId": 2,
              "privilegeName": "P2"
            },
            {
              "privilegeId": 12,
              "privilegeName": "P2E"
            }
          ]
        },
        {
          "featureId": 3,
          "featureName": "F2",
          "subFeatures": [
            {
              "featureId": 4,
              "featureName": "F21",
              "subFeatures": [],
              "privileges": [
                {
                  "privilegeId": 4,
                  "privilegeName": "P4"
                }
              ]
            }
          ],
          "privileges": [
            {
              "privilegeId": 3,
              "privilegeName": "P3"
            }
          ]
        }
    ]
}]

Using this code I could only see one level tree. Not sure how to use [hasChildren]="hasChildren" in this scenario.

`So far I tried this to get some data populated in the Kendo TreeView. Data looks like this.

<kendo-treeview [nodes]="node"
                [textField]="[ 'moduleName','featureName']"
                [childrenField]="['features']"
                kendoTreeViewExpandable
                kendoTreeViewHierarchyBinding>
</kendo-treeview>`

Thanks in Advance for help.


Solution

  • The tree component directly supports just one field for the node name. So you have to use a Node template to find the right attribute for displaying the node name. Further for children and haschildren you have to add some code that tells which attribute contains the children and does that attribute have a content. So your structure is:

    Module
      Feature
        Subfeature
    

    Each level has to be supported by custom code.

    Template:

     <kendo-treeview
         textField="moduleName"
         [nodes]="nodes"
         [children]="children"
         [hasChildren]="hasChildren"
     >
     <ng-template kendoTreeViewNodeTemplate let-dataItem>
            {{dataItem.moduleName || dataItem.featureName}}
        </ng-template>
     </kendo-treeview>
    

    HasChildren:

     public hasChildren = (dataitem: any): boolean => !!dataitem.features || !!dataitem.subFeatures;
    

    Children:

     public children = (dataitem: any): Observable<any[]> => of(dataitem.features || dataitem.subFeatures);
    

    I have prepared a Stackblitz that works with your data.