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

Mar*_*rkJ 5 typescript ag-grid angular

我试图在我的上下文菜单中调用一个函数。

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 => {
    });

  }
Run Code Online (Sandbox Code Playgroud)

我不断收到错误消息:ERROR TypeError: this.deletePriceFactor is not a function at Object.action (price-factor.component.ts:162)

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

action : () =>  { 
         this.deletePriceFactor(params.node.data);
        }
Run Code Online (Sandbox Code Playgroud)

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

bub*_*les 7

如果你的 html 是这样的:

<ag-grid-angular
      [getContextMenuItems]="getContextMenuItems"
      .
      .
      .
    ></ag-grid-angular>
Run Code Online (Sandbox Code Playgroud)

那么函数getContextMenuItems必须写成:

<ag-grid-angular
      [getContextMenuItems]="getContextMenuItems"
      .
      .
      .
    ></ag-grid-angular>
Run Code Online (Sandbox Code Playgroud)

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

之后,调用您的方法,如:

getContextMenuItems = (params) => {
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个伟大的见解。谢谢。 (2认同)