Checkbox Selection in EJ2 TypeScript Tree Grid

24 Sep 202624 minutes to read

Checkbox selection provides an option to select multiple Tree Grid records with help of checkbox in each row.

To render the checkbox in each Tree Grid row, you need to use checkbox column with type as checkbox using the column type property.

import { TreeGrid } from '@syncfusion/ej2-treegrid';
import { sampleData } from './datasource.ts';

let treeGridObj: TreeGrid = new TreeGrid({
    dataSource: sampleData,
    childMapping: 'subtasks',
    height: 315,
    treeColumnIndex: 2,
    columns: [
            { type: 'checkbox', width: 60 },
            { field: 'taskID', headerText: 'Task ID', width: 90, textAlign: 'Right' },
            { field: 'taskName', headerText: 'Task Name', width: 150 },
            { field: 'duration', headerText: 'Duration', width: 80, textAlign: 'Right' },
            { field: 'progress', headerText: 'progress', width: 80, textAlign: 'Right' }
    ]
});

treeGridObj.appendTo('#TreeGrid');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/35.1.37/material3.css" rel="stylesheet" />
    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='TreeGrid'></div>        
    </div>
</body>
</html>

  • By default, selection is allowed by clicking a Tree Grid row or checkbox in that row. To allow selection only through checkbox, you can set the
    selectionSettings.checkboxOnly property to true.
  • Selection can be persisted in all the operations using the selectionSettings.persistSelection property. For persisting selection on the treegrid, any one of the columns should be defined as a primary key using the columns.isPrimaryKey property.

Checkbox selection mode

In checkbox selection, selection can also be done by clicking on rows. This selection provides two types of checkbox selection mode which can be set by using the following API selectionSettings.checkboxMode. The modes are:

  • Default: This is the default value of the checkboxMode. In this mode, user can select multiple rows by clicking rows one by one.
  • ResetOnRowClick: In ResetOnRowClick mode, when user clicks on a row it will reset previously selected row. Also you can perform multiple-selection in this mode by press and hold CTRL key and click the desired rows. To select range of rows, press and hold the SHIFT key and click the rows.
import { TreeGrid } from '@syncfusion/ej2-treegrid';
import { sampleData } from './datasource.ts';

let treeGridObj: TreeGrid = new TreeGrid({
    dataSource: sampleData,
    childMapping: 'subtasks',
    height: 270,
    treeColumnIndex: 2,
    selectionSettings: {checkboxMode: 'ResetOnRowClick'},
    columns: [
            { type: 'checkbox', width: 60 },
            { field: 'taskID', headerText: 'Task ID', width: 90, textAlign: 'Right' },
            { field: 'taskName', headerText: 'Task Name', width: 180 },
            { field: 'duration', headerText: 'Duration', width: 80, textAlign: 'Right' },
            { field: 'progress', headerText: 'progress', width: 80, textAlign: 'Right' }
    ]
});

treeGridObj.appendTo('#TreeGrid');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/35.1.37/material3.css" rel="stylesheet" />
    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='TreeGrid'></div>        
    </div>
</body>
</html>

Checkbox Selection feature is intended for row selection only; it is not compatible with cell selection mode.

Conditional row selection

The TreeGrid supports conditional row selection through the isRowSelectable callback. This allows selection to be controlled by custom business logic, ensuring that only rows meeting specific conditions can be selected. The callback receives each row’s data and returns “true” to allow selection or “false” to prevent it.

Local data: The callback runs once when the TreeGrid initializes and evaluates all records because the full dataset is already available on the client.

Remote data: The callback runs only for the rows displayed on the current page when the TreeGrid first loads. It runs again whenever the TreeGrid fetches new data such as during paging, filtering, or sorting to re-evaluate the newly visible rows.

In the following sample, selection is disabled for rows where the “Progress” column has the value “Completed”.

import { TreeGrid, Selection, VirtualScroll } from '@syncfusion/ej2-treegrid';
import { taskData } from './datasource.ts';

TreeGrid.Inject(Selection, VirtualScroll);

let treegrid: TreeGrid = new TreeGrid({
  dataSource: taskData,
  idMapping: 'TaskID',
  parentIdMapping: 'ParentID',
  treeColumnIndex: 1,
  height: 600,
  enableVirtualization: true,
  selectionSettings: { persistSelection: true },
  columns: [
    { type: 'checkbox', width: 50 },
    { field: 'Task', headerText: 'Task', width: 300 },
    { field: 'TaskID', isPrimaryKey: true, visible: false },
    { field: 'AssignedTo', headerText: 'Assigned To', width: 140 },
    { field: 'StartDate', headerText: 'Start', width: 180, format: 'yMd' },
    { field: 'DueDate', headerText: 'Due', width: 180, format: 'yMd' },
    { field: 'Priority', headerText: 'Priority', width: 90 },
    { field: 'Progress', headerText: 'Status', width: 110 }
  ]
});

treegrid.appendTo('#TreeGrid');

