1

Getting familiar with Ag-Grid and caught one problem that I can't pass angular function into menu item cause I assume it gets executed in another scope.

I did assign property for grid as in a tutorial like: [getContextMenuItems]="getContextMenuItems"

And tried to pass angular function to be executed on context menu item click

My angular code looks like this:

 public getContextMenuItems(params: GetContextMenuItemsParams) {
    const items: Array<MenuItemDef> = [{
      name: 'test',
      action: () => { this.a() }
    }];

    return items;
  }

  public a () {
    console.log("test")
  }

Expected output: Should console log out "test" on menu click

Actual output: Cannot read property 'a' of undefined

empeK
  • 121
  • 4
  • This seemed to be relevant with https://stackoverflow.com/questions/42680019/scoping-issues-while-using-context-menu – Ali Khan Sep 30 '19 at 11:02

1 Answers1

0

Loosely speaking, the function getContextMenuItems is executed in an ag-Grid context (not Angular), and hence this will not be your component. (In my version of ag-Grid here, this is undefined.)

Your options are

  1. use the grid context. Assign it a reference to the (grid's parent-) component and access it in getContextMenuItems(params: GetContextMenuItemsParams) as params.context

or

  1. define getContextMenuItems using fat arrow syntax as pointed out by Seeschorle and others here: getContextMenuItems = (params) => { /*...*/ }
DerMike
  • 15,594
  • 13
  • 50
  • 63