Context menu in EJ2 TypeScript Grid control

22 Feb 202424 minutes to read

The Syncfusion EJ2 TypeScript Grid control comes equipped with a context menu feature, which is triggered when a user right-clicks anywhere within the grid. This feature serves to enrich the user experience by offering immediate access to a variety of supplementary actions and operations that can be executed on the data displayed in the grid.

In essence, the context menu provides a convenient and efficient way for users to interact with and manipulate the grid’s content, enabling them to perform tasks such as sorting, filtering, editing, or any other relevant actions without the need for navigating through the grid’s interface. This user-friendly feature streamlines the overall usability of the EJ2 TypeScript Grid, making it a powerful tool for data management and manipulation.

To activate the context menu within the grid, you have an option to configure the grid’s contextMenuItems property. You can set this property to either include the default context menu items or define your own custom context menu items, tailoring the menu options to suit your specific needs. This customization allows you to enhance the grid’s functionality by providing context-sensitive actions for interacting with your data.

To use the context menu, inject the ContextMenu module in the grid.

The context menu is triggered when you right-click on different areas of the grid, including:

  • Header: When you right-click on the grid’s header section.
  • Content: When you right-click on the grid’s main content area.
  • Pager: When you right-click on the pager section.

The context menu items that appear vary depending on the area you have clicked. For instance, the items available in the context menu when clicking on the header area differ from those in the content area or pager.

The default context menu items in the header area of the grid are as follows:

Items Description
AutoFit Automatically adjust the column width to fit the content.
AutoFitAll Automatically adjust all column widths to fit their content.
Group Group the data based on the current column.
Ungroup Remove grouping for the current column.
SortAscending Sort the current column in ascending order.
SortDescending Sort the current column in descending order.

The default context menu items in the content area of the grid are as follows:

Items Description
Edit Edit the currently selected record in the grid.
Delete Delete the currently selected record.
Save Save the changes made to the edited record.
Cancel Cancel the edit state and revert changes made to the edited record.
Copy Copy the selected records to the clipboard.
PdfExport Export the grid data as a PDF document.
ExcelExport Export the grid data as an Excel document.
CsvExport Export the grid data as a CSV document.

The default context menu items in the pager area of the grid are as follows:

Items Description
FirstPage Navigate to the first page of the grid.
PrevPage Navigate to the previous page of the grid.
LastPage Navigate to the last page of the grid.
NextPage Navigate to the next page of the grid.

The following example demonstrates how to enable context menu feature in the grid.

import { Grid, Resize, Sort, Group, ContextMenu, Edit, Page, PdfExport, ExcelExport } from '@syncfusion/ej2-grids';
import { data  } from './datasource.ts';

Grid.Inject(Resize, Sort, Group, Edit, ContextMenu, Page, PdfExport, ExcelExport);

let grid: Grid = new Grid({
    dataSource: data,
    allowSorting: true,
    allowPaging: true,
    allowGrouping:true,
    editSettings: {allowEditing: true, allowDeleting: true },
    allowPdfExport: true,
    allowExcelExport: true,
    contextMenuItems: ['AutoFit', 'AutoFitAll', 'SortAscending', 'SortDescending', 'Copy', 'Edit', 'Delete', 'Save', 'Cancel', 'PdfExport', 'ExcelExport', 'CsvExport', 'FirstPage', 'PrevPage', 'LastPage', 'NextPage', 'Group', 'Ungroup'],
    columns: [
        { field: 'OrderID', headerText: 'Order ID', width: 90, textAlign: 'Right', isPrimaryKey:true},
        { field: 'CustomerID', headerText: 'Customer Name', width: 100 },
        { field: 'Freight', headerText:'Freight', width: 80, format: 'C2', textAlign: 'Right', editType: 'numericedit' },
        { field: 'ShipCity', headerText: 'Ship City', width: 100 }
    ]
});
grid.appendTo('#Grid');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='Grid'></div>
    </div>
</body>
</html>

Custom context menu items

The Syncfusion EJ2 TypeScript Grid empowers you to enhance your user experience by incorporating custom context menu items into the default context menu. These customized options enable you to tailor the context menu to meet the unique requirements of your application.

By adding custom context menu items, you can introduce additional actions or operations that are directly relevant to your specific use case. This flexibility allows you to create a highly personalized and efficient interaction with your grid, making it a powerful tool for data management and manipulation.

