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

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

问题描述:

我正在关注文档here以向我的网格添加上下文菜单项。问题是,从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; 
} 

谢谢!

+0

这是不相关的AG-电网实际。类似问题:[作为引用传递的角5/4/2方法不在作用域中](https://stackoverflow.com/questions/48557364/1417185) – Paritosh

+0

[作为引用传递的Angular 5/4/2方法的可能的副本是不在范围内](https://stackoverflow.com/questions/48557364/angular-5-4-2-method-passed-as-reference-is-not-in-scope) – Paritosh

我假设你正在讲使用TypeScript的Angular 2或4组件。 如果是这样,然后使用胖箭头连接到你的功能。

例子:

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

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

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

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

正如下面的话,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; 
} 

同样可以用于其他任何回调像cellRenderer完成。

您需要为项目提供父上下文属性。 样品上下文菜单项:

{ 名: 'BreakoutReport', 动作:功能(){ this.context.isDrillDownData = FALSE; this.context.isBreakOutReport = true; this.context.populateBreakOutGrid(); }, cssClasses:[ 'redFont', '大胆'], 禁用:params.value.drillDownReport, 方面:params.context }

这里,this.context访问所有父功能。 请记住,此上下文需要先在网格选项中设置,然后才能转移到上下文菜单项。

第一步:在gridOptions设置方面

getGridOption() { 
      return { 
       getContextMenuItems: this.getContextMenu, 
       context: this//pass parent context 
      }; 
     } 

第2步:通过上下文关联菜单子项目

getContextMenu(params) { 
    const result = [ 
     { 
      name: 'Drilldown Report', 
      action: function() { 
       this.context.populateDrillDownReport();//access parent context using this.context inside the function. 
      }, 
      cssClasses: ['redFont', 'bold'], 
      disabled: !params.value.drillDownReport, 
      context: params.context//pass parent context 
     }, 
     'separator', 
     'copy', 
     'copyWithHeaders']; 
    return result; 
}