Row drag and drop in Angular Grid component

31 Aug 202424 minutes to read

The Syncfusion Angular Grid component provides built-in support for row drag and drop functionality. This feature allows you to easily rearrange rows within the grid by dragging and dropping them to new positions. Additionally, you can also drag and drop rows from one grid to another grid, as well as drag and drop rows to custom components.

To use the row drag and drop feature in Grid component, you need to inject the RowDDService in the provider section of the AppModule. The RowDDService is responsible for handling the row drag and drop functionality in the grid component. Once you have injected the RowDDService, you can then use the allowRowDragAndDrop and targetID properties to enable and configure the row drag and drop feature in the Grid.

Drag and drop within grid

The drag and drop feature allows you to rearrange rows within the grid by dragging them using a drag icon. This feature can be enabled by setting the allowRowDragAndDrop property to true. This property is a boolean value that determines whether row drag and drop is enabled or not. By default, it is set to false, which means that row drag and drop is disabled.

Here’s an example of how to enable drag and drop within the Grid:

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

import { Component, OnInit } from '@angular/core';
import { orderDetails } from './datasource';
import { SelectionSettingsModel } from '@syncfusion/ej2-angular-grids';

@Component({
imports: [
        
        GridModule
    ],

providers: [PageService, SelectionService, RowDDService],
standalone: true,
    selector: 'app-root',
    template: `<div class="control-section">
                <ejs-grid [dataSource]='data' [allowRowDragAndDrop]='true'
                [selectionSettings]='selectionOptions' height='400'>
                    <e-columns>
                        <e-column field='OrderID' headerText='Order ID' width='120'
                        textAlign='Right'></e-column>
                        <e-column field='CustomerID' headerText='Customer ID' width='120'>
                        </e-column>
                        <e-column field='OrderDate' headerText='Order Date' width='100' 
                        format="yMd" textAlign='Right'></e-column>
                        <e-column field='Freight' headerText='Freight' width='120' format='C2' 
                        textAlign='Right'></e-column>
                        <e-column field='ShipCity' headerText='Ship City' width='130'>
                        </e-column>
                        <e-column field='ShipCountry' headerText='Ship Country' width='130'>
                        </e-column>
                    </e-columns>
                </ejs-grid>
              </div>`
  })
export class AppComponent implements OnInit {

    public data?: object[];
    public selectionOptions?: SelectionSettingsModel;

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

Drag and drop to grid

The grid row drag and drop allows you to drag grid rows and drop to another grid. This feature can be enabled by setting the allowRowDragAndDrop property to true in the Grid component. This property specifies whether to enable or disable the row drag and drop feature in the Grid. By default, this property is set to false, which means that row drag and drop functionality is not enabled.

To specify the target component where the grid rows should be dropped, use the targetID property of the rowDropSettings object. The targetID property takes the ID of the target component as its value.

Here’s an example code snippet that demonstrates how to enable Row drag and drop another Grid component:

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

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

@Component({
imports: [
        
        GridModule
    ],

providers: [PageService, SelectionService, RowDDService],
standalone: true,
    selector: 'app-root',
    template: `<ejs-grid id='Grid' [dataSource]='data' [allowRowDragAndDrop]='true'
                [rowDropSettings]='rowDropOptions' [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>
                <ejs-grid id='DestGrid' [dataSource]='destGridData' 
                [allowRowDragAndDrop]='true' [rowDropSettings]='destRowDropOptions' 
                [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>`,
    styleUrls: ['./app.style.css']
})
export class AppComponent implements OnInit {

    public data?: object[];
    public destGridData?: object[];
    public rowDropOptions?: RowDropSettingsModel;
    public destRowDropOptions?: RowDropSettingsModel;
    public selectionOptions?: SelectionSettingsModel;

