无法在上下文菜单中执行功能

Unable to execute function in Context Menu

我正在尝试调用上下文菜单中的函数。

getContextMenuItems(params) {
    console.log(params.node.data)
    var result = [

      {
        name: "Delete",
        action : function () { 
         this.deletePriceFactor(params.node.data);
        }
        ,
        cssClasses: ["redFont", "bold"]
      },
      {
        name: "Audit"
      }

    ]
      return result;
    }

 deletePriceFactor = (rowdata)  =>{
    this.priceFactorService.deleteEntry(rowdata.exchangeCode, rowdata.productCode, rowdata.secType).subscribe(pricefactors => {
    });

  }

我一直收到错误消息: 错误类型错误:this.deletePriceFactor 不是函数 在 Object.action(价格-factor.component.ts:162)

我试过像这样使用箭头函数:

action : () =>  { 
         this.deletePriceFactor(params.node.data);
        }

以上导致另一个错误:core.js:1673 ERROR TypeError: Cannot read 属性 'deletePriceFactor' of undefined

如果您的 html 是这样的:

<ag-grid-angular
      [getContextMenuItems]="getContextMenuItems"
      .
      .
      .
    ></ag-grid-angular>

那么函数 getContextMenuItems 必须这样写:

getContextMenuItems = (params) => {
}

因此,this 关键字指向您的组件。

之后,像这样调用你的方法:

action : () => this.deletePriceFactor(params.node.data)

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

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 等任何其他回调也可以这样做。

参考:

对我有用