Row in Angular TreeGrid component

8 Sep 202524 minutes to read

Each row represents a single record or item from a data source. Rows in a TreeGrid present data in tabular format, where each row displays a set of values representing the fields of an individual data record. Rows allow interaction with the TreeGrid data through selection, cell editing, sorting, filtering operations, and event-driven actions.

Customize row styles

Customizing row styles in the Syncfusion® TreeGrid allows you to modify row appearance to meet design requirements. This feature is useful for highlighting specific rows or changing font styles, background colors, and other properties to enhance visual appeal. You can customize row styles using CSS, properties, methods, or events provided by the Syncfusion® Angular TreeGrid component.

Using event

You can customize row appearance using the rowDataBound event. This event triggers for every row when bound to the data source. In the event handler, you receive the RowDataBoundEventArgs object containing row details. Use this object to modify row appearance, add custom elements, or perform other customizations.

The following example demonstrates how to utilize the rowDataBound event to customize row styles based on the duration column value. This example inspects the Duration column value for each row and adjusts the row style accordingly.

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 { RowDataBoundEventArgs } from '@syncfusion/ej2-grids';

@Component({
    imports: [TreeGridModule,],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<ejs-treegrid [dataSource]='data' [treeColumnIndex]='1' height='250' [enableHover]='false' (rowDataBound)='rowBound($event)' childMapping='subtasks' >
                    <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[];

    ngOnInit(): void {
        this.data = sampleData;
    }
    rowBound(args: RowDataBoundEventArgs | any) {
        if (args.data['duration'] == 0) {
            args.row.style.background = '#336c12';
        } else if (args.data['duration'] < 3) {
            args.row.style.background = '#7b2b1d';
        }
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

The queryCellInfo event can also be used to customize cells and is triggered for every cell in the TreeGrid. This is useful when you need to customize cells based on specific conditions or criteria.

Using CSS

You can apply styles to rows using CSS selectors. The TreeGrid provides class names for each row element, which you can use to apply styles to specific rows.

Customize selected row

You can customize selected row appearance using CSS. This is useful for highlighting the currently selected row to improve TreeGrid visual appeal. By default, the TreeGrid provides the CSS class .e-selectionbackground to style the selected row. You can customize this default style by overriding the .e-selectionbackground class with custom CSS styles.

To change the selected row background color, add the following CSS code to your application:

.e-treegrid .e-selectionbackground {
    background-color: #f9920b;
}

The following example demonstrates how to use the .e-selectionbackground class to style the selected row:

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';

@Component({
    imports: [TreeGridModule],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    encapsulation: ViewEncapsulation.None,
    template: `<ejs-treegrid [dataSource]='data' [treeColumnIndex]='1' height='250' [enableHover]='false' childMapping='subtasks' >
                    <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>`,
    styles: [
        `.e-treegrid .e-selectionbackground {
                    background-color: #f9920b !important;
                }`,
    ],
})
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));

Using method

The TreeGrid provides the following methods to customize the appearance of rows:

  1. getRowByIndex: Returns the HTML element of a row at the specified index. Use this method to apply custom styles to a specific row.
  2. getRows: Returns an array of all row elements in the TreeGrid. Use this method to apply custom styles to all rows or to a specific set of rows based on conditions.
  3. getRowInfo: Returns the data object and index of the row corresponding to the specified row element. Use this method to apply custom styles based on row data.
  4. getSelectedRowIndexes: Returns an array of indexes for selected rows in the TreeGrid. Use this method to apply custom styles to selected rows.
  5. getSelectedRows: Returns an array of HTML elements representing selected rows in the TreeGrid. Use this method to directly loop through selected rows and customize their styles.

The following example demonstrates how to use the getRowByIndex method to customize row appearance inside the dataBound event:

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 { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { sampleData } from './datasource';

@Component({
    imports: [TreeGridModule,],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    encapsulation: ViewEncapsulation.None,
    template: `<ejs-treegrid #treegrid [dataSource]='data' [treeColumnIndex]='1' height='250' [enableHover]='false' childMapping='subtasks' (dataBound)="customizeRows()">
                  <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[];
    @ViewChild('treegrid')
    public treegrid: TreeGridComponent | undefined;

    ngOnInit(): void {
        this.data = sampleData;
    }
    public customizeRows() {
        (
            (this.treegrid as TreeGridComponent).getRowByIndex(2) as HTMLElement
        ).style.background = 'rgb(193, 228, 234)';
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Styling alternate rows

You can customize alternate row appearance using CSS to improve data readability and make it easier to distinguish between rows. By default, the Syncfusion® TreeGrid provides the CSS class .e-altrow to style alternate rows. You can customize this default style by overriding the .e-altrow class with custom CSS styles.

To change the alternate row background color, add the following CSS code to your application stylesheet:

.e-treegrid .e-altrow {
    background-color: #fafafa;
}

Please refer to the following example:

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';

@Component({
    imports: [TreeGridModule,],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    encapsulation: ViewEncapsulation.None,
    template: `<ejs-treegrid [dataSource]='data' [treeColumnIndex]='1' height='250' [enableHover]='false' childMapping='subtasks' >
                    <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>`,
    styles: [
        `.e-treegrid .e-altrow {
                background-color: #fafafa;
            }`,
    ],
})
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));

Styling parent and child rows

You can customize parent and child row appearance by utilizing the rowDataBound event. This event is triggered for every row when bound to the data source. Within the event handler, you can access the RowDataBoundEventArgs object containing row details. Use this object to modify parent and child row appearance, add custom elements, or perform other customizations using conditions.

The following example illustrates how to utilize the rowDataBound event to customize parent and child row styles based on the hasChildRecords property value in the dataSource object. In this example, each row’s style is adjusted based on the hasChildRecords property.

Please refer to the following example:

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 { RowDataBoundEventArgs } from '@syncfusion/ej2-grids';

@Component({
    imports: [TreeGridModule],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<ejs-treegrid [dataSource]='data' [treeColumnIndex]='1' height='250' [enableHover]='false' (rowDataBound)='rowBound($event)' childMapping='subtasks' >
                    <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[];

    ngOnInit(): void {
        this.data = sampleData;
    }
    rowBound(args: RowDataBoundEventArgs | any) {
        if (!args.data.hasChildRecords) {
            //Here apply the background color of child rows
            args.row.style.background = '#33ff12';
        } else {
            //Here apply the background color of parent rows
            args.row.style.background = '#ff2f1f';
        }
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Row height

The Syncfusion® TreeGrid allows you to customize row height based on your needs. This feature is useful when you need to display more content in a row or reduce row height to fit content. You can achieve this using the rowHeight property of the TreeGrid component. This property allows you to change the height of entire TreeGrid rows to your desired value.

The following example demonstrates how to dynamically alter row height using the rowHeight property:

import { NgModule, } 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, ViewChild, ViewEncapsulation } from '@angular/core';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { sampleData } from './datasource';

@Component({
    imports: [TreeGridModule, ButtonModule],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<div>
              <button ejs-button id="small" cssClass="e-small" (click)="clickHandler($event)">
                Change height 20px</button>

              <button ejs-button id="medium" cssClass="e-small" (click)="clickHandler($event)">
                Default height 42px</button>

              <button ejs-button  id="big" cssClass="e-small" (click)="clickHandler($event)">
                Change height 60px</button>
            </div>

            <div class="control-section"  style="padding-top:20px">
              <ejs-treegrid #treegrid [dataSource]='data' [treeColumnIndex]='1' height='250' [enableHover]='false' rowHeight='42' childMapping='subtasks' >
                  <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>
            </div>`,
})
export class AppComponent implements OnInit {
    public data?: Object[];
    @ViewChild('treegrid')
    public treegrid: TreeGridComponent | undefined;
    public heightRow: { [key: string]: number } = {
        small: 20,
        medium: 40,
        big: 60,
    };
    ngOnInit(): void {
        this.data = sampleData;
    }
    clickHandler(args: MouseEvent): void {
        (this.treegrid as TreeGridComponent).rowHeight =
            this.heightRow[(args.target as HTMLElement).id];
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

  • The rowHeight property can only be used to set the height of entire TreeGrid rows. It cannot be used to set the height of individual cells within a row.
  • The rowHeight property applies height to all rows in the TreeGrid, including header and footer rows.
  • You can also set height for a specific row using the rowHeight property of the corresponding row object in the rowDataBound event.

Customize row height for particular row

Customizing row height for a particular row is useful when you want to display more content in a specific row, reduce row height to fit content, or make a specific row stand out from other rows in the TreeGrid. This can be achieved using the rowHeight property of the TreeGrid component along with the rowDataBound event.

The rowHeight property of the TreeGrid component allows you to set the height of all rows to a specific value. However, if you want to customize row height for a specific row based on row data, you can use the rowDataBound event. This event is triggered every time a request is made to access row information, element, or data, and before the row element is appended to the TreeGrid element.

In the following example, the row height for the row with taskID as ‘5’ is set as ‘90px’ using the rowDataBound event:

import { NgModule, } 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, ViewChild, ViewEncapsulation } from '@angular/core';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { RowDataBoundEventArgs } from '@syncfusion/ej2-grids';
import { sampleData } from './datasource';

@Component({
    imports: [TreeGridModule,],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<ejs-treegrid #treegrid [dataSource]='data' [treeColumnIndex]='1' height='250' childMapping='subtasks' (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></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')
    public treegrid: TreeGridComponent | undefined;

    ngOnInit(): void {
        this.data = sampleData;
    }
    public rowDataBound(args: RowDataBoundEventArgs) {
        if ((args.data as any)['taskID'] === 5) {
            args.rowHeight = 90;
        }
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

  • In virtual scrolling mode, it is not applicable to set different row heights.
  • You can customize the row height of multiple rows by checking relevant criteria in the rowDataBound event and setting the rowHeight property accordingly.
  • In the rowDataBound event handler, you can access the current row using the args.row property and set the rowHeight property for that row using the setAttribute method.

Row hover

The Row Hover feature in TreeGrid provides a visual effect when the mouse pointer hovers over rows, making it easy to highlight and identify the selected row. This feature improves data readability in the TreeGrid. The row hover effect can be enabled or disabled using the enableHover property of the TreeGrid component.

By default, the enableHover property is set to true, which means the row hovering effect is enabled. To disable the row hover effect, set the enableHover property to false.

The following example demonstrates how to enable/disable the Row Hover feature:

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 { SwitchModule } from '@syncfusion/ej2-angular-buttons'
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { sampleData } from './datasource';

@Component({
    imports: [TreeGridModule, SwitchModule],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<div style="padding:0px 0px 20px 0px">
  
            <label> Enable/Disable Row Hover</label>

            <ejs-switch id="switch" [(checked)]="enableRowHover" 
            (change)="toggleRowHover()"></ejs-switch>

            </div>
            <ejs-treegrid #treegrid [dataSource]='data' [treeColumnIndex]='1' height='250' childMapping='subtasks' [enableHover]="enableRowHover"  >
                  <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[];
    @ViewChild('treegrid')
    public treegrid: TreeGridComponent | undefined;
    public enableRowHover: boolean = true;

    ngOnInit(): void {
        this.data = sampleData;
    }
    toggleRowHover(): void {
        this.enableRowHover = !this.enableRowHover;
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

The enableHover property applies to the entire TreeGrid, not individual rows or columns.

Custom actions or items on row hover

You can execute custom actions or display custom items when hovering over rows using the rowDataBound event of the TreeGrid.

The rowDataBound event is triggered every time a request is made to access row information, element, or data, before the row element is appended to the TreeGrid element.

The following example demonstrates how to implement a custom action using the rowDataBound event. In this event, when hovering over a row, a tooltip with a button is displayed. Clicking the button reveals a custom message:

import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { RowDataBoundEventArgs } from '@syncfusion/ej2-grids';
import { sampleData } from './datasource';
import { Tooltip } from '@syncfusion/ej2-popups';
import { Button } from '@syncfusion/ej2-buttons';

@Component({
  selector: 'app-container',
  template: `<div id='show' style="padding:0px 0px 20px 0px;" >
            </div>
            <p id="message">{{message}}</p>
            <ejs-treegrid #treegrid [dataSource]='data' [treeColumnIndex]='1' height='315' childMapping='subtasks' (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></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')
  public treegrid: TreeGridComponent | undefined;
  public message: string = '';

  ngOnInit(): void {
    this.data = sampleData;
  }

  rowDataBound(args: RowDataBoundEventArgs): void {
    //Here bind mouse over event while hovering over the row
    (args.row as HTMLElement).addEventListener(
      'mouseover',
      (mouseargs: MouseEvent) => {
        //Here button creation
        const buttonId = 'element_' + (args.data as any)['taskID'];
        const buttonElement = document.createElement('button');
        buttonElement.id = buttonId;
        buttonElement.textContent = 'Row details';
        let target: any;

        //Set tooltip target
        if (mouseargs && mouseargs.target != null) {
          if ((mouseargs.target as any).classList.contains('e-rowcell')) {
            target = mouseargs.target;
          } else {
            target = null;
          }
        }
        
        //Tooltip creation
        const tooltip: Tooltip = new Tooltip(
          {
            content: buttonElement,
            width: '100px',
            height: '40px',
            opensOn: 'Hover',
          },
          target
        );
        
        //Button click event
        buttonElement.addEventListener('click', () => {
          // Handle button click here
          this.message = `Button clicked for task ID: ${
            (args.data as any)['taskID']
          }`;
        });
      }
    );
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

How to get the row information when hovering over the cell

You can retrieve row information when hovering over a specific cell. This is useful for displaying additional details or performing actions based on row data. This can be achieved using the rowDataBound event and the getRowInfo method of the TreeGrid.

  • The rowDataBound event is triggered every time a request is made to access row information, element, or data, before the row element is appended to the TreeGrid element.
  • The getRowInfo method is used to retrieve row information when hovering over a specific cell. This method takes a single parameter, which is the target element being hovered over.

The following example demonstrates how to use the rowDataBound event and getRowInfo method to retrieve row information when hovering over a cell in the Syncfusion® TreeGrid:

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 { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { RowDataBoundEventArgs } from '@syncfusion/ej2-grids';
import { sampleData } from './datasource';

@Component({
    imports: [TreeGridModule,],
    providers: [PageService, SortService, FilterService],
    standalone: true,
    selector: 'app-container',
    template: `<div id='show' style="padding:0px 0px 20px 0px;" >
            </div>

            <ejs-treegrid #treegrid [dataSource]='data' [treeColumnIndex]='1' height='250' childMapping='subtasks' (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></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')
    public treegrid: TreeGridComponent | undefined;

    ngOnInit(): void {
        this.data = sampleData;
    }
    rowDataBound(args: RowDataBoundEventArgs): void {
        (args.row as HTMLElement).addEventListener('mouseover', (e: MouseEvent) => {
            const rowInformation = (this.treegrid as TreeGridComponent).getRowInfo(
                e.target as HTMLElement
            );
            console.log(rowInformation);
            (document.getElementById('show') as HTMLElement).innerHTML = `
        <table style="border-collapse: collapse; width: 600px;">
          <tr style="border: 2px solid;">
            <td style="padding: 2px;"><b>Row Information:</b></td>
          </tr>
          <tr style="border: 2px solid; padding: 8px;">
            <th style="border: 2px solid; padding: 8px; width: 120px;"><b>Class Name</b>
            </th>
            <td style="border: 2px solid; padding: 8px;">${(rowInformation.row as Element).className
                }
            </td>
          </tr>
          <tr style="border: 2px solid;">
            <th style="border: 2px solid; padding: 8px;"><b>Row Index</b>
            </th>
            <td style="border: 2px solid; padding: 8px;">${rowInformation.rowIndex
                }
          </td>
          </tr>
         </table>`;
        });
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

The getRowInfo method can only be used in the rowDataBound event. Attempting to use it elsewhere will result in an error.

Adding a new row programmatically

The Syncfusion® TreeGrid provides a way to add new rows programmatically. This feature is useful when you want to add new records to the TreeGrid without manually entering data. This can be done using the addRecord method of the TreeGrid.

The addRecord method takes three parameters:

  • The data object representing the new row to be added
  • The index at which the new row should be inserted. If no index is specified, the new row will be added at the end of the TreeGrid.
  • The new row position, which determines where the new row should be inserted based on the newRowPosition property.

In the TreeGrid, the newRowPosition property offers the following positions to add the row:

  • Top: When you set newRowPosition to Top, the new row will be positioned at the top of the TreeGrid.
  • Bottom: When you set newRowPosition to Bottom, the new row will be positioned at the bottom of the TreeGrid.
  • Above: Setting newRowPosition to Above allows you to position the new row above a specified target row. This is particularly useful when you want to insert a row above an existing one.
  • Below: Setting newRowPosition to Below allows you to position the new row below a specified target row. This is beneficial for inserting a row immediately after another.
  • Child: Selecting Child for newRowPosition designates the new row as a child of a specified parent row. This is useful for creating hierarchical structures within the TreeGrid, where the new row becomes a subordinate of the specified parent row.

The following example demonstrates how to add a new row using the addRecord method:

import { NgModule, ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid'
import { PageService, SortService, FilterService, EditService } from '@syncfusion/ej2-angular-treegrid'
import { ButtonModule } from '@syncfusion/ej2-angular-buttons'
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { EditSettingsModel, TreeGridComponent, } from '@syncfusion/ej2-angular-treegrid';
import { RowDataBoundEventArgs } from '@syncfusion/ej2-grids';
import { sampleData } from './datasource';

@Component({
    imports: [TreeGridModule, ButtonModule,],
    providers: [PageService, SortService, FilterService, EditService],
    standalone: true,
    selector: 'app-container',
    template: `<div style="padding:0px 0px 20px 0px">
                <button ejs-button id='above' (click)='addabove()'>Add New Row as Above position</button>
                <button ejs-button id='below' (click)='addbelow()'>Add New Row as Below position</button>
                <button ejs-button id='child' (click)='addchild()'>Add New Row as Child position</button>
          </div>
            <ejs-treegrid #treegrid [dataSource]='data' [treeColumnIndex]='1' height='250' childMapping='subtasks' [editSettings]='editSettings'  >
                  <e-columns>
                      <e-column field='taskID' headerText='Task ID' textAlign='Right' isPrimaryKey="true" 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 editSettings?: EditSettingsModel;
    @ViewChild('treegrid')
    public treegrid: TreeGridComponent | undefined;

    ngOnInit(): void {
        this.data = sampleData;
        this.editSettings = {
            allowEditing: true,
            allowAdding: true,
            allowDeleting: true,
        };
    }
    addabove() {
        const newRecord = {
            taskID: this.generatetaskID(),
            taskName: this.generatetaskName(),
            startDate: this.generatestartDate(),
            duration: this.generateduration(),
        };

        (this.treegrid as TreeGridComponent).addRecord(newRecord, 0, 'Above');
    }
    addbelow() {
        const newRecord = {
            taskID: this.generatetaskID(),
            taskName: this.generatetaskName(),
            startDate: this.generatestartDate(),
            duration: this.generateduration(),
        };

        (this.treegrid as TreeGridComponent).addRecord(newRecord, 4, 'Below');
    }
    addchild() {
        const newRecord = {
            taskID: this.generatetaskID(),
            taskName: this.generatetaskName(),
            startDate: this.generatestartDate(),
            duration: this.generateduration(),
        };
        (this.treegrid as TreeGridComponent).clearSelection();
        (this.treegrid as TreeGridComponent).addRecord(newRecord, 8, 'Child');
    }
    // Generate a random taskID
    generatetaskID(): number {
        return Math.floor(1000 + Math.random() * 90000);
    }
    // Generate a random taskName
    generatetaskName(): string {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let result = '';
        for (let i = 0; i < 5; i++) {
            result += characters.charAt(
                Math.floor(Math.random() * characters.length)
            );
        }
        return result;
    }
    // Generate a random startDate
    generatestartDate(): Date {
        return new Date();
    }
    // Generate a random duration value
    generateduration(): number {
        return Math.random() * 100;
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

  • If you want to add a new record to the beginning of the data source, you can pass 0 as the second parameter to the addRecord method.
  • If you do not specify an index, the new row will be added at the end of the TreeGrid.

Show or hide a row using an external actions

In a Syncfusion® TreeGrid, you can show or hide particular rows based on external actions, such as a checkbox click. This is useful in scenarios where you want to temporarily hide certain rows from the TreeGrid without removing them from the underlying data source. This can be achieved using the getRowByIndex method of the TreeGrid and getRowsObject method of the grid object within the TreeGrid instance along with the change event of the checkbox.

The getRowsObject method returns an array of row objects that represents all rows in the TreeGrid. You can use this method to iterate through all rows and access their data and index.

The getRowByIndex method returns the HTML element of a row at the specified index. You can use this method to get a specific row and apply changes to it.

In the following example, the onCheckBoxChange method checks whether the checkbox is checked or not. If checked, the method iterates through all rows in the TreeGrid using the getRowsObject method. For each row, it checks whether the value in the Duration column equals ‘0’. If it does, the index of that row is obtained using the getRowByIndex method and hidden by setting its display style to “none”. The index of the hidden row is also added to an array called hiddenRows.

If the checkbox is unchecked, the method iterates through the hiddenRows array and shows each row by setting its display style to an empty string. The hiddenRows array is also cleared.

import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import {
  EditSettingsModel,
  TreeGridComponent,
} from '@syncfusion/ej2-angular-treegrid';
import { RowDataBoundEventArgs } from '@syncfusion/ej2-grids';
import { sampleData } from './datasource';
import { ChangeEventArgs } from '@syncfusion/ej2-buttons';

@Component({
  selector: 'app-container',
  encapsulation: ViewEncapsulation.None,
  template: `<div style="padding:2px 0px 0px 0px">
             <ejs-checkbox #checkbox label='Show / Hide Row' 
                  (change)="onCheckBoxChange($event)"></ejs-checkbox>
            </div>
            <div><p id="message"  style="color:red; text-align:center;font-weight: bold;">{{ message }}</p> </div>

            <ejs-treegrid #treegrid [dataSource]='data' [treeColumnIndex]='1' height='315' childMapping='subtasks' >
                  <e-columns>
                      <e-column field='taskID' headerText='Task ID' textAlign='Right' isPrimaryKey="true" 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 rowIndex?: number;
  public hiddenRows: number[] = [];
  @ViewChild('treegrid')
  public treegrid: TreeGridComponent | undefined;
  public message?: string = '';

  ngOnInit(): void {
    this.data = sampleData;
  }
  public onCheckBoxChange(args: ChangeEventArgs) {
    if (args.checked) {
      for (let i = 0; i < (this.treegrid as TreeGridComponent).grid.getRowsObject().length;i++) {
        if (((this.treegrid as TreeGridComponent).grid.getRowsObject()[i].data as any).duration === 0
        ) {
          // check the row value
          this.rowIndex = (this.treegrid as TreeGridComponent).grid.getRowsObject()[i].index; 
          //get particular row index
          ((this.treegrid as TreeGridComponent).getRowByIndex(this.rowIndex) as HTMLElement).style.display = 'none'; //hide row
          this.hiddenRows.push(this.rowIndex as number); // add row index to hiddenRows array
        }
      }
      if (this.hiddenRows.length > 0) {
       this.message = `Rows with a duration column value of '0' have been hidden`;
      }
    } else {
      // Show hidden rows
      this.hiddenRows.forEach((rowIndex: number) => {
        ((this.treegrid as TreeGridComponent).getRowByIndex(rowIndex) as HTMLElement).style.display = '';
      });
      this.hiddenRows = [];
      this.message = 'Show all hidden rows';
    }
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

How to get the row data and element

The TreeGrid provides several methods to retrieve row data and elements. This feature is useful when you need to access specific rows, perform custom operations, or manipulate the data displayed in the grid.

  1. getRowByIndex: This method returns the HTML element of a row at the specified index. It can be used to retrieve the element of a specific row in the TreeGrid.

     const rowElement = this.treegrid.getRowByIndex(rowIndex);
  2. getRowInfo: This method allows you to retrieve row information based on a cell target element.

     const rowInformation = this.treegrid.getRowInfo(targetElement);
  3. getRows: This method returns an array of all row elements in the TreeGrid. If you need to retrieve row data and elements, you can combine the getRows method with the getRowInfo method.

      const rowElements = this.treegrid.getRows();
  4. getSelectedRowIndexes: This method allows you to retrieve the collection of indexes of the selected rows. However, it does not directly provide the row elements and associated data. To access the row elements and data of the selected rows, you can combine the getSelectedRowIndexes method with getRowByIndex and getRowInfo method.

     const selectedIndexes = this.treegrid.getSelectedRowIndexes();
  5. getSelectedRows: This method returns an array of HTML elements representing the selected rows in the TreeGrid. By iterating over this array, you can access each row element and data using the getRowInfo method. This way, you can access both the row elements and their associated data for the selected rows.

     const selectedRowElements = this.treegrid.getSelectedRows();

    See also