Search code examples
javascriptag-gridag-grid-ng2

Update & Delete by Custom Context Menu Ag-Grid


I am using ag-grid with angular 2.

I have created a custom context menu that has delete and update buttons. In a scenario, the user select one or more rows and then right clicks and clicks delete or update button.

These buttons call some functions those handles with gridOptions in order to get selected rows.

However; when I click the delete or update buttons, I have an error that says this.gripOptions is undefined.

Is there any example or documentation about this? How can I overcome this problem?

Thanks for the replies

    var gridOptions = {
        columnDefs: columnDefs,
        enableRangeSelection: true,
        getContextMenuItems: getContextMenuItems,
        allowContextMenuWithControlKey: true
    };
    getContextMenuItems(params) {
        var result = [
            { // custom item
                name: 'Delete',
                action: function () { this.delete()); }
            } 

    return result;
    }

    delete() {
        var selectedRows = this.gridOptions.api.getSelectedRows();
    }

Solution

  • This is because you declared gridOptions as a variable, not as a part of this. What you can do is:

    var vm = this;
    vm.gridOptions={...}
    

    [...]

     delete() {
        var selectedRows = vm.gridOptions.api.getSelectedRows();
    }
    

    In this way you don't relate on "this", that is difficult to manage in Javascript, but you have a certain reference to the local context