2017-03-08 83 views
1

我正在關注文檔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

回答

0

我假設你正在講使用TypeScript的Angular 2或4組件。 如果是這樣,然後使用胖箭頭連接到你的功能。

例子:

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

這應該爲你提供你所需要的範圍。

0

可以在網格的上下文中的引用添加到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完成。

0

您需要爲項目提供父上下文屬性。 樣品上下文菜單項:

{ 名: '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; 
}