使用上下文菜单时的范围问题

jwo*_*ong 5 ag-grid ag-grid-ng2

我正在按照此处的文档向我的网格添加上下文菜单项。问题是,从 getContextMenuItems 的范围(在示例中),我无法访问组件中的任何其他方法或变量。这可能吗?下面的例子:

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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

aka*_*ash 8

您可以this在网格的上下文中添加引用-

this.gridOptions.context = {
                    thisComponent : this
                };
Run Code Online (Sandbox Code Playgroud)

然后,thisComponent可以访问如下 -

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;
}
Run Code Online (Sandbox Code Playgroud)

对于任何其他回调,如cellRenderer.


See*_*rle 5

我假设您正在谈论使用 TypeScript 的 Angular 2 或 4 组件。如果是这样,则使用粗箭头连接到您的函数。

例子:

gridOptions.getContextMenuItems = () => this.getContextMenuItems();
Run Code Online (Sandbox Code Playgroud)

这应该为您提供所需的范围。