treegrid.grid.isRowSelectable = function (data: any, columns: any) {
    return data.Progress !== 'Completed';
};
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/35.1.37/material3.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='TreeGrid'></div>        
    </div>
</body>
</html>

Hierarchy checkbox selection

The hierarchy checkbox enables cascading selection of parent and child rows in Tree Grid. When a parent row checkbox is selected, all its child records are automatically selected, and the parent state updates based on children selection. To enable hierarchy checkbox selection, set the showCheckbox property to true in a column and configure the hierarchyCheckboxMode property. By default, hierarchy checkbox mode is set to self.

The available modes are displayed in the following table.

Item Description
self Only the targeted row is selected; children and parent are not affected.
hierarchy Selection cascades to all descendants and adjusts the parent state accordingly.
filteredHierarchy Behaves like hierarchy, but applies the cascade only to records matching the current filter or search criteria.
import { TreeGrid, Filter, Toolbar, Edit } from '@syncfusion/ej2-treegrid';
import { showCheckBoxData } from './datasource.ts';
import { DropDownList } from '@syncfusion/ej2-dropdowns';

/**
 * CheckBox Selection TreeGrid sample
 */


    TreeGrid.Inject(Filter, Toolbar, Edit);
    let treegrid: TreeGrid = new TreeGrid({
        dataSource: showCheckBoxData,
        childMapping: "subTasks",
        treeColumnIndex: 1,
        toolbar: ["Delete", "Search"],
        editSettings: { allowDeleting:true },
        hierarchyCheckboxMode: "self",
        allowFiltering: true,
        height: 380,
        columns: [
            {
                field: "taskID",
                visible: false,
                isPrimaryKey: true
            },
            {
                field: "taskName",
                headerText: "Task Name",
                width: 270,
                showCheckbox: true
            },
            {
                field: "assignee",
                headerText: "Employee",
                width: 180
            },
            {
                field: 'designation',
                headerText: 'Designation',
                width: 220
            },
            {
                field: "priority",
                headerText: "Priority",
                width: 140
            },
            {
                field: "status",
                headerText: "Status",
                width: 120,
                textAlign: "Center"
            },
            {
                field: "progress",
                headerText: "Progress",
                width: 120,
                textAlign: "Right"
            },
        ],
        queryCellInfo: (args: any) => {
            if (args.column.field === "status") {
                args.cell.innerHTML = `<span class="status-badge ${args.data.status
                    .toLowerCase()
                    .replace(/\s+/g, "-")}">
                ${args.data.status}
                </span>`;
            }
        },
    });
    treegrid.appendTo("#TreeGrid");

    const dropDownColumns = new DropDownList({
        dataSource: [
            { id: "Self", name: "Self" },
            { id: "Hierarchy", name: "Hierarchy" },
            { id: "FilteredHierarchy", name: "Filtered Hierarchy" },
        ],
        fields: { text: "name", value: "id" },
        value: "Self",
        width: "180px",
        change: function (e:any) {
            if (e.value === "Hierarchy") {
                treegrid.hierarchyCheckboxMode = "hierarchy";
            } else if (e.value === "FilteredHierarchy") {
                treegrid.hierarchyCheckboxMode = "filteredHierarchy";
            } else if (e.value === "Self") {
                treegrid.hierarchyCheckboxMode = "self";
            }
        },
    });
    dropDownColumns.appendTo("#hierarchyModes");
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/35.1.37/material3.css" rel="stylesheet" />
    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div class="control-section">
        <div class="content-wrapper">
            <div class="checkboxprop">
                <div class="checkboxmode">
                    <span>
                        Hierarchy Checkbox Mode
                    </span>
                    <div class="checkboxmode"><input type="text" tabindex="1" id="hierarchyModes"></div>
                </div>
            </div>
            <div id="TreeGrid" role="grid" aria-label="Tree Grid"></div>
        </div>
    </div>

    <style>
        .e-bigger.bootstrap5 .e-treegrid .e-hierarchycheckbox .e-frame,
        .e-bigger.bootstrap5-dark .e-treegrid .e-hierarchycheckbox .e-frame,
        .e-bigger.bootstrap4 .e-treegrid .e-hierarchycheckbox .e-frame {
            height: 17px;
            width: 17px;
        }

        .checkboxprop {
            padding-bottom: 5px;
        }

        .checkboxmode {
            display: inline-block;
        }

        .checkboxprop>.checkboxmode {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .checkboxprop>.checkboxmode>span {
            white-space: nowrap;
        }

        .checkboxprop>.checkboxmode>.checkboxmode {
            flex: 0 0 180px;
            width: 180px;
        }

        .status-badge {
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            display: inline-block;
        }

        .completed {
            background: #dcfce7;
            color: #15803d;
        }

        .in-progress {
            background: #dbeafe;
            color: #1d4ed8;
        }

        .not-started {
            background: #f3f4f6;
            color: #4b5563;
        }

        .under-review {
            background: #fef3c7;
            color: #b45309;
        }

        .blocked {
            background: #fee2e2;
            color: #dc2626;
        }
    </style>
</body>
</html>