Ag grid 使用关联菜单时的作用域问题
我正在按照文档将上下文菜单项添加到我的网格中。问题在于,从getContextMenuItems的范围(在本例中),我无法访问组件中的任何其他方法或变量。这可能吗?示例如下:Ag grid 使用关联菜单时的作用域问题,ag-grid,ag-grid-ng2,Ag Grid,Ag Grid Ng2,我正在按照文档将上下文菜单项添加到我的网格中。问题在于,从getContextMenuItems的范围(在本例中),我无法访问组件中的任何其他方法或变量。这可能吗?示例如下: private varIWantToAccess: boolean = false; function getContextMenuItems(params) { var result = [ { // custom item name: 'Alert ' + params.value,
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;
}
谢谢 我假设您正在谈论使用TypeScript的角度2或4组件。 如果是这样,则使用fat箭头连接到函数 例如:
gridOptions.getContextMenuItems = () => this.getContextMenuItems();
这将为您提供所需的范围。您可以在网格的上下文中添加对该
的引用-
this.gridOptions.context = {
thisComponent : this
};
然后,此组件可以按如下方式访问-
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;
}
private getContextMenuItems(参数){
控制台日志(params);
var结果=[
{//自定义项
名称:'样本',
操作:函数(){params.context.thisComponent.callMe();},
图标:“”
}];
返回结果;
}
对于任何其他回调,如cellRenderer
也可以执行相同的操作。您需要为该项提供父上下文属性。
上下文菜单项示例:
{
name: 'BreakoutReport',
action: function () {
this.context.isDrillDownData = false;
this.context.isBreakOutReport = true;
this.context.populateBreakOutGrid();
},
cssClasses: ['redFont', 'bold'],
disabled: !params.value.drillDownReport,
context: params.context
}
在这里,this.context
可以访问所有父函数。
请记住,此上下文需要先在网格选项中设置,然后才能传输到上下文菜单项
第一步:在gridOptions中设置上下文
getGridOption() {
return {
getContextMenuItems: this.getContextMenu,
context: this//pass parent context
};
}
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;
}
第二步:将上下文传递到上下文菜单子项
getGridOption() {
return {
getContextMenuItems: this.getContextMenu,
context: this//pass parent context
};
}
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;
}
这实际上与ag电网无关。类似问题:可能重复