We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

Need to bind childnodes in tree grid in angular 7

I need to show a tree grid (initially all collapsed) and then when I click on a row, it should pull the data from api call at backend and bind it under the parent row. 

I need to bind child nodes in treegrid in angular, can you provide sample code?


html file

 <ejs-treegrid #treegrid [dataSource]='treeData' (actionFailure)="onActionFailure($event)"
                        idMapping='id' hasChildMapping='hasChildren' parentIdMapping='root' enableLoadOnDemand="true"
                        [treeColumnIndex]='0' (expanding)='onTreeListExpanding($event)'
                        (expanded)='onTreeListExpanded($event)'>
                        <e-columns>
                            <e-column field='code' headerText='Code'></e-column>
                            <e-column field='name' headerText='Name'></e-column>
                        </e-columns>
                    </ejs-treegrid>

TS file

  treeData1DataManager;
  treeDataDataManager;

ngOnInit() {
    this.pageSettings = { pageSize: 3 };

    const authToken = this.authService.getIdToken();

    this.treeData1 = new DataManager({
      url: 'https://localhost:44396/api/v1/systems/GetTags',
      adaptor: new UrlAdaptor,
      requestType: 'POST',
      crossDomain: true,
      headers: [{ Authorization: 'Bearer ' + authToken }]
    });
    // this.query = new Query();
    this.treeData1.executeQuery(new Query()).then((eany=> {
      this.treeData = e.result;
     //console.log(this.treeData1)
    });
  }

  onActionFailure(eany): void {
    console.log(e.error)
  }

  onTreeListExpanding(eventany): void {

     // this.query = new Query();
     this.treeData1.executeQuery(new Query()).then((eany=> {
      this.treeData = e.result;
     //console.log(this.treeData1)
    });
  }

  onTreeListExpanded(eventany): void {
    console.log(event);
  }

10 Replies

PK Padmavathy Kamalanathan Syncfusion Team November 8, 2019 10:33 AM UTC

Hi Dayakar,

Thanks for contacting Syncfusion Forums.

QUERY: I need to show a tree grid (initially all collapsed) and then when I click on a row, it should pull the data from api call at backend and bind it under the parent row.

As you have mentioned, your query is same as the one in the forum https://www.syncfusion.com/forums/143305/hierarchial-data-load-on-demand-or-dynamically

The Sample for your requirement has been given in that same forum.

Please check the below link,

You can edit and check that sample in the stackblitz also. 

If you need further details, please get back to us with more detail.

Regards,
Padmavathy Kamalanathan




DR Dayakar Reddy November 8, 2019 10:58 AM UTC

Hi Padmavathy,

Pleas provide solution for below queries

1) I have already gone through the link which you have provided, but i could not able to bind the child nodes properly using Rest API call.
Please provide some sample to bind child nodes using rest api service calls

2) One of the child has sub child but there is no arrow getting displayed in treegrid to expand. that record has hasChildren property is true. 

3) Please provide me solution for how to enable paging in treegrid, when i enable below code , i am getting error in console, ERROR TypeError: Cannot set property 'allowPaging' of undefined

this.treegrid.allowPaging = true; 
this.pageSettings = { pageSize: 3, pageSizeMode: 'Root' };
 this.treegrid.pageSettings = this.pageSettings;


4) Please provide solution for how to do CRUD operations in treegrid for angular

Please find the attachment for reference i attached html and component. and some screenshots





Attachment: treegrid_8f3b4da0.zip


DR Dayakar Reddy November 12, 2019 04:00 PM UTC

Hi Padmavathy ,

Can you help me on treegrid?


I am binding child data for treegrid using dataStateChange event of treegrid but Missing expand icon in child nodes even though  hasChildMapping property isParent is true, please set hasChildData: true to childData array objects in the below link in index.ts file and please check the UI expand icon is missing for child node.

https://codesandbox.io/s/eager-microservice-ydpq7

Please provide solution for this i have attached the code and screenshots for your reference along with json data for chilsnode .