    ngOnInit(): void {
        this.data = data;
        this.destGridData = [];
        this.rowDropOptions = { targetID: 'DestGrid' };
        this.destRowDropOptions = { targetID: 'Grid' };
        this.selectionOptions = { type: 'Multiple' };
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

  • The row drag and drop feature is not supported in virtual scrolling and frozen rows and columns mode.
  • In order to use row drag and drop, you need to inject the RowDDService in the provider section of AppModule.

Drag and drop to custom component

The Grid provides the feature to drag and drop grid rows to any custom component. This feature allows you to easily move rows from one component to another without having to manually copy and paste data. To enable row drag and drop, you need to set the allowRowDragAndDrop property to true and defining the custom component ID in the targetID property of the rowDropSettings object. The ID provided in targetID should correspond to the ID of the target component where the rows are to be dropped.

In the below example, the selected grid row is dragged and dropped in to the TreeView component by using rowDrop event. Once the row is dropped into the TreeView component, we have removed the corresponding grid row from grid and its data inserted in custom component.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, PageService, SelectionService, RowDDService } from '@syncfusion/ej2-angular-grids'
import { TreeGridAllModule } from '@syncfusion/ej2-angular-treegrid'

import { Component, ViewChild,OnInit } from '@angular/core';
import { sampleGridData } from './datasource';
import { isNullOrUndefined } from '@syncfusion/ej2-base';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
import { GridComponent, RowDragEventArgs } from '@syncfusion/ej2-angular-grids';

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

providers: [PageService, SelectionService, RowDDService],
standalone: true,
  selector: 'app-root',
  template: ` <ejs-grid #grid id='Grid' [dataSource]='sourceData' [allowPaging]="true"
              [pageSettings]="true" [allowSelection]="true" [allowRowDragAndDrop]="true" 
              [selectionSettings]="selectionOptions" [rowDropSettings]="srcDropOptions" 
              (rowDrop)='onRowDrop($event)' [editSettings]="gridEditSettings">
                <e-columns> 
                        <e-column field='taskID' headerText='Task ID' textAlign='Right' 
                        width=90></e-column>
                        <e-column field='taskName' headerText='Task Name' textAlign='Left' 
                        width=180></e-column>
                        <e-column field='description' headerText='Description' 
                        textAlign='Left' width=180></e-column>
                        <e-column field='category' headerText='Category' 
                        textAlign='Left' width=180></e-column>
                        <e-column field='startDate' headerText='Start Date' textAlign='Right' 
                        format='yMd' width=120></e-column>
                        <e-column field='duration' headerText='Duration' textAlign='Right' 
                        width=80></e-column>
                </e-columns>
              </ejs-grid>
              <ejs-treegrid #treegrid id='TreeGrid'  
              childMapping='subtasks' [editSettings]='treeGridEditSettings'>
                  <e-columns>
                      <e-column field='taskID' headerText='Task ID'  textAlign='Right' 
                      width=90></e-column>
                      <e-column field='taskName' headerText='Task Name' textAlign='Left' 
                      width=180></e-column>
                      <e-column field='startDate' headerText='Start Date' textAlign='Right' 
                      format='yMd' width=90></e-column>
                      <e-column field='duration' headerText='Duration' textAlign='Right' 
                      width=80></e-column>
                </e-columns>
              </ejs-treegrid>`
})
export class AppComponent implements OnInit {

  @ViewChild('grid')
  gridObject!: GridComponent;
  @ViewChild('treegrid')
  treeGridObject!: TreeGridComponent;
  public sourceData: Object[] = [];
  public selectionOptions?: Object;
  public srcDropOptions?: Object;
  public treegridData: object[] = [];
  public gridEditSettings?:Object;
  public treeGridEditSettings?:Object;

