Context menu in Angular TreeGrid component
12 Sep 202520 minutes to read
The Syncfusion Angular TreeGrid supports a context menu that appears on right-click, providing quick access to built-in or custom actions. To enable this feature, define default or custom items using the contextMenuItems
property. Inject the ContextMenu
module into the TreeGrid to use context menus.
The following table lists the default context menu items:
Item | Description |
---|---|
AutoFit |
Auto-fits the current column. |
AutoFitAll |
Auto-fits all columns. |
Edit |
Edits the current record. |
Delete |
Deletes the current record. |
Save |
Saves the edited record. |
Cancel |
Cancels edit mode. |
PdfExport |
Exports TreeGrid data as a PDF document. |
ExcelExport |
Exports TreeGrid data as an Excel document. |
CsvExport |
Exports TreeGrid data as a CSV document. |
SortAscending |
Sorts the current column in ascending order. |
SortDescending |
Sorts the current column in descending order. |
FirstPage |
Navigates to the first page. |
PrevPage |
Navigates to the previous page. |
LastPage |
Navigates to the last page. |
NextPage |
Navigates to the next page. |
AddRow |
Adds a new row to the TreeGrid. |
Indent |
Indents the record by one hierarchical level. |
Outdent |
Outdents the record by one hierarchical level. |
import { NgModule,ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid'
import { PageService, SortService, FilterService,EditService,ToolbarService,
ResizeService, ExcelExportService, PdfExportService, ContextMenuService
} from '@syncfusion/ej2-angular-treegrid'
import {ButtonModule} from '@syncfusion/ej2-angular-buttons'
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns'
import { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import { ToolbarItems, RowDD } from '@syncfusion/ej2-angular-treegrid';
@Component({
imports: [
TreeGridModule,
ButtonModule,
DropDownListAllModule,
],
providers: [PageService,
SortService,
FilterService,
EditService,
SortService, ResizeService,
ExcelExportService,
PdfExportService, ContextMenuService,
ToolbarService],
standalone: true,
selector: 'app-container',
template: `<ejs-treegrid [dataSource]='data' #treegrid height='220' [allowPaging]='true' pageSettings='pager'
[contextMenuItems]='contextMenuItems'
[allowResizing]='true' [allowSorting]='true' [treeColumnIndex]='1' childMapping='subtasks' [allowExcelExport]='true' [allowPdfExport]='true'>
<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=120></e-column>
<e-column field='duration' headerText='Duration' textAlign='Right' width=110></e-column>
</e-columns>
</ejs-treegrid>`
})
export class AppComponent implements OnInit {
public data?: Object[];
public pager?: Object;
public editSettings?: Object;
public contextMenuItems?: Object[];
ngOnInit(): void {
this.data = sampleData;
this.editSettings = {allowEditing: true, allowAdding: true, allowDeleting: true, mode:"Row"};
this.contextMenuItems = ['AutoFit', 'AutoFitAll', 'SortAscending', 'SortDescending', 'Edit', 'Delete', 'Save', 'Cancel', 'PdfExport', 'ExcelExport', 'CsvExport', 'FirstPage', 'PrevPage', 'LastPage', 'NextPage', 'Indent', 'Outdent'];
this.pager = { pageSize: 8 }
}
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
Custom context menu items
You can add custom context menu items by defining the contextMenuItems
property as a collection of contextMenuItemModel
. Assign actions to these custom items in the contextMenuClick
event.
In the sample below, a context menu item is added for parent rows to expand or collapse child rows.
import { NgModule,ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid'
import { PageService, SortService, FilterService,EditService,ToolbarService,
ResizeService, ExcelExportService, PdfExportService, ContextMenuService
} from '@syncfusion/ej2-angular-treegrid'
import {ButtonModule} from '@syncfusion/ej2-angular-buttons'
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns'
import { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import { getValue, isNullOrUndefined } from '@syncfusion/ej2-base';
import { BeforeOpenCloseEventArgs } from '@syncfusion/ej2-inputs';
import { MenuEventArgs } from '@syncfusion/ej2-navigations';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
@Component({
imports: [
TreeGridModule,
ButtonModule,
DropDownListAllModule,
],
providers: [PageService,
SortService,
FilterService,
EditService,
SortService, ResizeService,
ExcelExportService,
PdfExportService, ContextMenuService,
ToolbarService],
standalone: true,
selector: 'app-container',
template: `<ejs-treegrid [dataSource]='data' #treegrid height='220' [allowPaging]='true' pageSettings='pager'
[contextMenuItems]='contextMenuItems' [treeColumnIndex]='1'
(contextMenuClick)='contextMenuClick($event)' (contextMenuOpen)='contextMenuOpen($event)' childMapping='subtasks'>
<e-columns>
<e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
<e-column field='taskName' headerText='Task Name' textAlign='Left' width=180></e-column>
<e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=120></e-column>
<e-column field='duration' headerText='Duration' textAlign='Right' width=110></e-column>
</e-columns>
</ejs-treegrid>`
})
export class AppComponent implements OnInit {
public data?: Object[];
public pager?: Object;
public editSettings?: Object;
public contextMenuItems?: Object[];
@ViewChild('treegrid')
public treeGridObj?: TreeGridComponent;
ngOnInit(): void {
this.data = sampleData;
this.editSettings = {allowEditing: true, allowAdding: true, allowDeleting: true, mode:"Row"};
this.contextMenuItems = [
{text: 'Collapse the Row', target: '.e-content', id: 'collapserow'},
{text: 'Expand the Row', target: '.e-content', id: 'expandrow'}
];
this.pager = { pageSize: 8 }
}
contextMenuClick(args?: MenuEventArgs): void {
(this.treeGridObj as TreeGridComponent).getColumnByField('taskID');
if ((args as MenuEventArgs ).item.id === 'collapserow') {
(this.treeGridObj as TreeGridComponent).collapseRow(<HTMLTableRowElement>((this.treeGridObj as TreeGridComponent).getSelectedRows()[0]));
} else {
(this.treeGridObj as TreeGridComponent).expandRow(<HTMLTableRowElement>((this.treeGridObj as TreeGridComponent).getSelectedRows()[0]));
}
}
contextMenuOpen(arg?: BeforeOpenCloseEventArgs) : void {
let elem: Element = (arg as BeforeOpenCloseEventArgs ).event.target as Element;
let uid: string = (elem.closest('.e-row') as Element).getAttribute('data-uid') as string;
if (isNullOrUndefined(getValue('hasChildRecords', (this.treeGridObj as TreeGridComponent).grid.getRowObjectFromUID(uid).data))) {
( arg as BeforeOpenCloseEventArgs ).cancel = true;
} else {
let flag: boolean = getValue('expanded', (this.treeGridObj as TreeGridComponent).grid.getRowObjectFromUID(uid).data);
let val: string = flag ? 'none' : 'block';
document.querySelectorAll('li#expandrow')[0].setAttribute('style', 'display: ' + val + ';');
val = !flag ? 'none' : 'block';
document.querySelectorAll('li#collapserow')[0].setAttribute('style', 'display: ' + val + ';');
}
}
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
Enable and disable context menu items dynamically
Context menu items can be enabled or disabled dynamically using the enableItems
method within the contextMenuOpen
event.
import { NgModule,ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid'
import { PageService, SortService, FilterService,EditService,ToolbarService,
ResizeService, ExcelExportService, PdfExportService, ContextMenuService
} from '@syncfusion/ej2-angular-treegrid'
import {ButtonModule} from '@syncfusion/ej2-angular-buttons'
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns'
import { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import { getValue, isNullOrUndefined } from '@syncfusion/ej2-base';
import { BeforeOpenCloseEventArgs } from '@syncfusion/ej2-inputs';
import { MenuEventArgs } from '@syncfusion/ej2-navigations';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
@Component({
imports: [
TreeGridModule,
ButtonModule,
DropDownListAllModule,
],
providers: [PageService,
SortService,
FilterService,
EditService,
SortService, ResizeService,
ExcelExportService,
PdfExportService, ContextMenuService,
ToolbarService],
standalone: true,
selector: 'app-container',
template: `<ejs-treegrid [dataSource]='data' #treegrid height='220' [allowPaging]='true' pageSettings='pager' [editSettings]='editSettings'
[contextMenuItems]='contextMenuItems' [treeColumnIndex]='1' (contextMenuOpen)='contextMenuOpen($event)' (contextMenuClick)='contextMenuClick($event)' childMapping='subtasks'>
<e-columns>
<e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
<e-column field='taskName' headerText='Task Name' textAlign='Left' width=180></e-column>
<e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=120></e-column>
<e-column field='duration' headerText='Duration' textAlign='Right' width=110></e-column>
</e-columns>
</ejs-treegrid>`
})
export class AppComponent implements OnInit {
public data?: Object[];
public pager?: Object;
public editSettings?: Object;
public contextMenuItems?: Object[];
@ViewChild('treegrid')
public treegrid?: TreeGridComponent;
ngOnInit(): void {
this.data = sampleData;
this.editSettings = {allowEditing: true, allowAdding: true, allowDeleting: true, mode:"Row"};
this.contextMenuItems=[
{ text: 'Edit Record', target: '.e-content', id: 'Edit_record' },
{ text: 'Delete Record', target: '.e-content', id: 'Delete_record' },
];
this.pager = { pageSize: 8 }
}
contextMenuClick(args?: MenuEventArgs): void {
if((args as MenuEventArgs).element.innerHTML == "Edit Record"){
(this.treegrid as TreeGridComponent).startEdit((args as MenuEventArgs | any).rowInfo.row);
}
else if((args as MenuEventArgs).element.innerHTML == "Delete Record"){
(this.treegrid as TreeGridComponent).deleteRecord((args as MenuEventArgs | any).rowInfo.row);
}
}
contextMenuOpen(args?: BeforeOpenCloseEventArgs): void {
if ((args as BeforeOpenCloseEventArgs | any).rowInfo.rowData.hasChildRecords == true){
(this.treegrid as TreeGridComponent).grid.contextMenuModule.contextMenu.enableItems(['Edit Record'],true);//Enable edit
(this.treegrid as TreeGridComponent).grid.contextMenuModule.contextMenu.enableItems(['Delete Record'],false);//Disable delete
} else {
(this.treegrid as TreeGridComponent).grid.contextMenuModule.contextMenu.enableItems(['Edit Record'],false);//Disable edit
(this.treegrid as TreeGridComponent).grid.contextMenuModule.contextMenu.enableItems(['Delete Record'],true);//Enable edit
}
}
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
To show or hide a context menu item for specific areas within the TreeGrid, use the
target
property.
For a complete overview of features, visit the Angular TreeGrid feature tour. Explore the Angular TreeGrid example to see how data can be presented and manipulated.