【问题标题】:Unable to execute function in Context Menu无法在上下文菜单中执行功能
【发布时间】:2019-11-12 06:55:32
【问题描述】:

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

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 (price-factor.component.ts:162)

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

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

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

【问题讨论】:

  • 什么是 Object.action ?
  • var 结果是一个对象列表。 Action 是调用我的函数的对象中的一个键
  • 第一个版本不行,`function() {}`改变this的上下文
  • 我将如何改变上下文?
  • 你能在 stackblitz 代码中添加一个 jsfiddle 吗?我会很容易测试

标签: angular typescript ag-grid


【解决方案1】:

如果你的 html 是这样的:

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

那么函数getContextMenuItems必须写成这样:

getContextMenuItems = (params) => {
}

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

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

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

【讨论】:

  • 这是一个很好的见解。谢谢。
  • “this”关键字的超级解释,我遇到了同样的问题。谢谢
【解决方案2】:

您可以在网格的上下文中添加对 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 等任何其他回调也可以这样做。

参考:Scoping issues while using context menu

它对我有用

【讨论】:

  • 为什么你认为图标没有显示?谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 2020-02-12
相关资源
最近更新 更多