  ngOnInit(): void {

    this.sourceData = sampleGridData;
    this.selectionOptions = { type: 'Multiple' };
    this.srcDropOptions = { targetID: 'TreeGrid' };
    this.gridEditSettings = { allowDeleting: true };
    this.treeGridEditSettings = { allowAdding: true, allowEditing: true };
  }
  onRowDrop(args:RowDragEventArgs) {
    if ((args.target as Element).closest('.e-treegrid')) {
      args.cancel = true;
      var rowIndex = !isNullOrUndefined((args.target as Element).closest('.e-row') as Element)
        ? ((args.target as HTMLElement).closest('.e-row') as any).rowIndex
        : 0;
      for (var i = 0; i < (args.data as Object[]).length; i++) {
        this.treeGridObject.addRecord((args.data as Object[])[i] , rowIndex);
        this.gridObject.deleteRecord('taskID', (args.data as Object[])[i]);
      }
    }
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

  • The rowDrop event is fired when a row is dropped onto a custom component, regardless of whether the drop is successful or not. You can use the args.cancel property to prevent the default action.

Drag and drop rows without drag icons

By default, when performing a drag and drop operation in the Syncfusion Grid, drag icons are displayed. However, in some cases, you may want to hide these drag icons. This can be achieved by setting the targetID property of the rowDropSettings object to the current Grid’s ID.

By setting the targetID, the Grid will render without a helper icon for row dragging. You can then customize the drag and drop action by binding to the rowDrop event of the Grid. In the rowDrop event, you can prevent the default action by setting args.cancel to true, and reorder the rows using the reorderRows method of the Grid.

Here’s an example of how to hide the drag and drop icon in the Syncfusion Grid:

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

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

@Component({
imports: [
        
        GridModule
    ],

providers: [PageService, SelectionService, RowDDService],
standalone: true,
    selector: 'app-root',
    template: `<div class="control-section">
                <ejs-grid #grid [dataSource]="data" [allowRowDragAndDrop]="true"
                [selectionSettings]="selectOptions" [rowDropSettings]="rowDropOptions"
                id="Grid" (rowDrop)="rowDrop($event)">
                    <e-columns>
                        <e-column field="OrderID" headerText="Order ID" width="120"
                        textAlign="Right"></e-column>
                        <e-column field="CustomerID" headerText="Customer Name" 
                        width="130"></e-column>
                        <e-column field="OrderDate" headerText="Order Date" width="120"
                        format="yMd" textAlign="Right"></e-column>
                        <e-column field="Freight" headerText="Freight" width="120"
                        format="C2" textAlign="Right"></e-column>
                        <e-column field="ShipCity" headerText="Ship City" width="130">
                        </e-column>
                        <e-column field="ShipCountry" headerText="Ship Country"
                        width="130"></e-column>
                    </e-columns>
                </ejs-grid>
            </div>`,
    styleUrls: ['./app.style.css']
})
export class AppComponent {
    public data: Object[] = [];
    public selectOptions?: Object;
    public rowDropOptions?: object;
    @ViewChild('grid') public grid?: GridComponent;

    ngOnInit(): void {
        this.data = data;
        this.selectOptions = { type: 'Multiple' };
        this.rowDropOptions = { targetID: 'Grid' };
    }
    rowDrop(args:RowDragEventArgs) {
        args.cancel = true;
        var value = [];
        for (var r = 0; r < (args.rows as Element[]).length; r++) {
            value.push((args.fromIndex as number) + r);
        }
        (this.grid as GridComponent).reorderRows(value, (args.dropIndex as number));
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

  • The selection feature must be enabled in the Grid to allow users to select rows before performing the drag and drop operation.
  • Multiple rows can be selected by clicking and dragging inside the grid. For multiple row selection, the type property must be set to Multiple.

Drag and drop events

The Grid component provides a set of events that are triggered during drag and drop operations on grid rows. These events allow you to customize the drag element, track the progress of the dragging operation, and perform actions when a row is dropped on a target element. The following events are available:

  1. rowDragStartHelper: This event is triggered when a click occurs on the drag icon or a grid row. It allows you to customize the drag element based on specific criteria.

  2. rowDragStart: This event is triggered when the dragging of a grid row starts.

  3. rowDrag: This event is triggered continuously while the grid row is being dragged.

  4. rowDrop: This event is triggered when a drag element is dropped onto a target element.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { GridModule, PageService, SelectionService, RowDDService } from '@syncfusion/ej2-angular-grids'
import { Component, ViewChild,OnInit } from '@angular/core';
import { GridComponent, RowDragEventArgs } from '@syncfusion/ej2-angular-grids';
import { orderDetails, columnDataType } from './datasource';

@Component({
imports: [ GridModule],
providers: [PageService, SelectionService, RowDDService],
standalone: true,
  selector: 'app-root',
  template: `<div style="text-align:center">
             <p style="color:red;" id="message">{{ message }}</p>
             </div>
            <ejs-grid #grid [dataSource]="data" [allowPaging]="true" 
            [allowRowDragAndDrop]="true" (rowDragStartHelper)="rowDragStartHelper($event)"
            [selectionSettings]="selectOptions" 
            id="Grid" (rowDrop)="rowDrop($event)"  (rowDragStart)="rowDragStart($event)" 
            (rowDrag)="rowDrag($event)">
              <e-columns>
                <e-column field="OrderID" headerText="Order ID" width="120"
                textAlign="Right"></e-column>
                <e-column field="CustomerID" headerText="Customer Name" 
                width="130"></e-column>
                <e-column field="OrderDate" headerText="Order Date" width="120"
                format="yMd" textAlign="Right"></e-column>
                <e-column field="Freight" headerText="Freight" width="120"
                format="C2" textAlign="Right"></e-column>
                <e-column field="ShipCity" headerText="Ship City" width="120">
                </e-column>
                <e-column field="ShipCountry" headerText="Ship Country"
                width="120"></e-column>
              </e-columns>
            </ejs-grid>`,
  styleUrls: ['./app.style.css']

})
export class AppComponent implements OnInit {

  public data: Object[] = [];
  public selectOptions?: Object;
  public message?: string;
  @ViewChild('grid')
  public grid!: GridComponent;

  ngOnInit(): void {
    this.data = orderDetails;
    this.selectOptions = { type: 'Multiple' };
  }
  rowDragStartHelper(args: RowDragEventArgs): void {
    this.message = `rowDragStartHelper event triggered`;
    if (((args.data as Object[])[0] as columnDataType).OrderID === 10248) {
      args.cancel = true;
    }
  }
  rowDragStart(args: RowDragEventArgs) {
    this.message = `rowDragStart event triggered`;
    args.cancel = true;
  }
  rowDrag(args:RowDragEventArgs): void {
    this.message = `rowDrag event triggered`;
    (args.rows as Element[]).forEach((row: Element) => {
      row .classList.add('drag-limit');
    });
  }
  rowDrop(args: RowDragEventArgs): void {
    this.message = `rowDrop event triggered`;
    const value = [];
    for (let r = 0; r < (args.rows as Element[]).length; r++) {
      value.push((args.fromIndex as number) + r);
    }
    this.grid.reorderRows(value, (args.dropIndex as number));
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Limitations

  • Single row is able to drag and drop in same grid without enable the row selection.
  • Row drag and drop feature is not having built in support with row template, detail template and hierarchy grid features of grid.

See also

Sorting data in the Syncfusion Grid
Filtering data in the Syncfusion Grid