Checkbox Column in Angular TreeGrid component
25 Aug 202524 minutes to read
The Syncfusion® Angular TreeGrid component supports checkbox selection in the tree column with hierarchical selection functionality using the autoCheckHierarchy property and the showCheckbox property of the column.
When the autoCheckHierarchy property is enabled, selecting a parent record’s checkbox automatically selects all checkboxes of its child records, maintaining the hierarchical relationship. Checkboxes can be rendered only in the tree column by setting the column.showCheckbox property to true.
The following example demonstrates the hierarchical selection of checkboxes in the TreeGrid by enabling the autoCheckHierarchy and column.showCheckbox properties.
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 { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
@Component({
    imports: [TreeGridModule,],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<ejs-treegrid [dataSource]='data' height='250' [treeColumnIndex]='1' childMapping='subtasks' autoCheckHierarchy='true' >
                 <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 [showCheckbox]='true'></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[];
    ngOnInit(): void {
        this.data = sampleData;
    }
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
- The
 column.showCheckboxproperty will be utilized only when the column serves as a tree column cell (i.e., the treeColumnIndex column).
Programmatically select checkboxes
The TreeGrid allows programmatic checkbox selection using the selectCheckboxes method. This method accepts an array of row indexes to check the corresponding checkboxes.
When a parent record index is passed to the selectCheckboxes method, all child record checkboxes for that parent will be automatically selected due to the hierarchical relationship. Therefore, passing child record indexes along with the parent record index is unnecessary.
The following example demonstrates programmatic checkbox selection in the TreeGrid using the selectCheckboxes method with row indexes as parameters.
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 { ButtonModule } from '@syncfusion/ej2-angular-buttons'
import { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
@Component({
    imports: [TreeGridModule, ButtonModule],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<button ejs-button id="btnId" cssClass="e-info" (click)='selectcheckboxes()'> Select Checkboxes </button>
            
             <ejs-treegrid #treegrid [dataSource]='data' height='250' [treeColumnIndex]='1' childMapping='subtasks' autoCheckHierarchy='true' >
                <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 [showCheckbox]='true'></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[];
    @ViewChild('treegrid') treegrid?: TreeGridComponent;
    ngOnInit(): void {
        this.data = sampleData;
    }
    selectcheckboxes(): void {
        var selectCheckBoxIndexes: number[] = [2, 3, 4, 5]; //Here pass the some parent / child row indexes
        (this.treegrid as TreeGridComponent).selectCheckboxes(
            selectCheckBoxIndexes
        );
    }
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Get checked record details
The TreeGrid provides methods to retrieve information about checked records when using the checkbox column feature:
- 
    
getCheckedRecords: Returns an array of data objects for all checked records.
 - 
    
getCheckedRowIndexes: Returns an array of row indexes for all checked records.
 
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 { ButtonModule } from '@syncfusion/ej2-angular-buttons'
import { Component, OnInit } from '@angular/core';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { DialogComponent } from '@syncfusion/ej2-angular-popups';
import { sampleData } from './datasource';
@Component({
    imports: [TreeGridModule, ButtonModule],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<div>
               <label style="padding: 30px 17px 0 0" >Get the checked record details :</label>
              <button ejs-button id="buttons" (click)="GetCheckedRecord()">Checked Records</button>
              <button ejs-button id="buttons" (click)="GetCheckedIndex()">Checked Index</button>
               </div>
               <div style="margin-left:180px"><p style="color:red;" id="message" [innerHTML]="message"></p></div>
          
                <ejs-treegrid #treegrid [dataSource]='data' height='250' [treeColumnIndex]='1' childMapping='subtasks' autoCheckHierarchy='true' >
                 <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 [showCheckbox]='true'></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 message?: any;
    public header?: string;
    public checked_record?: any;
    @ViewChild('treegrid')
    public treegrid: TreeGridComponent | undefined;
    @ViewChild('Dialog')
    public dialog?: DialogComponent;
    ngOnInit(): void {
        this.data = sampleData;
        this.header = 'Checked record Details';
    }
    GetCheckedRecord(): void {
        this.checked_record = (
            this.treegrid as TreeGridComponent
        ).getCheckedRecords();
        if (this.checked_record.length != 0) debugger;
        var content = '';
        for (var i = 0; i < this.checked_record.length; i++) {
            content +=
                'TaskID: ' +
                this.checked_record[i].taskID +
                ', Task Name: ' +
                this.checked_record[i].taskName +
                ', Date: ' +
                this.checked_record[i].startDate +
                ', Duration: ' +
                this.checked_record[i].duration +
                '<br>';
        }
        this.message = content;
    }
    GetCheckedIndex(): void {
        var checked_index = (
            this.treegrid as TreeGridComponent
        ).getCheckedRowIndexes();
        if (checked_index.length != 0)
            this.message = 'Checked records Index:' + checked_index;
    }
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Render checkbox in checked state at initial rendering
The TreeGrid allows rendering checkboxes in a checked state during initial rendering by combining the selectCheckboxes method with the dataBound event. This enables conditional checkbox selection during the data binding process.
The following example demonstrates rendering checkboxes in a checked state at initial rendering using the dataBound event. The dataBound event triggers after initial data rendering, where checkboxes are selected using the selectCheckboxes method with specific row indexes.
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 { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
@Component({
    imports: [TreeGridModule,],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<ejs-treegrid #treegrid [dataSource]='data' height='250' [treeColumnIndex]='1' childMapping='subtasks' autoCheckHierarchy='true' (dataBound)="databound()" >
                <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 [showCheckbox]='true'></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[];
    @ViewChild('treegrid') treegrid?: TreeGridComponent;
    ngOnInit(): void {
        this.data = sampleData;
    }
    databound(): void {
        if ((this.treegrid as TreeGridComponent).initialRender) {
            var selectCheckBoxIndexes: number[] = [2, 3, 4, 5]; //Here pass the desired row indexes to select on initial rendering
            (this.treegrid as TreeGridComponent).selectCheckboxes(
                selectCheckBoxIndexes
            );
        }
    }
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Hide checkbox for parent rows
The TreeGrid allows customization of checkbox visibility for parent or child rows using the rowDataBound event when utilizing the checkbox column feature. This enables conditional hiding of checkboxes for specific rows based on custom logic.
The rowDataBound event provides access to the row element, allowing customization of checkbox visibility based on specific conditions.
The following example demonstrates hiding checkboxes for parent rows in the TreeGrid using the rowDataBound event. The checkboxes are hidden by setting the display style property based on the row’s hierarchical level.
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 { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
@Component({
    imports: [TreeGridModule,],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<ejs-treegrid #treegrid [dataSource]='data' height='250' [treeColumnIndex]='1' childMapping='subtasks' autoCheckHierarchy='true' (rowDataBound)="rowdatabound($event)" >
               <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 [showCheckbox]='true'></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[];
    @ViewChild('treegrid') treegrid?: TreeGridComponent;
    ngOnInit(): void {
        this.data = sampleData;
    }
    rowdatabound(args: any): void {
        if (args.data.hasChildRecords) {
            //Here hide the parent checkboxes
            args.row.querySelector('.e-checkbox-wrapper').style.display = 'none';
        }
    }
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));**Hide checkbox for child rows
The following example demonstrates hiding checkboxes for child rows in the TreeGrid using the rowDataBound event. The checkboxes are hidden by setting the display style property based on the row’s hierarchical level condition.
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 { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
@Component({
    imports: [TreeGridModule,],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<ejs-treegrid #treegrid [dataSource]='data' height='250' [treeColumnIndex]='1' childMapping='subtasks' autoCheckHierarchy='true' (rowDataBound)="rowdatabound($event)" >
               <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 [showCheckbox]='true'></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[];
    @ViewChild('treegrid') treegrid?: TreeGridComponent;
    ngOnInit(): void {
        this.data = sampleData;
    }
    rowdatabound(args: any): void {
        if (!args.data.hasChildRecords) {
            //Here hide the parent checkboxes
            args.row.querySelector('.e-checkbox-wrapper').style.display = 'none';
        }
    }
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Change row background color on checkbox change event
The TreeGrid enables customization of row background color when checkbox selection changes using the checkboxChange event. This provides visual feedback for selected rows based on checkbox interactions.
The checkboxChange event provides access to the row element through the getRowByIndex method, enabling background color modification based on checkbox selection state.
The following example demonstrates customizing the background color of selected rows using the checkboxChange event and getRowByIndex method. The row element is obtained and the background color is changed by adding or removing CSS classes. The styles are defined based on the CSS class in the stylesheet.
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 { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { sampleData } from './datasource';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
@Component({
    imports: [TreeGridModule,],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    encapsulation: ViewEncapsulation.None,
    template: `<ejs-treegrid #treegrid [dataSource]='data' height='250' [treeColumnIndex]='1' childMapping='subtasks' 
                autoCheckHierarchy='true' enableCollapseAll="true" (checkboxChange)="checkboxChange($event)">
                <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 [showCheckbox]='true'></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>`,
    styles: [
        `
  .bgcolor td {
    background-color: rgb(207 183 183) !important;
    color: white !important;
}`,
    ],
})
export class AppComponent implements OnInit {
    public data?: Object[];
    @ViewChild('treegrid')
    public treegrid!: TreeGridComponent;
    ngOnInit(): void {
        this.data = sampleData;
    }
    checkboxChange(args: any) {
        if (args.checked) {
            setTimeout(() => {
                const checkedRows = this.treegrid.element.querySelectorAll('.e-check');
                Array.from(checkedRows).map((row) => {
                    row?.closest('tr')?.classList.add('bgcolor');
                });
            }, 0);
        } else {
            setTimeout(() => {
                const coloredRows = this.treegrid.element.querySelectorAll('.bgcolor');
                Array.from(coloredRows).map((row) => {
                    if (row.querySelector('.e-uncheck') || row.querySelector('.e-stop')) {
                        row.classList.remove('bgcolor');
                    }
                });
            }, 0);
        }
    }
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));