To add custom context menu items by defining the contextMenuItems property as a collection of contextMenuItemModel. You can also define actions for these customized items using the contextMenuClick event.

To incorporate custom context menu items in the Syncfusion EJ2 TypeScript Grid, you can achieve this by specifying the contextMenuItems property as a collection of contextMenuItemModel. This allows you to define and customize the appearance and behavior of these additional context menu items according to your requirements.

Furthermore, you can assign actions to these custom items by utilizing the contextMenuClick event. This event provides you with the means to handle user interactions with the custom context menu items, enabling you to execute specific actions or operations when these items are clicked.

The following example demonstrates how to add custom context menu items in the Grid control.

import { Grid, ContextMenu, Page } from '@syncfusion/ej2-grids';
import { employeeData  } from './datasource.ts';
import { MenuEventArgs } from '@syncfusion/ej2-navigations';

Grid.Inject(ContextMenu, Page);

let grid: Grid = new Grid({
    dataSource: employeeData,
    contextMenuItems: [{text: 'Copy with headers', target: '.e-content', id: 'copywithheader'}],
    allowSelection: true,
    allowPaging: true,
    contextMenuClick: function(args: MenuEventArgs){
        if(args.item.id === 'copywithheader'){
            grid.copy(true);
        }
    },
    columns: [
        { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 120,  isPrimaryKey: true },
        { field: 'FirstName', headerText: 'First Name', width: 150 },
        { field: 'LastName', headerText: 'Last Name', width: 150 },
        { field: 'City', headerText: 'City', width: 150 }
    ],
    height:265
});
grid.appendTo('#Grid');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='Grid'></div>
    </div>
</body>
</html>

Show context menu on left click

The Syncfusion EJ2 TypeScript Grid provides the ability to show the context menu items on a left mouse click instead of the default right mouse click action.

This can be achieved by using the created event and the context menu’s beforeOpen event of the Grid.

By using the onclick event listener of the Grid, you can obtain the clicked position values. The obtained positions are then sent to the open method of the context menu within the onclick event of the Grid. Additionally, the default action of right-clicking to open the context menu items items is prevented by utilizing the created event of the Grid.

The following example demonstrates how to show context menu on left click using created event.

import { Grid, Page, ContextMenu, ExcelExport, PdfExport, Sort, MouseEvent} from '@syncfusion/ej2-grids';
import { data } from './datasource.ts';
import { BeforeOpenCloseMenuEventArgs } from '@syncfusion/ej2-navigations';

Grid.Inject( Page, ContextMenu, ExcelExport, PdfExport, Sort);

let values: any;
let grid: Grid = new Grid({
  dataSource: data,
  allowPaging: true,
  allowPdfExport: true,
  allowExcelExport: true,
  allowSorting: true,
  contextMenuItems: ['SortAscending', 'SortDescending', 'PdfExport', 'ExcelExport', 'FirstPage', 'PrevPage', 'LastPage', 'NextPage'],
  columns: [
    { field: 'OrderID', headerText: 'Order ID', width: '90', textAlign: 'Right', isPrimaryKey: true },
    { field: 'CustomerID', headerText: 'Customer Name', width: '100' },
    { field: 'ShipCountry', headerText: 'Ship Country', width: '100' },
    { field: 'ShipCity', headerText: 'Ship City', width: '100' },
  ],
  created: () => {
    grid.contextMenuModule.contextMenu.beforeOpen = (args:BeforeOpenCloseMenuEventArgs) => {
      if (args.event && args.event.which === 3)
      {
        args.cancel = true;
      }  
      args.event = values;
      grid.contextMenuModule.contextMenuBeforeOpen(args);
    };
  },
});
grid.appendTo('#Grid');

(document.getElementById('Grid') as HTMLElement).onclick = (event: MouseEvent) => {
  values = event;
  grid.contextMenuModule.contextMenu.open(
    values.pageY + pageYOffset,
    values.pageX + pageXOffset
  );
};
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='Grid'></div>
    </div>
</body>
</html>

You can hide or show an item in context menu for specific area inside of grid by defining the target property.

Enable or disable context menu items

With the Syncfusion EJ2 TypeScript Grid, you have the ability to manage the activation or deactivation of both default and custom context menu items. This feature provides you with the flexibility to tailor the behavior of context menu items to suit specific conditions or individual interactions within your application.

