Context menu in Angular Treegrid component

27 Sep 202321 minutes to read

The TreeGrid has options to show the context menu when right clicked on it. To enable this feature, you need to define either default or custom item in the contextMenuItems.

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

The default items are in the following table.

Items Description
AutoFit Auto fit the current column.
AutoFitAll Auto fit all columns.
Edit Edit the current record.
Delete Delete the current record.
Save Save the edited record.
Cancel Cancel the edited state.
PdfExport Export the treegrid data as Pdf document.
ExcelExport Export the treegrid data as Excel document.
CsvExport Export the treegrid data as CSV document.
SortAscending Sort the current column in ascending order.
SortDescending Sort the current column in descending order.
FirstPage Go to the first page.
PrevPage Go to the previous page.
LastPage Go to the last page.
NextPage Go to the next page.
AddRow Add new row to the treegrid.
Indent Indents the record to one level of hierarchy.
Outdent Outdents the record to one level of hierarchy.
import { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import { ToolbarItems, RowDD } from '@syncfusion/ej2-angular-treegrid';

@Component({
    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 { 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 { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule,
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                EditService,
                SortService, ResizeService, 
                ExcelExportService, 
                PdfExportService, ContextMenuService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Custom context menu items

The custom context menu items can be added by defining the contextMenuItems as a collection of contextMenuItemModel.
Actions for this customized items can be defined in the contextMenuClick event.

In the below sample, we have shown context menu item for parent rows to expand or collapse child rows.

import { Component, OnInit, ViewChild } 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({
    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 { 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 { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule,
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                EditService,
                SortService, ResizeService, 
                ExcelExportService, 
                PdfExportService, ContextMenuService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

Enable and disable context menu items dynamically

You can enable and disable the context menu items using the enableItems method in contextMenuOpen event.

import { Component, OnInit, ViewChild } 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({
    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 { 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 { AppComponent } from './app.component';
import {ButtonModule} from '@syncfusion/ej2-angular-buttons';
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        TreeGridModule,
        ButtonModule,
        DropDownListAllModule,
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PageService,
                SortService,
                FilterService,
                EditService,
                SortService, ResizeService, 
                ExcelExportService, 
                PdfExportService, ContextMenuService,
                ToolbarService]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);

You can hide or show an item in context menu for specific area inside of treegrid by defining the target property.
You can refer to our Angular Tree Grid feature tour page for its groundbreaking feature representations. You can also explore our Angular Tree Grid example to knows how to present and manipulate data.