Row in Angular Grid Component

17 Sep 202524 minutes to read

Rows in the Syncfusion Angular Grid represent individual records from a data source, presenting information in a structured tabular format. Each row displays field values from a single data record, enabling users to interact with data through selection, editing, sorting, filtering, and custom operations. The Grid provides comprehensive row management capabilities including styling customization, height control, hover effects, frozen row functionality, and programmatic data manipulation.

Key Row Management Features:

  • Dynamic row styling based on data conditions
  • Customizable row heights for optimal content display
  • Interactive hover effects and visual feedback
  • Frozen rows for persistent header information
  • Programmatic row addition, modification, and visibility control
  • Comprehensive row data access and manipulation methods

Row Style Customization

Row styling customization allows modification of row appearance to meet specific design requirements and enhance visual appeal. The Grid supports multiple approaches for row styling including event-driven customization, CSS-based styling, and method-based manipulation.

Event-Based Row Styling

The rowDataBound event provides the most flexible approach for row styling, triggering for every row during data binding. This event handler receives RowDataBoundEventArgs containing row details, enabling conditional styling based on data values.

The following example demonstrates conditional row styling based on the Freight column value, applying different CSS classes for various data ranges:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule,RowDataBoundEventArgs,DetailRowService } from '@syncfusion/ej2-angular-grids'
import { Component, OnInit } from '@angular/core';
import { data , columnDataType} from './datasource';

@Component({
    imports: [GridModule],
    providers: [DetailRowService],
    standalone: true,
    selector: 'app-root',
    template: `<ejs-grid #grid [dataSource]='data' [enableHover]='false' 
              [allowSelection]='false' [height]='315' (rowDataBound)='rowDataBound($event)'>
                    <e-columns>
                        <e-column field='OrderID' headerText='Order ID' textAlign='Right'
                        width=100></e-column>
                        <e-column field='CustomerID' headerText='Customer ID' width=120>
                        </e-column>
                        <e-column field='Freight' headerText='Freight' textAlign='Right' 
                        format='C2' width=80></e-column>
                        <e-column field='ShipCity' headerText='Ship City' width=130 >
                        </e-column>
                    </e-columns>
                </ejs-grid>`
})
export class AppComponent implements OnInit {

    public data?: object[];

    ngOnInit(): void {
        this.data = data;
    }
    rowDataBound(args: RowDataBoundEventArgs) {
        const Freight = 'Freight';
        if ((args.data as columnDataType)[Freight] < 30) {
            (args.row as Element).classList.add('below-30');
        } else if ((args.data as columnDataType)[Freight] >= 30 && ((args.data as columnDataType)[Freight] < 80)) {
            (args.row as Element).classList.add('below-80');
        } else {
            (args.row as Element).classList.add('above-80');
        }
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

The queryCellInfo event provides similar functionality for individual cell customization and can be combined with row-level styling for comprehensive appearance control.

CSS-Based Row Styling

CSS selectors provide a declarative approach for row styling, utilizing Grid-specific classes for consistent appearance modifications across the application.

Alternate Row Customization

Alternate row styling improves data readability by creating visual distinction between consecutive rows. The Grid provides the .e-altrow CSS class for alternate row targeting, which can be customized with application-specific styles.

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

The following example demonstrates alternate row styling implementation:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule } from '@syncfusion/ej2-angular-grids'
import { Component, OnInit } from '@angular/core';
import { data } from './datasource';

@Component({
    imports: [GridModule],
    standalone: true,
    selector: 'app-root',
    template: `<ejs-grid [dataSource]='data'>
                <e-columns>
                    <e-column field='OrderID' headerText='Order ID' textAlign='Right' 
                    width=120></e-column>
                    <e-column field='CustomerID' headerText='Customer ID' width=140>
                    </e-column>
                    <e-column field='Freight' headerText='Freight' textAlign='Right' 
                    format='C' width=120></e-column>
                    <e-column field='OrderDate' headerText='Order Date' textAlign='Right'
                    format='yMd' width=140></e-column>
                </e-columns>
               </ejs-grid>`
})
export class AppComponent implements OnInit {

