Context menu in Vue Treegrid component

20 Mar 202316 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.
<template>
<div id="app">
        <ejs-treegrid :dataSource='data' childMapping='subtasks' :treeColumnIndex='1' :allowPaging='true' :pageSettings='pageSettings' :allowSorting='true' :allowResizing='true' :editSettings='editSettings' :allowPdfExport='true' :allowExcelExport='true' :contextMenuItems="contextMenuItems">
            <e-columns>
                <e-column field='taskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
                <e-column field='taskName' headerText='Task Name' width='160'></e-column>
                <e-column field='startDate' headerText='Start Date' width='90' format="yMd" textAlign='Right'></e-column>
                <e-column field='duration' headerText='Duration' width='80' textAlign='Right'></e-column>
            </e-columns>
        </ejs-treegrid>
</div>
</template>
<script>
import Vue from "vue";
import { TreeGridPlugin, Resize, Sort, ContextMenu, Edit, Page, PdfExport, ExcelExport, RowDD } from "@syncfusion/ej2-vue-treegrid";
import { sampleData } from "./datasource.js";

Vue.use(TreeGridPlugin);

export default {
  data ()  {
    return {
      data: sampleData,
      editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true },
      pageSettings: { pageSize: 7 },
      contextMenuItems: ['AutoFit', 'AutoFitAll', 'SortAscending', 'SortDescending',
        'Copy', 'Edit', 'Delete', 'Save', 'Cancel',
        'PdfExport', 'ExcelExport', 'CsvExport', 'FirstPage', 'PrevPage',
        'LastPage', 'NextPage', 'Group', 'Ungroup', 'Indent', 'Outdent'],
    };
  },
  provide: {
      treegrid: [ Resize, Sort, ContextMenu, Edit, Page, PdfExport, ExcelExport ]
    }
}
</script>

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.

<template>
<div id="app">
        <ejs-treegrid ref='treegrid' :dataSource='data' childMapping='subtasks' :treeColumnIndex='1' :allowPaging='true' :pageSettings='pageSettings' :contextMenuItems="contextMenuItems" :contextMenuOpen='contextMenuOpen' :contextMenuClick='contextMenuClick'>
            <e-columns>
                <e-column field='taskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
                <e-column field='taskName' headerText='Task Name' width='160'></e-column>
                <e-column field='startDate' headerText='Start Date' width='90' format="yMd" textAlign='Right'></e-column>
                <e-column field='duration' headerText='Duration' width='80' textAlign='Right'></e-column>
            </e-columns>
        </ejs-treegrid>
</div>
</template>
<script>
import Vue from "vue";
import { TreeGridPlugin, ContextMenu, Page, TreeGridComponent  } from "@syncfusion/ej2-vue-treegrid";
import { sampleData } from "./datasource.js";
import { BeforeOpenCloseEventArgs } from '@syncfusion/ej2-vue-inputs';
import { MenuEventArgs } from '@syncfusion/ej2-vue-navigations';
import { getValue, isNullOrUndefined } from '@syncfusion/ej2-base';

Vue.use(TreeGridPlugin);

export default {
  data ()  {
    return {
      data: sampleData,
      pageSettings: { pageSize: 7 },
      contextMenuItems: [
          {text: 'Collapse the Row', target: '.e-content', id: 'collapserow'},
          {text: 'Expand the Row', target: '.e-content', id: 'expandrow'}
      ],
    };
  },
  provide: {
      treegrid: [ ContextMenu, Page ]
  },
  methods:{
      contextMenuOpen:function (arg: BeforeOpenCloseEventArgs) {
        let elem: Element = arg.event.target as Element;
        let uid = (elem.closest('.e-row') as HTMLTableRowElement).getAttribute('data-uid');
        if (isNullOrUndefined(getValue('hasChildRecords', this.$refs.treegrid.ej2Instances.grid.getRowObjectFromUID(uid).data))) {
            arg.cancel = true;
        } else {
          let flag: boolean = getValue('expanded', this.$refs.treegrid.ej2Instances.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 + ';');
        }
      },
      contextMenuClick:function (args: MenuEventArgs) {
        let selectedRows = this.$refs.treegrid.getSelectedRows() as any;
        let selectedRecords = this.$refs.treegrid.getSelectedRecords() as any;
        if (args.item.id === 'collapserow') {
          this.$refs.treegrid.collapseRow(selectedRows[0] as HTMLTableRowElement, selectedRecords[0]);
        } else {
          this.$refs.treegrid.expandRow(selectedRows[0] as HTMLTableRowElement, selectedRecords[0]);
        }
      }
  }
}
</script>

Enable and disable context menu items dynamically

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

<template>
<div id="app">
        <ejs-treegrid ref='treegrid' :dataSource='data' childMapping='subtasks' :treeColumnIndex='1' :editSettings='editSettings' :allowPaging='true' :pageSettings='pageSettings' :contextMenuItems="contextMenuItems" :contextMenuOpen='contextMenuOpen' :contextMenuClick='contextMenuClick'>
            <e-columns>
                <e-column field='taskID' headerText='Task ID' width='90' textAlign='Right'></e-column>
                <e-column field='taskName' headerText='Task Name' width='160'></e-column>
                <e-column field='startDate' headerText='Start Date' width='90' format="yMd" textAlign='Right'></e-column>
                <e-column field='duration' headerText='Duration' width='80' textAlign='Right'></e-column>
            </e-columns>
        </ejs-treegrid>
</div>
</template>

<script>
import Vue from "vue";
import { TreeGridPlugin, ContextMenu, Page, Edit, TreeGridComponent  } from "@syncfusion/ej2-vue-treegrid";
import { sampleData } from "./datasource.js";
import { BeforeOpenCloseEventArgs } from '@syncfusion/ej2-vue-inputs';
import { MenuEventArgs } from '@syncfusion/ej2-vue-navigations';
import { getValue, isNullOrUndefined } from '@syncfusion/ej2-base';

Vue.use(TreeGridPlugin);

export default {
  data ()  {
    return {
      data: sampleData,
      editSettings: { allowDeleting: true, allowEditing: true, allowAdding: true, mode: 'Row' },
      pageSettings: { pageSize: 7 },
      contextMenuItems: [
          {text: 'Edit Record', target: '.e-content', id: 'Edit_record'},
          { text: 'Delete Record', target: '.e-content', id: 'Delete_record' },
      ],
    };
  },
  provide: {
      treegrid: [ ContextMenu, Page, Edit ]
  },
  methods:{
      contextMenuOpen:function (args: BeforeOpenCloseEventArgs) {
        if (args.rowInfo.rowData.hasChildRecords == true) {
          this.$refs.treegrid.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Edit Record'],true);
          this.$refs.treegrid.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Delete Record'],false);
        } else  {
          this.$refs.treegrid.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Edit Record'],false);
          this.$refs.treegrid.ej2Instances.grid.contextMenuModule.contextMenu.enableItems(['Delete Record'],true);
        }
      },
      contextMenuClick:function (args: MenuEventArgs) {
        if(args.element.innerHTML == "Edit Record"){
            this.$refs.treegrid.ej2Instances.grid.editModule.startEdit(args.rowInfo.row);
        }
        else if(args.element.innerHTML == "Delete Record"){
             this.$refs.treegrid.ej2Instances.grid.editModule.deleteRecord(args.rowInfo.row);
        }
      }
  }
}
</script>

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