HelpBot Assistant

How can I help you?

Row Selection in Angular Grid Component

19 Mar 202624 minutes to read

Row selection in the Grid component provides interactive selection of specific rows or ranges of rows within the grid. Row selection can be performed effortlessly through mouse clicks or arrow keys (up, down, left, and right). This feature is useful when highlighting, manipulating, or performing actions on specific rows within the grid.

To enable row selection, set the selectionSettings.mode property to either Row or Both. This property determines the selection mode of the grid.

Single row selection

Single row selection provides selecting a single row at a time within the grid. This feature is useful when focusing on specific rows or performing actions on the data within a particular row.

To configure single row selection, set the selectionSettings.mode property to Row and the selectionSettings.type property to Single. This configuration allows selecting only one row at a time within the grid.

The following example demonstrates single row selection in grid component:

import { data } from './datasource';
import { Component } from '@angular/core';
import { EditService, FilterService, GridModule, PageService, SelectionSettingsModel, ToolbarService } from '@syncfusion/ej2-angular-grids';

@Component({
    imports: [ GridModule ],
    providers: [EditService, ToolbarService, PageService, FilterService],
    standalone: true,
    selector: 'app-root',
    template:`   
            <ejs-grid #grid [dataSource]="data" allowPaging="true" 
            [selectionSettings]="selectionOptions">
                <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 selectionOptions?: SelectionSettingsModel;
    public ngOnInit(): void {
        this.data = data;
        this.selectionOptions = { mode: 'Row',  type: 'Single' };
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Multiple row selection

To allow selecting multiple rows simultaneously, set Multiple row selection provides option to select multiple rows within the grid. This feature is useful when performing actions on several rows simultaneously or focusing on specific data areas.

To configure multiple row selection, set the selectionSettings.mode property to Row and the selectionSettings.type property to Multiple. This configuration allows selecting multiple rows at a time within the grid.

The following example demonstrates multiple rows selection in grid component:

import { data } from './datasource';
import { Component } from '@angular/core';
import { EditService, FilterService, GridModule, PageService, SelectionSettingsModel, ToolbarService } from '@syncfusion/ej2-angular-grids';

@Component({
    imports: [GridModule ],
    providers: [EditService, ToolbarService, PageService, FilterService],
    standalone: true,
    selector: 'app-root',
    template: `   
            <ejs-grid #grid [dataSource]="data" allowPaging="true" 
            [selectionSettings]="selectionOptions">
                <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 selectionOptions?: SelectionSettingsModel;

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

Select row at initial rendering

A specific row can be selected during the initial rendering of the Grid component. This feature is particularly useful when highlighting or pre-selecting a specific row in the grid. To achieve this, utilize the selectedRowIndex property provided by the Grid component.

The following example demonstrates selecting a row at initial rendering:

import { data } from './datasource';
import { Component, OnInit } from '@angular/core';
import { EditService, FilterService, GridModule, PageService, SelectionSettingsModel, ToolbarService } from '@syncfusion/ej2-angular-grids';

@Component({
    imports: [GridModule ],
    providers: [EditService, ToolbarService, PageService, FilterService],
    standalone: true,
    selector: 'app-root',
    template: `<ejs-grid [dataSource]='data' [selectedRowIndex]=1 
               [selectionSettings]='selectionOptions' height='315px'>
                    <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[];
    public selectionOptions?: SelectionSettingsModel;

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

Select rows in any page based on index value

The Grid allows selecting rows in any page based on their index value. This feature is useful when performing specific actions on rows, such as highlighting, applying styles, or executing operations, regardless of their location across multiple pages within the grid.

To achieve this, utilize the selectRow method and the goToPage method of the grid control. By handling the change event of the DropDownList component, implement the logic to navigate to the desired page and select the row based on the index value.

Additionally, by handling the actionComplete event of the grid, maintain the selection of the desired row after completing the paging action.

The following example demonstrates selecting rows on any page based on their index value using the actionComplete and change events:

import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { DropDownListModule } from '@syncfusion/ej2-angular-dropdowns';
import { EditEventArgs, EditService, FilterService, GridComponent, GridModule, PageService, SelectionService, ToolbarService } from '@syncfusion/ej2-angular-grids';
import { ChangeEventArgs } from '@syncfusion/ej2-dropdowns';

@Component({
  imports: [GridModule, DropDownListModule ],
  providers: [EditService, ToolbarService, PageService, FilterService, SelectionService],
  standalone: true,
  selector: 'app-root',
  template: `<div style="display: flex">
               <label style="padding: 5px 5px 0 0" > Select Row :</label>
               <ejs-dropdownlist id='value' #sample index='0' 
               width='220' [dataSource]='ddlData' (change)='valueChange($event)' >
               </ejs-dropdownlist>
              </div>
              <div style="padding: 5px 5px 0 0">
                  <ejs-grid #grid [dataSource]='data' 
                  (actionComplete)='actioncomplete($event)' allowPaging='true' 
                  height=250 [pageSettings]='initialPage'>
                      <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='ShipCountry' headerText='Ship Country' width='170'>
                          </e-column>
                      </e-columns>
                  </ejs-grid>
              </div>`
})

export class AppComponent implements OnInit {

  public data?: Object[];
  public initialPage?: Object;
  public mod: any;
  public value: any;
  @ViewChild('grid')
  public grid?: GridComponent;
  public ddlData?: Object[] = [
    { text: 'Select row index' },
    { text: '1', value: '1' },
    { text: '2', value: '2' },
    { text: '30', value: '30' },
    { text: '80', value: '80' },
    { text: '110', value: '110' },
    { text: '120', value: '120' },
    { text: '210', value: '210' },
    { text: '310', value: '310' },
    { text: '410', value: '410' },
    { text: '230', value: '230' }
  ];

  ngOnInit(): void {
    this.data = data;
    this.initialPage = { pageSize: 10 }
  }
  actioncomplete(args: EditEventArgs): void {
    if (args.requestType === "paging") {
      (this as any).grid.selectRow(this.mod);
    }
  }
  valueChange(args: ChangeEventArgs): void {
    this.value = +args.value;
    this.mod = (this.value - 1) % 10;
    const page = Math.ceil(this.value / 10);

    if (page === 1) {
      if ((this.grid as GridComponent).pagerModule.pagerObj.currentPage != 1) {
        (this.grid as GridComponent).pagerModule.goToPage(1);
      }
      (this.grid as GridComponent).selectRow(this.mod);
    }
    else {
      (this.grid as GridComponent).pagerModule.goToPage(page);
      if ((this.grid as GridComponent).pagerModule.pagerObj.currentPage == page) {
        (this.grid as GridComponent).selectRow(this.mod);
      }
    }
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Multiple row selection by single click

The Grid component allows multiple row selection by simply clicking on rows one by one without pressing CTRL or SHIFT keys. When clicking on a row, it becomes selected, and clicking on another row adds it to the selection without deselecting the previously selected rows. To deselect a previously selected row, click on the row again.

To configure simple multiple row selection, set the selectionSettings.enableSimpleMultiRowSelection property to true.

The following example demonstrates configuring multiple row selection with a single click on a grid row using the enableSimpleMultiRowSelection property:

import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { SwitchModule } from '@syncfusion/ej2-angular-buttons';
import { EditService, FilterService, GridComponent, GridModule, PageService, SelectionSettingsModel, ToolbarService } from '@syncfusion/ej2-angular-grids';

@Component({
  imports: [ GridModule,SwitchModule ],
  providers: [EditService, ToolbarService, PageService, FilterService],
  standalone: true,
  selector: 'app-root',
  template: `
        <div style="padding: 0px 0px 10px 0px">
          <label>Enable/Disable simple multiple row selection</label>
          <ejs-switch id="switch" [(checked)]="enableSelection" 
          (change)="toggleRowSelection()"></ejs-switch>
        </div>
        <ejs-grid #grid [dataSource]="data" [selectionSettings]="selectionOptions" 
        height="300px">
        <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[];
  public selectionOptions?: SelectionSettingsModel;
  public enableSelection = false;
  @ViewChild('grid') grid!: GridComponent;

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

Select rows programmatically

Single row selection, multiple row selection, and range of row selection can be performed externally in a grid using built-in methods. This feature allows interacting with specific rows within the grid programmatically.

Single row selection

To achieve single row selection, use the selectRow method. This method allows programmatic selection of a specific row within the grid by specifying the row index.

The example below demonstrates single row selection in the grid. The row index is obtained from a textbox component and passed to the selectRow method. Upon clicking the “Select Row” button, the corresponding row is selected:

import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ButtonModule } from '@syncfusion/ej2-angular-buttons';
import { EditService, FilterService, GridModule, PageService, ToolbarService } from '@syncfusion/ej2-angular-grids';
import { TextBoxComponent, TextBoxModule,GridComponent,SelectionSettingsModel, PageSettingsModel, } from '@syncfusion/ej2-angular-inputs';

@Component({
  imports: [GridModule, TextBoxModule, ButtonModule ],
  providers: [EditService, ToolbarService, PageService, FilterService],
  standalone: true,
  selector: 'app-root',
  template: `
        <div>
          <label style="padding: 30px 17px 0 0">Enter the row index: </label>
          <ejs-textbox #textbox required  width="220">
          </ejs-textbox>
        </div>
        <div style="padding: 10px 0 0px 150px">
        <button ejs-button id="button" (click)="click()">Select Row</button>
        </div>
        <div style="padding: 20px 0px 0px 0px">
          <ejs-grid #grid [dataSource]="data"  [selectionSettings]="selectionOptions" >
            <e-columns>
              <e-column field="OrderID" headerText="Order ID" textAlign="Right" 
              width="120"></e-column>
              <e-column field="CustomerID" headerText="Customer ID" width="120"></e-column>
              <e-column field="ShipCountry" headerText="Ship Country" width="130">
              </e-column>
              <e-column field="Freight" headerText="Freight" format="C2" width="100">
              </e-column>
            </e-columns>
          </ejs-grid>
        </div>`
})
export class AppComponent implements OnInit {

  public data?: Object[];
  public selectionOptions?: SelectionSettingsModel;
  public pageOptions?: PageSettingsModel;
  public rowIndex?: number;

  @ViewChild('textbox') public textbox?: TextBoxComponent;
  @ViewChild('grid') public grid?: GridComponent;

  ngOnInit(): void {
    this.data = data;
    this.selectionOptions = { mode: 'Row', type: 'Single' };
    this.pageOptions = { pageSize: 5 };
  }
  click(): void {
    this.rowIndex = parseInt((this.textbox as TextBoxComponent).element.value, 10);
    if (!isNaN(this.rowIndex)) {
      (this.grid as GridComponent).selectRow(this.rowIndex);
    }
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Multiple rows selection

To achieve multiple row selection, use the selectRows method. This method allows selecting a collection of rows by specifying their indexes, providing the ability to interact with multiple rows together.

The following example demonstrates selecting multiple rows in the grid by calling the selectRows method within the button click event and passing an array of row indexes as arguments.

import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ButtonModule } from '@syncfusion/ej2-angular-buttons';
import { EditService, FilterService, GridModule, PageService, ToolbarService, GridComponent,SelectionSettingsModel,PageSettingsModel, } from '@syncfusion/ej2-angular-grids';
import { TextBoxModule } from '@syncfusion/ej2-angular-inputs';

@Component({
  imports: [GridModule, TextBoxModule,  ButtonModule ],
  providers: [EditService, ToolbarService, PageService, FilterService],
  standalone: true,
  selector: 'app-root',
  template: `
        <div style="padding: 10px 0px 20px 0px">
          <button ejs-button class="btn" (click)="selectRows([1, 3])">
          select [1, 3] </button>
          <button ejs-button class="btn" (click)="selectRows([0, 2])">
          select [0, 2]</button>
          <button ejs-button class="btn" (click)="selectRows([2, 4])">
          select [2, 4] </button>
          <button ejs-button class="btn" (click)="selectRows([0,5])">
          select [0,5]</button>
          <button ejs-button class="btn" (click)="selectRows([1,6])">
          select [1,6]</button>
        </div>
        <div style="padding: 10px 0px 20px 0px">
          <button ejs-button class="btn" (click)="selectRows([0,7,8])">
          select [0,7,8]</button>
          <button ejs-button class="btn" (click)="selectRows([1,9,10])">
          select [1,9,10]</button>
          <button ejs-button class="btn" (click)="selectRows([4,7,12])">
          select [4,7,12]</button>
          <button ejs-button class="btn" (click)="selectRows([2,5,6])">
          select [2,5,6]</button>
        </div>
        <div style="padding: 20px 0px 0px 0px">
          <ejs-grid #grid [dataSource]="data" [selectionSettings]="selectionOptions">
            <e-columns>
              <e-column field="OrderID" headerText="Order ID" textAlign="Right" 
              width="120"></e-column>
              <e-column field="CustomerID" headerText="Customer ID" width="120">
              </e-column>
              <e-column field="ShipCountry" headerText="Ship Country" width="130">
              </e-column>
              <e-column field="Freight" headerText="Freight" format="C2" width="100">
              </e-column>
            </e-columns>
          </ejs-grid>
        </div>`
})
export class AppComponent implements OnInit {

  public data?: Object[];
  public selectionOptions?: SelectionSettingsModel;
  public pageOptions?: PageSettingsModel;
  @ViewChild('grid') public grid?: GridComponent;

  ngOnInit(): void {
    this.data = data;
    this.selectionOptions = { type: 'Multiple', mode: 'Row' };
    this.pageOptions = { pageSize: 5 };
  }
  selectRows(rowIndexes: number[]): void {
    this.grid?.clearRowSelection();
    this.grid?.selectRows(rowIndexes);
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Range of rows selection

Range selection in the grid provides selecting a continuous range of rows within the grid. This feature is particularly useful when performing actions on multiple rows simultaneously or focusing on a specific range of data.

To achieve range selection, use the selectRowsByRange method. This method selects a range of rows from start and end row indexes.

The following example demonstrates selecting a range of rows within the grid by obtaining the selected rows start index and end index through textbox components. Then pass these start index and end index as arguments to the selectRowsByRange method. When the “Select Rows” button is clicked, a range of rows is selected within the grid:

import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ButtonModule } from '@syncfusion/ej2-angular-buttons';
import { EditService, FilterService, GridModule, PageService, ToolbarService, GridComponent,SelectionSettingsModel,PageSettingsModel, } from '@syncfusion/ej2-angular-grids';
import { TextBoxComponent, TextBoxModule } from '@syncfusion/ej2-angular-inputs';

@Component({
  imports: [ GridModule, TextBoxModule, ButtonModule ],
  providers: [EditService, ToolbarService, PageService, FilterService],
  standalone: true,
  selector: 'app-root',
  template: `
        <div>
          <label style="padding: 30px 17px 0 0">Enter the start row index: </label>
          <ejs-textbox #textbox required  width="120"></ejs-textbox>
        </div>
        <div>
          <label style="padding: 30px 17px 0 0">Enter the end row index: </label>
          <ejs-textbox #textbox1 required width="120"></ejs-textbox>
        </div>
        <div style="padding: 10px 0 0px 180px">
        <button ejs-button id="button" (click)="click()">Select rows</button>
        </div>
        <div style="padding: 20px 0px 0px 0px">
          <ejs-grid #grid [dataSource]="data" [selectionSettings]="selectionOptions">
            <e-columns>
              <e-column field="OrderID" headerText="Order ID" textAlign="Right" 
              width="120"></e-column>
              <e-column field="CustomerID" headerText="Customer ID" width="120"></e-column>
              <e-column field="ShipCountry" headerText="Ship Country" width="130"></e-column>
              <e-column field="Freight" headerText="Freight" format="C2" width="100">
              </e-column>
            </e-columns>
          </ejs-grid>
        </div>`
})
export class AppComponent implements OnInit {
    
  public data?: Object[];
  public selectionOptions?: SelectionSettingsModel;
  public pageOptions?: PageSettingsModel;
  public startIndex?:number;
  public endIndex?:number;
  @ViewChild('textbox') public textbox?: TextBoxComponent;
  @ViewChild('textbox1') public textbox1?: TextBoxComponent;
  @ViewChild('grid') public grid?: GridComponent;

  ngOnInit(): void {
    this.data = data;
    this.selectionOptions = { mode: 'Row', type: 'Multiple' };
    this.pageOptions = { pageSize: 5 };
  }
  click(): void {
    this.startIndex = parseInt((this.textbox as TextBoxComponent).element.value, 10); 
    this.endIndex = parseInt((this.textbox1 as TextBoxComponent).element.value, 10); 
    (this.grid as GridComponent).selectionModule.clearRowSelection();
    if (!isNaN(this.startIndex) && !isNaN(this.endIndex)) {
      (this.grid as GridComponent).selectionModule.selectRowsByRange(this.startIndex, this.endIndex);
    }
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Select grid rows based on certain condition

Specific rows in the Angular Grid component can be programmatically selected based on a certain condition. This feature is particularly useful when dynamically highlighting or manipulating specific rows in the grid based on custom conditions. This functionality can be achieved using the selectRows method in the dataBound event of the grid.

The following example demonstrates selecting grid rows only when the “Employee ID” column value is greater than “3”.

import { columnDataType, data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { FilterService, GridComponent, GridModule, GroupService, PageService, RowDataBoundEventArgs, SelectionSettingsModel, SortService } from '@syncfusion/ej2-angular-grids';

@Component({
    imports: [ GridModule ],
    providers: [PageService, SortService, FilterService, GroupService],
    standalone: true,
    selector: 'app-root',
    template: `<div id="GridParent">
                    <ejs-grid #Grid [dataSource]="data" allowPaging='true' [selectionSettings]='selectionOptions'
                    (rowDataBound)='rowDataBound($event)' (dataBound)='dataBound()' height='273px'>
                        <e-columns>
                            <e-column field='OrderID' headerText='Order ID' textAlign='Right' isPrimaryKey='true' width=100></e-column>
                            <e-column field='CustomerID' headerText='Customer ID' width=120></e-column>
                            <e-column field='EmployeeID' headerText='Employee ID' textAlign= 'Right' width=120></e-column>
                            <e-column field='ShipCity' headerText='Ship City'  width=120></e-column>
                            <e-column field='ShipName' headerText='Ship Name' width=150></e-column>
                        </e-columns>
                    </ejs-grid>
               </div>`
})
export class AppComponent implements OnInit {
    public data?: object[];
    @ViewChild('Grid') 
    public grid?: GridComponent;
    public selectionOptions?: SelectionSettingsModel;
    public selIndex?: number[] = [];

    ngOnInit(): void {
        this.data = data;
        this.selectionOptions = { type: 'Multiple' };
    }

    public rowDataBound(args: RowDataBoundEventArgs ): void {
            if (((args.data as columnDataType)['EmployeeID'] as number) > 3) {
            this.selIndex?.push(parseInt(((args.row as Element).getAttribute('aria-rowindex') as string), 10));
        }
    }

    public dataBound(): void {
        if (this.selIndex?.length) {
            this.grid?.selectRows(this.selIndex);
            this.selIndex = [];
        }
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Get selected row indexes

The indexes of the currently selected rows in the Grid component can be retrieved. This feature is particularly useful when performing actions or operations specifically on the selected rows.

To achieve this, invoke the getSelectedRowIndexes method, which returns an array of selected row indexes.

The following example demonstrates getting selected row indexes using the getSelectedRowIndexes method:

import { GridComponent, SelectionSettingsModel,GridModule, PageService, EditService, ToolbarService, FilterService } from '@syncfusion/ej2-angular-grids'
import { ButtonModule } from '@syncfusion/ej2-angular-buttons'
import { Component, OnInit, ViewChild } from '@angular/core';
import { data } from './datasource';
import { CommonModule } from '@angular/common';

@Component({
imports: [
        CommonModule,
        GridModule,
        ButtonModule
    ],
providers: [EditService, ToolbarService, PageService, FilterService],
standalone: true,
  selector: 'app-root',
  template: ` 
        <div style="padding: 5px 0px 5px 0px">
          <button ejs-button class="btn" (click)="click()">Get selected row indexes</button>
        </div>
        <p id="message" *ngIf="showMessage">Selected row indexes: {{ selectedRowIndexes }}</p>
        <ejs-grid #grid [dataSource]="data" height="300px" 
        [selectionSettings]="selectionOptions">
          <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[];
  public selectedRowIndexes: number[] = [];
  public selectionOptions?: SelectionSettingsModel;
  public showMessage = false;

  @ViewChild('grid')
  public grid?: GridComponent;

  ngOnInit(): void {
    this.data = data;
    this.selectionOptions = { type: 'Multiple' };
  }
  click() {
    this.selectedRowIndexes = (this.grid as GridComponent).getSelectedRowIndexes();
    this.showMessage = this.selectedRowIndexes.length > 0;
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Get selected records on various pages

The Grid component allows retrieving the selected records even when navigating to different pages. This feature is useful when working with large data sets and allows performing actions on the selected records across multiple pages.

To persist the selection across pages, enable the persistSelection property. By default, this property is set to false. To enable it, set the value to true in the selectionSettings property of the Grid component.

To retrieve the selected records from different pages, use the getSelectedRecords method. This method returns an array of the selected records.

The following example demonstrates retrieving selected records from various pages using the getSelectedRecords method and displaying the “Order ID” values of those records in a dialog when the “Show Selected Records” button is clicked:

import { ButtonModule } from '@syncfusion/ej2-angular-buttons';
import { DialogModule } from '@syncfusion/ej2-angular-popups';
import { Component, OnInit, ViewChild } from '@angular/core';
import { data } from './datasource';
import { GridComponent, SelectionSettingsModel, PageSettingsModel,GridModule, PageService, EditService, ToolbarService, FilterService } from '@syncfusion/ej2-angular-grids';
import { CommonModule } from '@angular/common';

@Component({
imports: [
        GridModule,
        CommonModule,
        ButtonModule,
        DialogModule
    ],
providers: [EditService, ToolbarService, PageService, FilterService],
standalone: true,
  selector: 'app-root',
  template: `
    <div style="padding: 20px 0px">
      <button ejs-button class="sample" (click)="showSelectedRecords()">Show Selected Records</button>
    </div>
    <ejs-grid #grid [dataSource]="data" allowPaging="true" [selectionSettings]="selectionOptions" 
    [pageSettings]="pageOptions">
      <e-columns>
        <e-column type="checkbox" width="50"></e-column>
        <e-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" 
        width="120"></e-column>
        <e-column field="CustomerID" headerText="Customer ID" width="120"></e-column>
        <e-column field="ShipCountry" headerText="Ship Country" width="130"></e-column>
        <e-column field="Freight" headerText="Freight" format="C2" width="100"></e-column>
      </e-columns>
    </ejs-grid>
    <ejs-dialog #dialogComponent [header]="'Selected Records'" [content]="dialogContent"
      [visible]="dialogVisible" (close)="dialogClose()" showCloseIcon="true" width="400px" 
      [position]='{ X: 300, Y: 100 }'>
      <ng-template #dialogContent>
        <ng-container>
          <div *ngFor="let record of selectedRecords">
            <p><b>Order ID:</b> {{ record.OrderID }}</p>
          </div>
        </ng-container>
      </ng-template>
    </ejs-dialog>
  `
})
export class AppComponent implements OnInit {

  public data?: object[];
  public selectionOptions?: SelectionSettingsModel;
  public pageOptions?: PageSettingsModel;
  public dialogVisible: boolean = false;
  public selectedRecords: Order[] = [];
  @ViewChild('grid')
  public grid?: GridComponent;

  ngOnInit(): void {
    this.data = data;
    this.selectionOptions = { type: 'Multiple', persistSelection: true };
    this.pageOptions = { pageSize: 5 };
  }

  showSelectedRecords(): void {
    this.selectedRecords = (this.grid as GridComponent).getSelectedRecords();
    if (this.selectedRecords.length > 0) {
      this.dialogVisible = true;
    }
  }
  dialogClose(): void {
    this.dialogVisible = false;
  }
}
interface Order {
  OrderID?: number;
  CustomerID?: string;
  ShipCountry?: string;
  Freight?: number;
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

To persist the grid selection, it is necessary to define any one of the columns as a primary key using the columns.isPrimaryKey property.

Get selected records

Getting selected records enables retrieving the data of the selected rows from the Grid component. This is particularly useful when performing actions on the selected data or displaying specific information based on the selected rows.

To retrieve the selected records, use the getSelectedRecords method. This method enables obtaining an array of objects representing the selected records.

The following example displays the selected row count using the getSelectedRecords method:

import { GridModule, PageService,EditService, ToolbarService, FilterService,GridComponent, SelectionSettingsModel } from '@syncfusion/ej2-angular-grids;
import { ButtonModule } from '@syncfusion/ej2-angular-buttons';
import { Component, OnInit, ViewChild } from '@angular/core';
import { data } from './datasource';
import { CommonModule } from '@angular/common';

@Component({
imports: [GridModule,CommonModule,ButtonModule],
providers: [EditService, ToolbarService, PageService, FilterService],
standalone: true,
  selector: 'app-root',
  template: `
    <div style="padding: 20px 0px">
      <button ejs-button class="sample" (click)="click()">Selected Records count</button>
    </div>
    <p id="message" *ngIf="showMessage">Selected record count: {{ selectedRecordscount }}</p>
    <div class="control-section">
      <ejs-grid #grid [dataSource]="data" allowPaging="true" [allowSelection]="true" 
      [selectionSettings]="selectionOptions">
        <e-columns>
          <e-column field="OrderID" isPrimaryKey="true" headerText="Order ID" width="120" 
          textAlign="Right"></e-column>
          <e-column field="CustomerID" headerText="Customer ID" 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="ShipCountry" headerText="Ship Country" width="130" format="yMd" 
          textAlign="Right"></e-column>
        </e-columns>
      </ejs-grid>
    </div>
  `,
})
export class AppComponent implements OnInit {

  @ViewChild('grid') public grid?: GridComponent;
  public data?: Object[];
  public selectionOptions?: SelectionSettingsModel;
  public showMessage = false;
  public selectedRecordscount: number = 0;

  public ngOnInit(): void {
    this.data = data;
    this.selectionOptions = { type: 'Multiple' };
  }
  click(): void {
    this.selectedRecordscount = (this.grid as GridComponent).getSelectedRecords().length;
    this.showMessage = this.selectedRecordscount > 0;
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Clear row selection programmatically

Clearing row selection programmatically in the Grid component is a useful feature when removing any existing row selections. To achieve this, use the clearRowSelection method.

The clearRowSelection method is applicable when the selection type is set to Multiple or Single.

The following example demonstrates clearing row selection by calling the clearRowSelection method in the button click event.

import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ButtonModule } from '@syncfusion/ej2-angular-buttons';
import { EditService, FilterService, GridComponent, GridModule, PageService, PageSettingsModel, SelectionSettingsModel, ToolbarService } from '@syncfusion/ej2-angular-grids';
import { TextBoxModule } from '@syncfusion/ej2-angular-inputs';

@Component({
    imports: [ GridModule,  TextBoxModule, ButtonModule ],
    providers: [EditService, ToolbarService, PageService, FilterService],
    standalone: true,
    selector: 'app-root',
    template: `<div style="padding: 20px 0px 0px 0px">
                <button ejs-button id="button" (click)='click()'>clear Row Selection</button>
                </div>
                <div style="padding: 20px 0px 0px 0px">
                    <ejs-grid #grid [dataSource]='data' [selectedRowIndex]=2 allowPaging=true 
                    [selectionSettings]='selectionOptions' [pageSettings]='pageOptions'>
                        <e-columns>
                            <e-column field='OrderID' headerText='Order ID' textAlign='Right'
                            width=120></e-column>
                            <e-column field='CustomerID' headerText='Customer ID' width=120>
                            </e-column>
                            <e-column field='ShipCountry' headerText='Ship Country' width=130>
                            </e-column>
                            <e-column field='Freight' headerText='Freight' format= 'C2' 
                            width=100></e-column>
                        </e-columns>
                    </ejs-grid>
                </div>`
})
export class AppComponent implements OnInit {

    public data?: Object[];
    public selectionOptions?: SelectionSettingsModel;
    public pageOptions?: PageSettingsModel;

    @ViewChild('grid')
    public grid?: GridComponent;

    ngOnInit(): void {
        this.data = data;
        this.selectionOptions = { mode: 'Row', type: 'Multiple' };
        this.pageOptions = { pageSize: 5 };
    }
    click(): void {
        (this.grid as GridComponent).selectionModule.clearRowSelection()
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Row selection events

The Grid provides several events related to row selection that allow responding to and customizing the behavior of row selection. These events provide control over various aspects of row selection. The following are the available row selection events:

rowSelecting: This event is triggered before any row selection occurs. It provides an opportunity to implement custom logic or validation before a row is selected, allowing control over the selection process.

rowSelected: This event is triggered after a row is successfully selected. Use this event to perform actions or updates when a row is selected.

rowDeselecting: This event is triggered just before a selected row is deselected. It allows performing custom logic or validation to decide whether the row should be deselected or not.

rowDeselected: This event is triggered when a particular selected row is deselected. Use this event to perform actions or validations when a row is no longer selected.

In the following example, row selection is canceled when the value of “Customer ID” is equal to “VINET” within the rowSelecting event. The background color changes to green when the value of “Freight” is greater than “10” and less than or equal to “140”, triggering the rowDeselected event. The background color changes to red when the value of “Freight” is less than or equal to “10” during the rowDeselected event. Furthermore, the background color changes to yellow when the value of “Freight” is greater than “140” during the rowDeselected event. A notification message is displayed to indicate which event was triggered whenever a row is selected.

import { Component, OnInit, ViewChild } from '@angular/core';
import { data ,Order} from './datasource';
import { GridModule, GridModule,GridComponent, SelectionSettingsModel,PageSettingsModel,RowSelectingEventArgs, RowSelectEventArgs, RowDeselectEventArgs, RowDeselectingEventArgs} from '@syncfusion/ej2-angular-grids';
import { DialogComponent } from '@syncfusion/ej2-angular-popups';

@Component({
  imports: [ GridModule],
  standalone: true,
  selector: 'app-root',
  template: `
        <p id="message">{{ message }}</p>
        <div style="padding: 20px 0px 0px 0px">
          <ejs-grid
            #grid
            [enableHover]='false'
            [dataSource]="data"
            [selectionSettings]="selectionOptions"
            (rowSelected)="rowSelected($event)"
            (rowSelecting)="rowselecting($event)"
            (rowDeselected)="rowDeselected($event)"
            (rowDeselecting)="rowDeselecting($event)">
            <e-columns>
              <e-column field="OrderID" headerText="Order ID" textAlign="Right" width="120">
              </e-column>
              <e-column field="CustomerID" headerText="Customer ID" width="120">
              </e-column>
              <e-column field="ShipCountry" headerText="Ship Country" width="130">
              </e-column>
              <e-column field="Freight" headerText="Freight" format="C2" width="100">
              </e-column>
            </e-columns>
          </ejs-grid>
        </div>`,
})
export class AppComponent implements OnInit {
  public data?: Object[];
  public selectionOptions?: SelectionSettingsModel;
  public pageOptions?: PageSettingsModel;
  public message?: string;

  @ViewChild('grid') public grid?: GridComponent;
  @ViewChild('dialogComponent') public dialog?: DialogComponent;
  public selectedCellCount: number = 0;
  public dialogVisible: boolean = false;

  ngOnInit(): void {
    this.data = data;
    this.selectionOptions = { mode: 'Row', type: 'Multiple' };
    this.pageOptions = { pageSize: 5 };
  }
  rowselecting(args: RowSelectingEventArgs): void {
    this.message = `Trigger rowSelecting`;
    if ((args.data as Order).CustomerID == 'VINET')
      args.cancel = true;
  }
  rowSelected(args: RowSelectEventArgs): void {
    this.message = ` Trigger rowSelected`;
    if ((args.data as Order).Freight > 10 || (args.data as Order).Freight <= 140)
      (args.row as HTMLElement).style.backgroundColor = 'rgb(96, 158, 101)'; 
  }
  rowDeselected(args: RowDeselectEventArgs ): void {
    this.message = `Trigger rowDeselected`;
    if ((args.data as Order).Freight <= 10)
    (args.row as HTMLElement).style.backgroundColor = 'red';
  }
  rowDeselecting(args: RowDeselectingEventArgs): void {
    this.message = `Trigger rowDeselecting`;
    if ((args.data as Order).Freight > 140)
    (args.row as HTMLElement).style.backgroundColor = 'yellow';
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Pass selected records to server using AJAX

The Syncfusion Angular Grid allows selecting multiple or single records and sending them to the server using AJAX requests. This feature is useful for scenarios requiring processing or manipulation of selected data on the server side.

To pass selected records to the server using AJAX requests in the Syncfusion Angular Grid, follow these steps:

Step 1: Open Visual Studio and create an “Angular and ASP.NET Core” project named “SelectedRecord”. To create an Angular and ASP.NET Core application, follow the documentation link for detailed steps.

Step 2 : Create a simple Angular Grid by following the Getting Started documentation link.

Step 3: In the Angular component HTML file (e.g., “app.component.html”), add a button to trigger the AJAX call and include the Syncfusion Angular Grid with necessary configurations. Handle the button click event to retrieve the selected records using the getSelectedRecords method from the grid and send them to the server using AJAX.

<button ejs-button (click)="click($event)">Pass the selected records to controller</button>
<div style="padding: 20px 17px 0 0">
  <ejs-grid #grid [dataSource]='data' allowPaging="true" height="320" [selectionSettings]="selectionOptions">
    <e-columns>
      <e-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-column>
      <e-column field="EmployeeID" headerText="Employee ID" width="120"></e-column>
      <e-column field="CustomerID" headerText="Customer Name" textAlign="Right" width="120"></e-column>
      <e-column field="OrderDate" headerText="Date" width="150" format="yMd"></e-column>
    </e-columns>
  </ejs-grid>
</div>
import { Component, OnInit, ViewChild } from '@angular/core';
import { GridComponent, SelectionSettingsModel } from '@syncfusion/ej2-angular-grids';
import { DataManager, UrlAdaptor } from '@syncfusion/ej2-data';
import { Ajax } from '@syncfusion/ej2-base';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {
  @ViewChild('grid') public grid?: GridComponent;
  public data?: DataManager;
  public selectionOptions?: SelectionSettingsModel;

  ngOnInit(): void {
    this.data = new DataManager({
      url: 'https://localhost:****/api/grid', // Replace with your API endpoint.
      adaptor: new UrlAdaptor()
    });
    this.selectionOptions = { type: 'Multiple' }
  }
  public click(event: MouseEvent): void {
    var selectedRecords = (this.grid as GridComponent).getSelectedRecords();
    var rows = JSON.stringify(selectedRecords);
    var ajax = new Ajax({
      url: 'https://localhost:****/api/grid/SelectRecord',
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      data: rows
    }); //Use remote server host number instead ****.
    ajax.onSuccess = (result: any) :void => {
    }
    ajax.send();
  }
}

Step 4: On the server side, create a controller named GridController.cs under the Controllers folder to handle incoming requests and process selected records. Add the following code:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Base;
using SelectedReacord.Server.Models;
namespace SelectedReacord.Server.Controllers
{
    [ApiController]
    public class GridController : Controller
    {
        [HttpPost]
        [Route("api/[controller]")]
        public object Post([FromBody] DataManagerRequest DataManagerRequest)
        {
            // Retrieve data from the data source (e.g., database).
            IQueryable<OrdersDetails> DataSource = GetOrderData().AsQueryable();
            QueryableOperation queryableOperation = new QueryableOperation(); // Initialize DataOperations instance.
            // Handling searching operation.
            if (DataManagerRequest.Search != null && DataManagerRequest.Search.Count > 0)
            {
                DataSource = queryableOperation.PerformSearching(DataSource, DataManagerRequest.Search);
            }
            // Handling filtering operation.
            if (DataManagerRequest.Where != null && DataManagerRequest.Where.Count > 0)
            {
                foreach (var condition in DataManagerRequest.Where)
                {
                    foreach (var predicate in condition.predicates)
                    {
                        DataSource = queryableOperation.PerformFiltering(DataSource, DataManagerRequest.Where, predicate.Operator);
                    }
                }
            }
            // Handling sorting operation.
            if (DataManagerRequest.Sorted != null && DataManagerRequest.Sorted.Count > 0)
            {
                DataSource = queryableOperation.PerformSorting(DataSource, DataManagerRequest.Sorted);
            }
            // Get the total count of records.
            int totalRecordsCount = DataSource.Count();

            // Handling paging operation.
            if (DataManagerRequest.Skip != 0)
            {
                DataSource = queryableOperation.PerformSkip(DataSource, DataManagerRequest.Skip);
            }
            if (DataManagerRequest.Take != 0)
            {
                DataSource = queryableOperation.PerformTake(DataSource, DataManagerRequest.Take);
            }
            // Return data based on the request.
            return new { result = DataSource, count = totalRecordsCount };
        }

        [HttpGet]
        [Route("api/[controller]")]
        public List<OrdersDetails> GetOrderData()
        {
            var data = OrdersDetails.GetAllRecords().ToList();
            return data;
        }
        [HttpPost]
        [Route("api/[controller]/SelectRecord")]
        public ActionResult SelectRecord([FromBody] List<Gridcolumns> row)
        {
            return Json(row);
        }
        public class SelectedModel
        {
            public List<Gridcolumns> rowData { get; set; }
        }
        public class Gridcolumns
        {
            public int OrderID { get; set; }
            public string CustomerID { get; set; }
            public int EmployeeID { get; set; }
            public DateTime OrderDate { get; set; }
        }
    }
}

Step 5: Create a model class named OrdersDetails.cs under the Models folder in the server-side project to represent the order data. Add the following code:

namespace SelectedReacord.Server.Models
{
    public class OrdersDetails
    {
        public static List<OrdersDetails> order = new List<OrdersDetails>();
        public OrdersDetails()
        {

        }
        public OrdersDetails(
        int OrderID, string CustomerId, int EmployeeId, double Freight, bool Verified,
        DateTime OrderDate, string ShipCity, string ShipName, string ShipCountry,
        DateTime ShippedDate, string ShipAddress)
        {
            this.OrderID = OrderID;
            this.CustomerID = CustomerId;
            this.EmployeeID = EmployeeId;
            this.Freight = Freight;
            this.ShipCity = ShipCity;
            this.Verified = Verified;
            this.OrderDate = OrderDate;
            this.ShipName = ShipName;
            this.ShipCountry = ShipCountry;
            this.ShippedDate = ShippedDate;
            this.ShipAddress = ShipAddress;
        }

        public static List<OrdersDetails> GetAllRecords()
        {
            if (order.Count() == 0)
            {
                int code = 10000;
                for (int i = 1; i < 10; i++)
                {
                    order.Add(new OrdersDetails(code + 1, "ALFKI", i + 0, 2.3 * i, false, new DateTime(1991, 05, 15), "Berlin", "Simons bistro", "Denmark", new DateTime(1996, 7, 16), "Kirchgasse 6"));
                    order.Add(new OrdersDetails(code + 2, "ANATR", i + 2, 3.3 * i, true, new DateTime(1990, 04, 04), "Madrid", "Queen Cozinha", "Brazil", new DateTime(1996, 9, 11), "Avda. Azteca 123"));
                    order.Add(new OrdersDetails(code + 3, "ANTON", i + 1, 4.3 * i, true, new DateTime(1957, 11, 30), "Cholchester", "Frankenversand", "Germany", new DateTime(1996, 10, 7), "Carrera 52 con Ave. Bolívar #65-98 Llano Largo"));
                    order.Add(new OrdersDetails(code + 4, "BLONP", i + 3, 5.3 * i, false, new DateTime(1930, 10, 22), "Marseille", "Ernst Handel", "Austria", new DateTime(1996, 12, 30), "Magazinweg 7"));
                    order.Add(new OrdersDetails(code + 5, "BOLID", i + 4, 6.3 * i, true, new DateTime(1953, 02, 18), "Tsawassen", "Hanari Carnes", "Switzerland", new DateTime(1997, 12, 3), "1029 - 12th Ave. S."));
                    code += 5;
                }
            }
            return order;
        }

        public int? OrderID { get; set; }
        public string? CustomerID { get; set; }
        public int? EmployeeID { get; set; }
        public double? Freight { get; set; }
        public string? ShipCity { get; set; }
        public bool? Verified { get; set; }
        public DateTime OrderDate { get; set; }
        public string? ShipName { get; set; }
        public string? ShipCountry { get; set; }
        public DateTime ShippedDate { get; set; }
        public string? ShipAddress { get; set; }
    }
}

Step 7: In the Program.cs file, add the following code:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(builder =>
    {
      builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
    });
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseCors();
app.UseDefaultFiles();
app.UseStaticFiles();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapFallbackToFile("/index.html");
app.Run();

The following screenshot shows passing of selected records to the server:

Pass selected records to server using ajax

Pass selected records to server using FETCH

The Syncfusion Angular Grid allows selecting multiple or single records and sending them to the server using Fetch requests. This feature is useful for scenarios requiring processing or manipulation of selected data on the server side.

To pass selected records to the server using Fetch requests in the Syncfusion Angular Grid, follow these steps:

Step 1: Open Visual Studio and create an “Angular and ASP.NET Core” project named “SelectedRecord”. To create an Angular and ASP.NET Core application, follow the documentation link for detailed steps.

Step 2 : Create a simple Angular Grid by following the Getting Started documentation link.

Step 3: In the Angular component HTML file (e.g., “app.component.html”), add a button to trigger the Fetch call and include the Syncfusion Angular Grid with necessary configurations. Handle the button click event to retrieve the selected records using the getSelectedRecords method from the grid and send them to the server using Fetch.

<button ejs-button (click)="click($event)">Pass the selected records to controller</button>
<div style="padding: 20px 17px 0 0">
  <ejs-grid #grid [dataSource]='data' allowPaging="true" height="320" [selectionSettings]="selectionOptions">
    <e-columns>
      <e-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-column>
      <e-column field="EmployeeID" headerText="Employee ID" width="120"></e-column>
      <e-column field="CustomerID" headerText="Customer Name" textAlign="Right" width="120"></e-column>
      <e-column field="OrderDate" headerText="Date" width="150" format="yMd"></e-column>
    </e-columns>
  </ejs-grid>
</div>
import { Component, OnInit, ViewChild } from '@angular/core';
import { GridComponent, SelectionSettingsModel } from '@syncfusion/ej2-angular-grids';
import { DataManager, UrlAdaptor } from '@syncfusion/ej2-data';
import { Fetch } from '@syncfusion/ej2-base';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {
  @ViewChild('grid') public grid?: GridComponent;
  public data?: DataManager;
  public selectionOptions?: SelectionSettingsModel;

  ngOnInit(): void {
    this.data = new DataManager({
      url: 'https://localhost:****/api/grid', // Replace with your API endpoint.
      adaptor: new UrlAdaptor()
    });
    this.selectionOptions = { type: 'Multiple' }
  }
  public click(event: MouseEvent): void {
    var selectedRecords = (this.grid as GridComponent).getSelectedRecords();
    var rows = JSON.stringify(selectedRecords);
    var fetch = new Fetch({
      url: 'https://localhost:****/api/grid/SelectRecord',
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      data: rows
    }); //Use remote server host number instead ****
    fetch.onSuccess = (result: any):void => {
    }
   fetch.send();
  }
}

Step 4: On the server side, create a controller named GridController.cs under the “Controllers” folder to handle incoming requests and process selected records. Add the following code:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Base;
using SelectedReacord.Server.Models;
namespace SelectedReacord.Server.Controllers
{
    [ApiController]
    public class GridController : Controller
    {
        [HttpPost]
        [Route("api/[controller]")]
        public object Post([FromBody] DataManagerRequest DataManagerRequest)
        {
            // Retrieve data from the data source (e.g., database).
            IQueryable<OrdersDetails> DataSource = GetOrderData().AsQueryable();
            QueryableOperation queryableOperation = new QueryableOperation(); // Initialize DataOperations instance.
            // Handling searching operation.
            if (DataManagerRequest.Search != null && DataManagerRequest.Search.Count > 0)
            {
                DataSource = queryableOperation.PerformSearching(DataSource, DataManagerRequest.Search);
            }
            // Handling filtering operation.
            if (DataManagerRequest.Where != null && DataManagerRequest.Where.Count > 0)
            {
                foreach (var condition in DataManagerRequest.Where)
                {
                    foreach (var predicate in condition.predicates)
                    {
                        DataSource = queryableOperation.PerformFiltering(DataSource, DataManagerRequest.Where, predicate.Operator);
                    }
                }
            }
            // Handling sorting operation.
            if (DataManagerRequest.Sorted != null && DataManagerRequest.Sorted.Count > 0)
            {
                DataSource = queryableOperation.PerformSorting(DataSource, DataManagerRequest.Sorted);
            }
            // Get the total count of records.
            int totalRecordsCount = DataSource.Count();

            // Handling paging operation.
            if (DataManagerRequest.Skip != 0)
            {
                DataSource = queryableOperation.PerformSkip(DataSource, DataManagerRequest.Skip);
            }
            if (DataManagerRequest.Take != 0)
            {
                DataSource = queryableOperation.PerformTake(DataSource, DataManagerRequest.Take);
            }
            // Return data based on the request.
            return new { result = DataSource, count = totalRecordsCount };
        }

        [HttpGet]
        [Route("api/[controller]")]
        public List<OrdersDetails> GetOrderData()
        {
            var data = OrdersDetails.GetAllRecords().ToList();
            return data;
        }
        [HttpPost]
        [Route("api/[controller]/SelectRecord")]
        public ActionResult SelectRecord([FromBody] List<Gridcolumns> row)
        {
            return Json(row);
        }
        public class SelectedModel
        {
            public List<Gridcolumns> rowData { get; set; }
        }
        public class Gridcolumns
        {
            public int OrderID { get; set; }
            public string CustomerID { get; set; }
            public int EmployeeID { get; set; }
            public DateTime OrderDate { get; set; }
        }
    }
}

Step 5: Create a model class named OrdersDetails.cs under the Models folder in the server-side project to represent the order data. Add the following code:

namespace SelectedReacord.Server.Models
{
    public class OrdersDetails
    {
        public static List<OrdersDetails> order = new List<OrdersDetails>();
        public OrdersDetails()
        {

        }
        public OrdersDetails(
        int OrderID, string CustomerId, int EmployeeId, double Freight, bool Verified,
        DateTime OrderDate, string ShipCity, string ShipName, string ShipCountry,
        DateTime ShippedDate, string ShipAddress)
        {
            this.OrderID = OrderID;
            this.CustomerID = CustomerId;
            this.EmployeeID = EmployeeId;
            this.Freight = Freight;
            this.ShipCity = ShipCity;
            this.Verified = Verified;
            this.OrderDate = OrderDate;
            this.ShipName = ShipName;
            this.ShipCountry = ShipCountry;
            this.ShippedDate = ShippedDate;
            this.ShipAddress = ShipAddress;
        }

        public static List<OrdersDetails> GetAllRecords()
        {
            if (order.Count() == 0)
            {
                int code = 10000;
                for (int i = 1; i < 10; i++)
                {
                    order.Add(new OrdersDetails(code + 1, "ALFKI", i + 0, 2.3 * i, false, new DateTime(1991, 05, 15), "Berlin", "Simons bistro", "Denmark", new DateTime(1996, 7, 16), "Kirchgasse 6"));
                    order.Add(new OrdersDetails(code + 2, "ANATR", i + 2, 3.3 * i, true, new DateTime(1990, 04, 04), "Madrid", "Queen Cozinha", "Brazil", new DateTime(1996, 9, 11), "Avda. Azteca 123"));
                    order.Add(new OrdersDetails(code + 3, "ANTON", i + 1, 4.3 * i, true, new DateTime(1957, 11, 30), "Cholchester", "Frankenversand", "Germany", new DateTime(1996, 10, 7), "Carrera 52 con Ave. Bolívar #65-98 Llano Largo"));
                    order.Add(new OrdersDetails(code + 4, "BLONP", i + 3, 5.3 * i, false, new DateTime(1930, 10, 22), "Marseille", "Ernst Handel", "Austria", new DateTime(1996, 12, 30), "Magazinweg 7"));
                    order.Add(new OrdersDetails(code + 5, "BOLID", i + 4, 6.3 * i, true, new DateTime(1953, 02, 18), "Tsawassen", "Hanari Carnes", "Switzerland", new DateTime(1997, 12, 3), "1029 - 12th Ave. S."));
                    code += 5;
                }
            }
            return order;
        }

        public int? OrderID { get; set; }
        public string? CustomerID { get; set; }
        public int? EmployeeID { get; set; }
        public double? Freight { get; set; }
        public string? ShipCity { get; set; }
        public bool? Verified { get; set; }
        public DateTime OrderDate { get; set; }
        public string? ShipName { get; set; }
        public string? ShipCountry { get; set; }
        public DateTime ShippedDate { get; set; }
        public string? ShipAddress { get; set; }
    }
}

Step 6: In the “Program.cs” file, add the following code:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(builder =>
    {
        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
    });
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseCors();
app.UseDefaultFiles();
app.UseStaticFiles();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapFallbackToFile("/index.html");
app.Run();

The following screenshot shows passing selected records to the server:

Pass selected records to server using fetch