Thanks,
Dayakar.


Attachment: treegrid_7ee5de0a.zip


PK Padmavathy Kamalanathan Syncfusion Team November 12, 2019 04:14 PM UTC

Hi Dayakar,

Thanks for contacting Syncfusion Forums.

QUERY: Provide sample for binding child nodes

From your query we understand that you need to bind child node to parent node of TreeGrid using API.

Please check the below sample,


QUERY2: One of the child node has sub child but there is no arrow getting displayed in treegrid to expand

From your code we can see that you are using Custom Binding(using dataStateChage) to bind data to TreeGrid. Since you are using our DataManager, you need not to use the Custom Binding. Custom Binding is meant for custom logic data. In our data manager, we have did everything needed for binding child node by inbuilt.

So we suggest you use our dataManager with webApi Adaptor. Please check the sample provided above.

QUERY3: getting error in pageSettings definition

Please check the below code,


  <ejs-treegrid [dataSource]='data' childMapping='subtasks' [treeColumnIndex]='1'
                [pageSettings]='pageSetting' allowPaging='true'>       
           ------
    </ejs-treegrid>

in ts

export class DefaultPagingComponent implements OnInit {  
   public data: Object[] = [];     
   public pageSetting: Object;    
    ngOnInit(): void {        
     -------
  this.pageSetting = { pageCount: 2, pageSizes: true } ; 
    } 
}
 
We suggest you to define the allowPaging property as shown above. Please check the below sample,

QUERY4: Provide sample for CRUD operation

We have provided sample above for performing CRUD with webApi Adaptor. Please check that.

If you have further queries, please get back to us.

Regards,
Padmavathy Kamalanathan



DR Dayakar Reddy November 12, 2019 04:34 PM UTC

Hi Padmavathy Thank you for the reply.

I am following the below approach 

But i want to use Custom Binding(using dataStateChage) based on my requirement we need to display large number of records in treegrid, can you suggest me how to display expand icon for child nodes when we use custom binding?

though the isParent is set to true the expand is missing for child nodes.

Thanks,
Dayakar.


SE Sathyanarayanamoorthy Eswararao Syncfusion Team November 13, 2019 12:33 PM UTC

Hi Dayakar, 
  
Query : though the isParent is set to true the expand is missing for child nodes. 
  
We were also able to replicate the issue on our side. We have confirmed that the reported issue is a bug and have logged a defect report for the same. The fix for this issue will be in the patch release which is expected to be rolled out on November 27 2019. 

Till then we appreciate your patience. You can track the status of the reported issue from the below link. 

  
Regards, 
Sathyanarayanamoorthy 



DR Dayakar Reddy November 14, 2019 05:34 AM UTC

Hi Padmavathy , Thank you for the reply, Instead of custom binding now i am using syncfusion dataManager. expand icon is now getting displayed. your sample code helped me.

I have below query

1)  i am doing CRUD operations on treegrid,  how to add additional fields to through request to rest api when we add record in treegrid when we use dataManager  or how to update the request from typescript anuglar


  // POST: api/Orders
        [HttpPost]
        public object Post([FromBody]SelfReferenceData value)
        {
            SelfReferenceData.tree.Insert(0, value);
            var data = SelfReferenceData.tree.ToList();
            return Json(new { result = data, count = data.Count });
        }


PK Padmavathy Kamalanathan Syncfusion Team November 18, 2019 03:42 AM UTC

Hi Dayakar, 

We have achieved your requirement by using the Custom Adaptor concept and overriding the insert method of the WebApiAdaptor. Please refer the below code example. 

Please refer the below documentations for more details. 



import { Component, ViewChild, ViewEncapsulation, OnInit, Inject } from '@angular/core'; 
import { DataManager, WebApiAdaptor, Query, DataUtil } from '@syncfusion/ej2-data'; 
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid'; 
 
 
let primaryKey: any; 
 
let selectedRecord: any; 
 