    public data?: object[];

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

Selected Row Customization

Selected row styling enhances user interaction feedback by highlighting the currently selected row. The .e-selectionbackground class provides the default selection styling, which can be overridden for custom appearance.

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

The following example demonstrates selected row styling customization:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule } from '@syncfusion/ej2-angular-grids'
import { Component, OnInit } from '@angular/core';
import { data } from './datasource';

@Component({
    imports: [GridModule],
    standalone: true,
    selector: 'app-root',
    template: `<ejs-grid [dataSource]='data'>
                <e-columns>
                    <e-column field='OrderID' headerText='Order ID' textAlign='Right'
                    width=120></e-column>
                    <e-column field='CustomerID' headerText='Customer ID' width=140>
                    </e-column>
                    <e-column field='Freight' headerText='Freight' textAlign='Right'
                    format='C' width=120></e-column>
                    <e-column field='OrderDate' headerText='Order Date' textAlign='Right' 
                    format='yMd' width=140></e-column>
                </e-columns>
               </ejs-grid>`,
    styles: [`
        .e-grid .e-selectionbackground {
            background-color: #f9920b;
        }
    `]
})
export class AppComponent implements OnInit {
    
    public data?: object[];

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

Method-Based Row Styling

The Grid provides comprehensive methods for programmatic row styling and manipulation:

Row Access Methods:

  1. getRowByIndex: Returns HTML element of a row at the specified index
  2. getRowIndexByPrimaryKey: Returns row index based on primary key value
  3. getRows: Returns array of all row elements
  4. getRowInfo: Returns row data object and index from row element
  5. getSelectedRowIndexes: Returns array of selected row indexes
  6. getSelectedRows: Returns array of selected row HTML elements

The following example demonstrates method-based row styling using getRowByIndex within the dataBound event:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule,GridComponent } from '@syncfusion/ej2-angular-grids'
import { Component, OnInit, ViewChild } from '@angular/core';
import { data } from './datasource';

@Component({
  imports: [GridModule],
  standalone: true,
  selector: 'app-root',
  template: `<ejs-grid #grid [dataSource]="data" (dataBound)="customizeRows()">
                <e-columns>
                    <e-column field="OrderID" headerText="Order ID" textAlign="Right"
                    width="100"></e-column>
                    <e-column field="CustomerID" headerText="Customer ID" width="120">
                    </e-column>
                    <e-column field="Freight" headerText="Freight" textAlign="Right" 
                    format="C" width="100">
                    </e-column>
                    <e-column field="OrderDate" headerText="Order Date" textAlign="Right" 
                    format="yMd" width="100"></e-column>
                </e-columns>
            </ejs-grid>`,
})
export class AppComponent implements OnInit {

  public data?: object[];
  @ViewChild('grid')
    public grid?: GridComponent;

