Unable to execute function in Context Menu

╄→尐↘猪︶ㄣ 提交于 2021-01-28 02:41:10

问题


I'm trying to call a function in my 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 => {
    });

  }

I keep getting an error: ERROR TypeError: this.deletePriceFactor is not a function at Object.action (price-factor.component.ts:162)

I have tried using arrow functions like this:

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

The above results in another error: core.js:1673 ERROR TypeError: Cannot read property 'deletePriceFactor' of undefined


回答1:


if your html is like:

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

then the function getContextMenuItems must be writen like :

getContextMenuItems = (params) => {
}

Hence, the this keyword points to your component.

After that, call your method like:

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



回答2:


You can add the reference to this in grid's context -

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

And then, thisComponent can be access as below -

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;
}

Same can be done for any other call backs like cellRenderer.

reference: Scoping issues while using context menu

Its worked for me



来源:https://stackoverflow.com/questions/56838691/unable-to-execute-function-in-context-menu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!