angularag-grid-angular

Ag Grid Angular Context Menu calling function


Unable to call a function from Context Menu items in AG Grid Angular, here is my high level code

  ngOnInit(): void {
    this.getContextMenuItems = (params) => this.getMenuItems(params);
  }

  deleteMenuItemEvent = (rowdata) => {
    window.alert("Test Test");
  };

 getMenuItems(
    params: GetContextMenuItemsParams
  ): (string | MenuItemDef)[] {
   
    var result: (string | MenuItemDef)[] = [
      {
        // custom item
        name: "Menu Item 1",
        action: () => this.deleteMenuItemEvent(params),
        cssClasses: ['red', 'bold'],
      },
      {
        // custom item
        name: "Menu Item 2",
        action: function () {
          this.deleteMenuItemEvent(params);
        }
      }
    ];
    return result;
  }

Getting the below error

TypeError: Cannot read properties of undefined (reading 'deleteMenuItemEvent')

Tried the options from below url but no luck, is there any thing else to be done

[https://stackoverflow.com/questions/42680019/scoping-issues-while-using-context-menu][1]


Solution

  • You can just use .bind(this) to ensure the function always executes on the component context!

    Function.prototype.bind Docs

      ngOnInit(): void {
        this.getContextMenuItems = (params) => this.getMenuItems(params);
      }
    
      deleteMenuItemEvent = (params) => {
        const rowData = params.node.data;
        window.alert("Test Test");
      };
    
     getMenuItems(
        params: GetContextMenuItemsParams
      ): (string | MenuItemDef)[] {
       
        var result: (string | MenuItemDef)[] = [
          {
            // custom item
            name: "Menu Item 1",
            action: this.deleteMenuItemEvent.bind(this), // tells js to execute on the context of 
            // this component where deleteMenuItemEvent method exists!
            cssClasses: ['red', 'bold'],
          },
          {
            // custom item
            name: "Menu Item 2",
            action: this.deleteMenuItemEvent.bind(this), // tells js to execute on the context of 
            // this component where deleteMenuItemEvent method exists!
          }
        ];
        return result;
      }