By enabling or disabling context menu items, you can ensure that certain options are available or restricted based on the context of the data or the needs of your users. This level of control allows you to create a more dynamic and user-centric experience with the grid, aligning it with your application’s requirements and enhancing usability.

This can be achieved using the enableItems method of the context menu. By setting the enable parameter in the enableItems method to true, you can enable context menu items, and by setting it to false, you can disable them. Based on your specific condition or requirements, you can enable or disable the context menu item using the enableItems method.

In the following example, the EJ2 Toggle Switch Button control is added to enable and disable the context menu items using enableItems method. When the switch is toggled, the change event is triggered, and the Copy items is updated accordingly.

import { Grid, Edit, Page, ContextMenu } from '@syncfusion/ej2-grids';
import { data } from './datasource.ts';
import { Switch, ChangeEventArgs } from '@syncfusion/ej2-buttons';

Grid.Inject( Edit, Page, ContextMenu);

let grid: Grid = new Grid({
    dataSource: data,
    editSettings: { allowAdding: true, allowDeleting: true, allowEditing: true },
    allowPaging: true,
    contextMenuItems: ['Copy', 'Edit', 'Delete'],
    columns: [
        { field: 'OrderID', headerText: 'Order ID', width: 90, textAlign: 'Right', isPrimaryKey: true },
        { field: 'CustomerID', headerText: 'Customer Name', width: 100 },
        { field: 'Freight', headerText: 'Freight', format: 'C2', textAlign: 'Right', editType: 'numericedit', width: 90 },
        { field: 'ShipCity', headerText: 'Ship City', width: 150 }
    ]
});
grid.appendTo('#Grid');

let toggle: Switch = new Switch({
    change: onSwitchChange,
});
toggle.appendTo('#switch');

function onSwitchChange(args: ChangeEventArgs) {
    if (args.checked) {
        grid.contextMenuModule.contextMenu.enableItems(['Copy'], false);
    } else {
        grid.contextMenuModule.contextMenu.enableItems(['Copy'], true);
    }
}
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <label style="padding: 10px 10px"> Enable or disable context menu items </label>
        <input id="switch" type="checkbox"/>
        <div id='Grid' style="padding: 10px"></div>
    </div>
</body>
</html>

Show or hide context menu items

The Syncfusion EJ2 TypeScript Grid provides the flexibility to show or hide both default and custom context menu items. This feature allows you to customize the context menu items based on various conditions or individuals interactions.

This can be achieved using the showItems and hideItems methods of the context menu by specifying the item you want to show or hide as an argument.

In the following example, the EJ2 Toggle Switch Button control is added to show or hide the context menu items using showItems and hideItems methods. When the switch is toggled, the change event is triggered, and the Copy items is updated accordingly.

import { Grid, Edit, Page, ContextMenu } from '@syncfusion/ej2-grids';
import { data } from './datasource.ts';
import { Switch, ChangeEventArgs } from '@syncfusion/ej2-buttons';

Grid.Inject( Edit, Page, ContextMenu);

let grid: Grid = new Grid({
    dataSource: data,
    editSettings: { allowAdding: true, allowDeleting: true, allowEditing: true },
    allowPaging: true,
    contextMenuItems: ['Copy', 'Edit', 'Delete'],
    columns: [
        { field: 'OrderID', headerText: 'Order ID', width: 90, textAlign: 'Right', isPrimaryKey: true },
        { field: 'CustomerID', headerText: 'Customer Name', width: 100 },
        { field: 'Freight', headerText: 'Freight', format: 'C2', textAlign: 'Right', editType: 'numericedit', width: 90 },
        { field: 'ShipCity', headerText: 'Ship City', width: 150 }
    ]
});
grid.appendTo('#Grid');

let toggle: Switch = new Switch({
    change: onSwitchChange,
});
toggle.appendTo('#switch');

function onSwitchChange(args: ChangeEventArgs) {
    if (args.checked) {
        grid.contextMenuModule.contextMenu.hideItems([
            'Edit Record',
            'Delete Record',
          ]);
    } else {
        grid.contextMenuModule.contextMenu.showItems([
            'Edit Record',
            'Delete Record',
          ]);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/25.1.35/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <label style="padding: 10px 10px"> Show or hide context menu items </label>
        <input id="switch" type="checkbox"/>
        <div id='Grid' style="padding: 10px"></div>
    </div>
</body>
</html>