  ngOnInit(): void {
    this.data = data;
  }
  public customizeRows() {
    ((this.grid as GridComponent).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));

Row Height

Row height customization enables optimal content display and improved visual hierarchy within the Grid. The rowHeight property provides uniform height control, while event-driven approaches enable row-specific height customization.

The following example demonstrates dynamic row height adjustment:

import { Component, ViewChild } from '@angular/core';
import { GridModule,GridComponent } from '@syncfusion/ej2-angular-grids';
import { orderDetails } from './datasource';
import { ButtonModule } from '@syncfusion/ej2-angular-buttons';

@Component({
  imports: [ GridModule, ButtonModule],
  standalone: true,
  selector: 'app-root',
  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-grid #grid [dataSource]='data' rowHeight='42' height='400'>
              <e-columns>
                  <e-column field='OrderID' headerText='Order ID' width='120' textAlign='Right'>
                  </e-column>
                  <e-column field='CustomerName' headerText='Customer Name' width='150'>
                  </e-column>
                  <e-column field='OrderDate' headerText='Order Date' width='130' format="yMd" 
                  textAlign='Right'> </e-column>
                  <e-column field='Freight' headerText='Freight' width='120' format='C2'
                  textAlign='Right'></e-column>
                  <e-column field='ShippedDate' headerText='Shipped Date' width='140' format='yMd' 
                  textAlign='Right'></e-column>
                  <e-column field='ShipCountry' headerText='Ship Country' width='150'></e-column> 
              </e-columns>
          </ejs-grid>
      </div>`
})
export class AppComponent {

  public data?: Object[];

  @ViewChild('grid')
  public grid?: GridComponent;
  public heightRow: { [key: string]: number } = {
    small: 20,
    medium: 40,
    big: 60
  };
  ngOnInit(): void {
    this.data = orderDetails;
  }

  clickHandler(args: MouseEvent): void {
    (this.grid as GridComponent).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 applies uniform height to all rows, including header and footer rows.
  • Individual row height cannot be controlled through the rowHeight property alone.
  • Row-specific height customization requires the rowDataBound event approach.

Individual Row Height Customization

Individual row height customization addresses scenarios requiring variable content display or specific row emphasis. This approach combines the rowHeight property with the rowDataBound event for conditional height application.

The following example sets custom height for rows with OrderID value of ‘10249’:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule,RowDataBoundEventArgs,DetailRowService} from '@syncfusion/ej2-angular-grids'
import { Component, OnInit } from '@angular/core';
import { data , columnDataType} from './datasource';

@Component({
    imports: [ GridModule],
    providers: [DetailRowService],
    standalone: true,
    selector: 'app-root',
    template: `<ejs-grid #grid [dataSource]='data' [height]='315' 
               (rowDataBound)='rowDataBound($event)'>
                    <e-columns>
                        <e-column field='OrderID' headerText='Order ID' textAlign='Right' 
                        width=100></e-column>
                        <e-column field='CustomerID' headerText='Customer ID' width=120>
                        </e-column>
                        <e-column field='Freight' headerText='Freight' textAlign='Right' 
                        format='C2' width=80></e-column>
                        <e-column field='ShipCity' headerText='Ship City' width=130 >
                        </e-column>
                    </e-columns>
                </ejs-grid>`
})
export class AppComponent implements OnInit {

    public data?: object[];

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

  • Virtual scrolling mode does not support variable row heights due to performance optimization requirements.
  • Multiple rows can be customized by implementing appropriate conditional logic within the rowDataBound event handler.
  • Row height modification uses the args.row property and setAttribute method for implementation.

Row Hover

Row hover functionality provides visual feedback during mouse interaction, enhancing data readability and user experience. The enableHover property controls hover effect availability across the entire Grid.

The following example demonstrates hover effect control through a Switch component:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule,GridComponent,DetailRowService } from '@syncfusion/ej2-angular-grids'
import { SwitchModule } from '@syncfusion/ej2-angular-buttons'
import { Component, OnInit,ViewChild } from '@angular/core';
import { data } from './datasource';
import { ChangeEventArgs } from '@syncfusion/ej2-navigations';

@Component({
  imports: [GridModule,SwitchModule],
  providers: [DetailRowService],
  standalone: true,
  selector: 'app-root',
  template: `<div style="padding:0px 0px 20px 0px">
            <label> Enable/Disable Row Hover</label>
            <ejs-switch id="switch" [checked]="true" 
            (change)="toggleRowHover($event)"></ejs-switch>
            </div>
            <ejs-grid #grid [dataSource]='data'>
              <e-columns>
                  <e-column field='OrderID' headerText='Order ID' textAlign='Right' 
                  width=120></e-column>
                  <e-column field='CustomerID' headerText='Customer ID' width=150>
                  </e-column>
                  <e-column field='ShipCity' headerText='Ship City' width=150></e-column>
                  <e-column field='ShipName' headerText='Ship Name' width=150></e-column>
              </e-columns>
            </ejs-grid>`
          
})
export class AppComponent implements OnInit {

  public data?: object[];
  @ViewChild('grid') public grid?: GridComponent;

  ngOnInit(): void {
    this.data = data;
  }
  toggleRowHover(args:CustomChangeEventArgs): void {
   (this.grid as GridComponent).enableHover = args.checked;
  }
  
}

interface CustomChangeEventArgs extends ChangeEventArgs {
  checked: boolean;
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

The enableHover property affects the entire Grid and cannot be applied to individual rows or columns.

How to get the row information when hovering over the cell

Row information retrieval during hover interactions enables dynamic content display and contextual actions. This functionality combines the rowDataBound event with the getRowInfo method for comprehensive row data access.

  • 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 Grid element.
  • The getRowInfo method is used to retrieve the row information when hovering over a specific cell. This method takes a single parameter, which is the target element that is being hovered over.

Here’s an example that demonstrates how to use the rowDataBound event and getRowInfo method to retrieve the row information when hovering over a cell in the Syncfusion Grid.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule } from '@syncfusion/ej2-angular-grids'
import { TooltipModule } from '@syncfusion/ej2-angular-popups'

import { Component, OnInit, ViewChild } from '@angular/core';
import { GridComponent, RowDataBoundEventArgs } from '@syncfusion/ej2-angular-grids';
import { data } from './datasource';

@Component({
imports: [
        
        GridModule,
        TooltipModule
    ],

standalone: true,
  selector: 'app-root',
  template: `<div id='show' style="padding:0px 0px 20px 0px;" ></div>
            <ejs-grid #grid [dataSource]='data' (rowDataBound)='rowDataBound($event)'>
                <e-columns>
                    <e-column field='OrderID' headerText='Order ID' textAlign='Right' 
                    width=120></e-column>
                    <e-column field='CustomerID' headerText='Customer ID' width=140>
                    </e-column>
                    <e-column field='Freight' headerText='Freight' textAlign='Right' 
                    format='C' width=120></e-column>
                    <e-column field='OrderDate' headerText='Order Date' textAlign='Right'
                    format='yMd' width=120></e-column>
                </e-columns>
            </ejs-grid>`,
})
export class AppComponent implements OnInit {

  @ViewChild('grid', { static: true }) public grid?: GridComponent;
  public data?: object[];

  ngOnInit(): void {
    this.data = data;
  }
  rowDataBound(args: RowDataBoundEventArgs): void {
    (args.row as HTMLElement).addEventListener('mouseover', (e: MouseEvent) => {
      const rowInformation = (this.grid as GridComponent).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 requires execution within the rowDataBound event context for proper functionality.

Row pinning (Frozen)

Frozen rows functionality maintains specific rows in fixed positions during vertical scrolling, ensuring important information remains visible within large datasets. The frozenRows property specifies the number of rows to freeze from the top of the Grid.

The following example freezes the top two rows:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, FreezeService, SelectionService, EditService, ToolbarService } from '@syncfusion/ej2-angular-grids'
import { NumericTextBoxAllModule, RatingAllModule } from '@syncfusion/ej2-angular-inputs'
import {  ButtonModule } from '@syncfusion/ej2-angular-buttons'


import { Component, OnInit, ViewChild } from '@angular/core';
import { GridComponent, } from '@syncfusion/ej2-angular-grids';
import { NumericTextBoxComponent } from '@syncfusion/ej2-angular-inputs';
import { data } from './datasource';

@Component({
imports: [
        
        GridModule,
        NumericTextBoxAllModule,
        RatingAllModule,
        ButtonModule
    ],

providers: [FreezeService, SelectionService, EditService, ToolbarService],
standalone: true,
  selector: 'app-root',
  template: `<div style="display: flex">
    <label style="padding: 10px 10px 26px 0"> Change the frozen rows: </label>
    <ejs-numerictextbox
      #frozenRows
      min="0"
      max="5"
      [validateDecimalOnType]="true"
      decimals="0"
      format="n"
      value="2"
      width="100px"
    ></ejs-numerictextbox>
    <div>
      <button style="margin-left:5px" ejs-button (click)="frozenRowsFn()">
        Update
      </button>
    </div>
  </div>
  <ejs-grid #grid style="padding: 5px 5px" [dataSource]='data' height=315 [frozenRows]='2' [allowSelection]='false'  [enableHover]='false'>
    <e-columns>
      <e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
      <e-column field='CustomerID' headerText='Customer ID' width=100></e-column>
      <e-column field='OrderDate' headerText='Order Date' width=100 format='yMd' textAlign='Right'></e-column>
      <e-column field='EmployeeID' headerText='Employee ID' textAlign='Right' width=80></e-column>
      <e-column field='ShipName' headerText='Ship Name' width=130></e-column>
      <e-column field='ShipAddress' headerText='Ship Address' width=140></e-column>
      <e-column field='ShipCity' headerText='Ship City' width=100></e-column>
      <e-column field='ShipCountry' headerText='Ship Country' width=100></e-column>
      <e-column field='ShipRegion' headerText='Ship Region' width=80></e-column>
      <e-column field='ShipPostalCode' headerText='Ship Postal Code' width=110></e-column>
      <e-column field='Freight' headerText='Freight' width=80></e-column>
    </e-columns>
  </ejs-grid>`
})
export class AppComponent implements OnInit {

  public data?: object[];
  @ViewChild('grid')
  public grid?: GridComponent;
  @ViewChild('frozenRows')
  public frozenRows?: NumericTextBoxComponent;

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

  frozenRowsFn() {
    (this.grid as GridComponent).frozenRows = (this.frozenRows as NumericTextBoxComponent).value;
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

  • Frozen rows must remain within the visible viewport area.
  • Row virtualization is supported with frozen rows for enhanced performance.
  • Frozen rows functionality can be combined with frozen columns for complete grid section freezing.

Frozen Row Line Color Customization

Frozen row visual appearance can be customized through CSS styling to match application design requirements. The .e-frozenrow-border class provides the styling target for frozen row borders.

.e-grid .e-frozenrow-border {
    background-color: rgb(5, 114, 47);
}

The following example demonstrates frozen row border customization:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, FreezeService, SelectionService, EditService, ToolbarService } from '@syncfusion/ej2-angular-grids'


import { Component, OnInit } from '@angular/core';
import { data } from './datasource';

@Component({
imports: [
        
        GridModule,
    ],

providers: [FreezeService, SelectionService, EditService, ToolbarService],
standalone: true,
    selector: 'app-root',
    template: `<ejs-grid [dataSource]='data' height=315 [allowSelection]='false' [frozenRows]='3' [enableHover]='false'>
    <e-columns>
      <e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
      <e-column field='CustomerID' headerText='Customer ID' width=100 ></e-column>
      <e-column field='OrderDate' headerText='Order Date' width=100 format='yMd' textAlign='Right'></e-column>
      <e-column field='EmployeeID' headerText='Employee ID' textAlign='Right' width=80></e-column>
      <e-column field='ShipName' headerText='Ship Name' width=130></e-column>
      <e-column field='ShipAddress' headerText='Ship Address' width=140 ></e-column>
      <e-column field='ShipCity' headerText='Ship City' width=100></e-column>
      <e-column field='ShipCountry' headerText='Ship Country' width=100></e-column>
      <e-column field='ShipRegion' headerText='Ship Region' width=80></e-column>
      <e-column field='ShipPostalCode' headerText='Ship Postal Code' width=110></e-column>
      <e-column field='Freight' headerText='Freight' width=80></e-column>
    </e-columns>
  </ejs-grid>`
})
export class AppComponent implements OnInit {

    public data?: object[];
  
    ngOnInit(): void {
      this.data = data
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Deprecated methods

Previous Current Explanation
getMovableRows() gridInstance.getMovableRows()[0].querySelectorAll(‘.e-unfreeze’) getRows() gridInstance.getRows()[0].querySelectorAll(‘.e-unfreeze’) The previous architecture used separate tables for left, right, and movable contents, returning only movable rows when calling the method, whereas the current architecture combines them into one table, returning all rows and introduces the e-unfreeze class for selecting movable rows
getFrozenRightRows() gridInstance.getFrozenRightRows()[0].querySelectorAll(‘.e-rightfreeze’) getRows() gridInstance.getRows()[0].querySelectorAll(‘.e-rightfreeze’) In the previous architecture, it returned only the table rows from the right freeze table, but in the current architecture, all rows of the entire table are returned, introducing the e-rightfreeze class for selecting right freeze rows.
getMovableRowByIndex()
getFrozenRowByIndex()
getFrozenRightRowByIndex()
getRowByIndex() gridInstance.getRowByIndex(1).querySelectorAll(‘.e-unfreeze’) In the previous architecture, separate methods were used to select rows from different table sections, while in the current architecture, the getMovableRowByIndex(), getFrozenRightRowByIndex(), and getFrozenRowByIndex() methods now return the same table row based on the given index. Additionally, class names for table cells (td’s) have been separated into e-leftfreeze, e-unfreeze, and e-rightfreeze, making it easier to customize cells within a row.
getMovableCellFromIndex()
getFrozenRightCellFromIndex()
getCellFromIndex() gridInstance.getCellFromIndex(1,1) In the previous approach, the getMovableCellFromIndex() method was used to choose a specific cell within the movable table, and the getFrozenRightCellFromIndex() method was utilized to target a particular cell within the right freeze table. However, in the current architecture, you have the flexibility to select a specific cell in either the movable or right freeze table by using both the getFrozenRightCellFromIndex() and getMovableCellFromIndex() methods. This new method simplifies the process of selecting and retrieving specific cells within these tables, offering more versatility and convenience.
getMovableDataRows()
getFrozenRightDataRows()
getFrozenDataRows()
getDataRows() gridInstance.getDataRows()[0].querySelectorAll(‘.e-unfreeze’) In the previous approach, there were separate methods (getMovableDataRows(), getFrozenRightDataRows(), and getFrozenDataRows()) for obtaining viewport data rows from the freeze, movable, and right tables individually. However, in the new approach, these methods have been enhanced to return the entire viewport data rows for all sections together, simplifying data retrieval. You can now extract specific cells within these rows using selectors such as e-leftfreeze for the left freeze, e-unfreeze for the movable, and e-rightfreeze for the right freeze tables, providing greater flexibility in working with the data.
getMovableColumnHeaderByIndex()
getFrozenRightColumnHeaderByIndex()
getFrozenLeftColumnHeaderByIndex()
getColumnHeaderByIndex() gridInstance.getColumnHeaderByIndex(1) In the previous architecture, the methods selected movable, right freeze, and left freeze headers separately. However, in the new approach, when using the getMovableColumnHeaderByIndex(), getFrozenRightColumnHeaderByIndex(), and getFrozenLeftColumnHeaderByIndex() methods, you will still obtain the same results as in the previous architecture.

Validation messages displayed in frozen sections prevent scrolling until resolved, ensuring data integrity during editing operations.

Limitations

  • Frozen row is not compatible with the following features:
    1. Autofill

Adding a new row programmatically

Programmatic row addition enables dynamic data insertion without manual user input. The addRecord method provides flexible row insertion capabilities with optional index specification.

Method Parameters:

  • data: Object representing the new row data
  • index (optional): Insertion position. If omitted, the row is added at the end

The following example demonstrates programmatic row addition:

import { NgModule } from '@angular/core'
import { FormsModule } from '@angular/forms'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, EditService} from '@syncfusion/ej2-angular-grids'
import { TimePickerModule } from '@syncfusion/ej2-angular-calendars'
import { TextBoxModule } from '@syncfusion/ej2-angular-inputs'
import { ButtonModule } from '@syncfusion/ej2-angular-buttons'

import { Component, OnInit, ViewChild } from '@angular/core';
import { EditSettingsModel, GridComponent } from '@syncfusion/ej2-angular-grids';
import {data} from './datasource';

@Component({
imports: [
        
        GridModule,
        FormsModule,
        TimePickerModule,
        FormsModule,
        TextBoxModule,
        ButtonModule 
        
    ],

providers: [EditService],
standalone: true,
    selector: 'app-root',
    template: `<div style="padding:0px 0px 20px 0px">
                    <button ejs-button id='add' (click)='addRow()'>Add New Row</button>
                </div>
                <ejs-grid #grid id="grid" [dataSource]='data' [editSettings]='editSettings'>
                    <e-columns>
                        <e-column field='OrderID' headerText='Order ID' textAlign='Right'
                        width=100 isPrimaryKey="true"></e-column>
                        <e-column field='CustomerID' headerText='Customer ID' width=120>
                        </e-column>
                        <e-column field='ShipCity' headerText='ShipCity' width=100>
                        </e-column>
                        <e-column field='Freight' headerText='Freight' textAlign='Right' 
                        format='C' width=100></e-column>
                        <e-column field='ShipName' headerText='Ship Name' width=150>
                        </e-column>
                    </e-columns>
                </ejs-grid>`
})
export class AppComponent implements OnInit {

    public data?: object[];
    public editSettings?: EditSettingsModel;
    @ViewChild('grid')
    public grid?: GridComponent;

    ngOnInit(): void {
        this.data = data; // Initialize an empty array
        this.editSettings = { allowEditing: true, allowAdding: true, allowDeleting: true };
    }
    addRow() {
        const newRecord = {
            OrderID: this.generateOrderId(),
            CustomerID: this.generateCustomerId(),
            ShipCity: this.generateShipCity(),
            Freight: this.generateFreight(),
            ShipName: this.generateShipName()
        };

        (this.grid as GridComponent).addRecord(newRecord, 0);
    }
    // Generate a random OrderID
    generateOrderId(): number {
        return Math.floor(10000 + Math.random() * 90000);
    }
    // Generate a random CustomerID
    generateCustomerId(): 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 ShipCity
    generateShipCity(): string {
        const cities = ['London', 'Paris', 'New York', 'Tokyo', 'Berlin'];
        return cities[Math.floor(Math.random() * cities.length)];
    }
    // Generate a random Freight value
    generateFreight(): number {
        return Math.random() * 100;
    }
    // Generate a random ShipName
    generateShipName(): string {
        const names = ['Que Delícia', 'Bueno Foods', 'Island Trading', 'Laughing Bacchus Winecellars'];
        return names[Math.floor(Math.random() * names.length)];
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

  • When working with remote data, it is impossible to add a new row between the existing rows.
  • 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 grid.

Show or hide a row using an external actions

In a Syncfusion grid, you can show or hide a particular row based on some external action, such as a checkbox click.This can be useful in scenarios where you want to hide certain rows from the grid temporarily, without removing them from the underlying data source. This can be achieved by using the getRowByIndex and getRowsObject methods of the grid along with the change event of the checkbox

The getRowsObject method returns an array of row objects that represents all the rows in the grid. You can use this method to iterate through all the 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 is used to check whether the checkbox is checked or not. If it is checked, the method iterates through all the rows in the grid using the getRowsObject method. For each row, it checks whether the value in the CustomerID column is equal to “VINET”. If it is, 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 { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule } from '@syncfusion/ej2-angular-grids'
import { CheckBoxModule} from '@syncfusion/ej2-angular-buttons'
import { Component, ViewChild } from '@angular/core';
import { orderDetails, columnDataType } from './datasource';
import { GridComponent } from '@syncfusion/ej2-angular-grids';
import { ChangeEventArgs } from '@syncfusion/ej2-buttons';

@Component({
imports: [
        
        GridModule,
        CheckBoxModule
    ],

standalone: true,
  selector: 'app-root',
  template: `<div style="padding:2px 0px 0px 0px">
                <ejs-checkbox #checkbox label='Show / Hide Row' 
                (change)="onCheckBoxChange($event)"></ejs-checkbox>
            </div>
            <p id="message">{{ message }}</p>
            <ejs-grid #grid [dataSource]='data' height='350'>
                <e-columns>
                    <e-column field='OrderID' headerText='Order ID' width='120' 
                    textAlign='Right'></e-column>
                    <e-column field='CustomerID' headerText='Customer Name' width='150'>
                    </e-column>
                    <e-column field='OrderDate' headerText='Order Date' width='130' 
                    format="yMd" textAlign='Right'>
                    </e-column>
                    <e-column field='Freight' headerText='Freight' width='120' format='C2' 
                    textAlign='Right'>
                    </e-column>
                    <e-column field='ShippedDate' headerText='Shipped Date' width='130' 
                    format="yMd" textAlign='Right'>
                    </e-column>
                    <e-column field='ShipCountry' headerText='Ship Country' width='150'>
                    </e-column>
                </e-columns>
            </ejs-grid>`,
})
export class AppComponent {

  public data: Object[] = [];
  public rowIndex?: number;
  public hiddenRows: number[] = [];
  @ViewChild('grid')
    public grid?: GridComponent;
  public message?: string = '';

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

  public onCheckBoxChange(args: ChangeEventArgs) {
    if (args.checked) {
      for (let i = 0; i < (this.grid as GridComponent).getRowsObject().length; i++) {
        if (((this.grid as GridComponent).getRowsObject()[i].data as columnDataType).CustomerID === 'VINET') {
          // check the row value
          this.rowIndex = (this.grid as GridComponent).getRowsObject()[i].index; //get particular row index
          ((this.grid as GridComponent).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 customer name column value of VINET have been hidden`;
      }
    } else {
      // Show hidden rows
      this.hiddenRows.forEach((rowIndex: number) => {
        ((this.grid as GridComponent).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 Grid provides comprehensive methods for row data and element retrieval, enabling custom operations and data manipulation:

  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 grid.

     const rowElement = this.grid.getRowByIndex(rowIndex);
  2. getRowIndexByPrimaryKey:The method allows you to retrieve the row index based on a specific primary key value or row data.

     const rowIndex = this.grid.getRowIndexByPrimaryKey(primaryKey);
  3. getRowInfo:This method allows you to retrieve row information based on a cell target element.

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

      const rowElements = this.grid.getRows();
  5. 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.grid.getSelectedRowIndexes();
  6. getSelectedRows:This method returns an array of HTML elements representing the selected rows in the grid.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.grid.getSelectedRows();

These methods can be combined for comprehensive row data access and manipulation scenarios, providing complete control over Grid row interactions and customization.

See Also