Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scoping issues while using context menu

I'm following the docs here to add a context menu item to my grid. The issue is that from the scope of getContextMenuItems (in the example), I'm unable to access any other methods or variables in my component. Is this possible? Example below:

private varIWantToAccess: boolean = false;

function getContextMenuItems(params) {
    var result = [
    { // custom item
        name: 'Alert ' + params.value,
        action: function () 
    {
        window.alert('Alerting about ' + params.value);
        this.varIWantToAccess = true; // Builds fine, but throws a run time exception, since this "this" context is different than the one that has "varIWantToAccess"
    }
    },
        ....
        return result;
}

Thanks!

like image 634
jwong Avatar asked Mar 08 '17 19:03

jwong


2 Answers

You can add the reference to this in grid's context -

this.gridOptions.context = {
                    thisComponent : this
                };

And then, thisComponent can be access as below -

private getContextMenuItems(params) { 
    console.log(params);
    var result = [
        { // custom item
            name: 'Sample',
            action: function () {params.context.thisComponent.callMe();  },
            icon: '<i class="fa fa-pencil" />'
        }];
    return result;
}

Same can be done for any other call backs like cellRenderer.

like image 63
Akash Avatar answered Oct 24 '22 08:10

Akash


I assume that you are speaking of an Angular 2 or 4 component using TypeScript. If so then use fat arrow to connect to your function.

Example:

gridOptions.getContextMenuItems = () => this.getContextMenuItems();

This should provide you the scope you need.

like image 21
Seeschorle Avatar answered Oct 24 '22 08:10

Seeschorle