Local data in Angular Treegrid component

27 Sep 202315 minutes to read

In Local Data binding, data source for rendering the TreeGrid control is retrieved from the same application locally.

Two types of Data binding are possible with the TreeGrid control.

  • Hierarchical Datasource binding
  • Self-Referential Data binding (Flat Data)

To bind local data to the treegrid, you can assign a JavaScript object array to the dataSource property. The local data source can also be provided as an instance of the DataManager.

By default, DataManager uses JsonAdaptor for local data-binding.

Hierarchy data source binding

The childMapping property is used to map the child records in hierarchy data source.

The following code example shows you how to bind the hierarchical local data into the TreeGrid control.

import { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import {PageSettingsModel } from '@syncfusion/ej2-angular-grids';

@Component({
    selector: 'app-container',
    template: `<ejs-treegrid [dataSource]='data'  [treeColumnIndex]='1' childMapping='subtasks'
                [allowPaging]="true" [pageSettings]='pageSettings'>
                <e-columns>
                    <e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
                    <e-column field='taskName' headerText='Task Name' textAlign='Left' width=180></e-column>
                    <e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=90></e-column>
                    <e-column field='duration' headerText='Duration' textAlign='Right' width=80></e-column>
                </e-columns>
                </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data?: Object[];
    public pageSettings?: PageSettingsModel;

    ngOnInit(): void {
        this.data = sampleData;
        this.pageSettings = { pageSize: 6 };
    }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { PageService, SortService, FilterService } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

  • Remote data binding is not supported for Hierarchy Data.

Self-Referential data binding (Flat data)

TreeGrid is rendered from Self-Referential data structures by providing two fields, ID field and parent ID field.

  • ID Field: This field contains unique values used to identify nodes. Its name is assigned to the idMapping property.
  • Parent ID Field: This field contains values that indicate parent nodes. Its name is assigned to the parentIdMapping property.
import { Component, OnInit } from '@angular/core';
import { projectData } from './datasource';

@Component({
    selector: 'app-container',
    template: `<ejs-treegrid [dataSource]='data' [treeColumnIndex]='1' parentIdMapping='parentID' idMapping='TaskID' height=265 [allowPaging]="true">
        <e-columns>
            <e-column field='TaskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
            <e-column field='TaskName' headerText='Task Name' width='170'></e-column>
            <e-column field='StartDate' headerText='Start Date' width='130' format="yMd" textAlign='Right'></e-column>
            <e-column field='Duration' headerText='Duration' width='80' textAlign='Right'></e-column>
        </e-columns>
                </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data?: Object[];

    ngOnInit(): void {
        this.data = projectData;
    }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { PageService, SortService, FilterService } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Herewith we have provided list of reserved properties and the purpose used in TreeGrid. We recommend to avoid these reserved properties for Internal purpose(To get rid of conflicts).

Reserved keywords Purpose
childRecords Specifies the childRecords of a parentData
hasChildRecords Specifies whether the record contains child records
hasFilteredChildRecords Specifies whether the record contains filtered child records
expanded Specifies whether the child records are expanded
parentItem Specifies the parentItem of childRecords
index Specifies the index of current record
level Specifies the hierarchy level of record
filterLevel Specifies the hierarchy level of filtered record
parentIdMapping Specifies the parentID
uniqueID Specifies the unique ID of a record
parentUniqueID Specifies the parent Unique ID of a record
checkboxState Specifies the checkbox state of a record
isSummaryRow Specifies the summary of a record
taskData Specifies the main data
primaryParent Specifies the Primary data

Refresh the data source

Add or delete the data source through an external button. To reflect the data source changes in the tree grid, you need to invoke the refresh method.

Please follow the below steps to refresh the tree grid after changing the data source:

Step 1:

Add or delete the datasource record by using the following code:

    this.treegrid.dataSource.unshift(data); // Add a new record.

    this.treegrid.dataSource.splice(selectedRow, 1); // Delete a record.

Step 2:

Refresh the tree grid after changing the datasource by using the refresh method.

    this.treegrid.refresh(); // Refresh the tree grid.
import { Component, OnInit, ViewChild } from '@angular/core';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { sampleData } from './datasource';

@Component({
    selector: 'app-container',
    template: `<button ej-button class="e-flat" (click)="add()">Add</button>
                <button ej-button class="e-flat" (click)="delete()">Delete</button>
                <ejs-treegrid #treegrid [dataSource]="data" childMapping="subtasks" height="350" [treeColumnIndex]="1" [allowPaging]="true" [pageSettings]="pageSettings">
                    <e-columns>
                        <e-column field="taskID" headerText="Task ID" width="90" textAlign="Right"></e-column>
                        <e-column field="taskName" headerText="Task Name" width="200"></e-column>
                        <e-column field="startDate" headerText="Start Date" width="110" format="yMd" textAlign="Right"></e-column>
                        <e-column field="endDate" headerText="End Date" width="110" format="yMd" textAlign="Right"></e-column>
                        <e-column field="duration" headerText="Duration" width="100" textAlign="Right"></e-column>
                        <e-column field="progress" headerText="Progress" width="80" textAlign="Right"></e-column>
                        <e-column field="priority" headerText="Priority" width="90"></e-column>
                    </e-columns>
                </ejs-treegrid>`
})
export class AppComponent implements OnInit {

    public data: Object[] = [];
    @ViewChild('treegrid') public treegrid?: TreeGridComponent;
    pageSettings: any;

    ngOnInit(): void {
        this.data = sampleData;
    }
    add(): void {
    const rdata: object = {
      taskID: 102,
      taskName: 'New record',
      startDate: new Date(8367642e5),
      endDate: new Date(8467642e5),
      duration: 15,
      progress: 100,
      priority: 'Normal',
    };
    (this.treegrid?.dataSource as object[]).unshift(rdata);
    this.treegrid?.refresh();
  }
  delete(): void {
    const selectedRow: number = this.treegrid?.getSelectedRowIndexes()[0] as number;
    if (this.treegrid?.getSelectedRowIndexes().length) {
      (this.treegrid?.dataSource as object[]).splice(selectedRow, 1);
    } else {
      alert('No records selected for delete operation');
    }
    this.treegrid?.refresh();
  }
}
import { NgModule,ViewChild } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid';
import { PageService, SortService, FilterService } from '@syncfusion/ej2-angular-treegrid';
import { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Get the content of the tree grid by using the getContent method.
Get the table content by using the getContentTable method in the tree grid.
Destroy the component by using the destroy method in the tree grid.