@Component({ 
    selector: 'fetchdata', 
    templateUrl: './fetchdata.component.html', 
    encapsulation: ViewEncapsulation.Emulated 
}) 
 
export class FetchDataComponent { 
    public data: any; 
    public toolbarOptions: string[] | undefined; 
    public editSettings: Object | undefined; 
    @ViewChild('treegrid') 
    public treegrid: TreeGridComponent; 
 
    ngOnInit(): void { 
 
        this.editSettings = { allowEditing: true, allowAdding: true, allowDeleting: true, mode: "Row", newRowPosition:"Below" }; 
        this.toolbarOptions = ['Add', 'Delete', 'Update', 'Cancel']; 
        this.data = new DataManager({ 
            url: 'api/SelfReferenceData', 
            adaptor: new CustomAdaptor() 
        }); 
    } 
 
    actionBegin(args: any): void { 
        if (args.requestType == "save" && args.action == "add") { 
            primaryKey = selectedRecord.TaskID; 
        } 
    } 
 
    rowSelected(args: any): void { 
        selectedRecord = args.data; 
    } 
     
 
}                    
 
//////   Extending the WebApiAdaptor and overriding the insert method. 
 
class CustomAdaptor extends WebApiAdaptor { 
    public insert(dm: DataManager, data: Object, tableName?: string): Object { 
        dm.dataSource.url = dm.dataSource.url + "?$key=" + primaryKey   ////  sending the primary key of selected record in query string 
        return {  
            type: 'POST', 
            url: dm.dataSource.url, 
            data: JSON.stringify(data),            
        }; 
    } 
 
} 
 

[Controller.cs] 


[HttpPost] 
        public object Post([FromBody]SelfReferenceData value) 
        { 
            var queryString = Request.Query; 
            StringValues keys; 
            queryString.TryGetValue("$key", out keys);   /// retrieving the key value from querystring 
            int key = Int32.Parse(keys[0]);     
            SelfReferenceData.tree.Insert(0, value); 
            var data = SelfReferenceData.tree.ToList(); 
            return Json(new { result = data, count = data.Count }); 
        } 



If you need any  further assistance please get back to us. We will be happy to assist you. 

Regards, 
Padmavathy Kamalanathan



DR Dayakar Reddy July 22, 2021 07:42 AM UTC

Hi,

Treegrid it is loading records on initial load and when you expand the tree rows it is loading Childs on demand .

treegrid is using datamanager to pull the records from backend  through API call.


I have few questions below

1)  For the treegrid search we need to search the child records as well. in below scenario it is not working

 as for the initial load we are only fetching the parent records. child data will be fetched if user expand parent rows. so search wont work on child records if user donot expand the rows.


2)  when we fitler columns in treegrid it is hitting backend API

can we stop calling backend API for filter?  instead can we filter locally available data?


Thanks,

Dayaka Reddy

 




JR Jagadesh Ram Raajkumar Syncfusion Team July 23, 2021 12:14 PM UTC

Hi Dayakar, 

Query 1: search wont work on child records if user donot expand the rows when using remote data. 

While using custom binding, by default TreeGrid parent rows will be rendered with the collapsed state. Tree Grid provides the option to load the child records also during the initial rendering itself for remote data binding by setting loadChildOnDemand as true. When loadChildOnDemand is enabled parent records are rendered in the expanded state. As per your requirement, the search action will now be performed on all the records rendered including the child records. 

Please refer to the below documentation,  

Note: When loadChildOnDemand is used, child records need to be returned along with the parent records from the server-side. 

Query 2: when we fitler columns in treegrid it is hitting backend API 

On remote data binding, all TreeGrid actions will be processed on the server side. To avoid postback, set the TreeGrid to load all data on initialization and make the actions process in client-side. To enable this behavior, use the offline property of DataManager.

Please refer to the below documentation, 

Kindly get back to us for further assistance.


Regards,
Jagadesh Ram 


Loader.
Live Chat Icon For mobile
Up arrow icon