【问题标题】:referencing 'this' in ag-grid events在 ag-grid 事件中引用“this”
【发布时间】:2019-04-06 06:13:01
【问题描述】:

在 ag-grid 事件中,例如onRowSelected(), 'this' 指的是网格对象。但是,我需要引用组件变量并且不知道如何。我所做的是这个,但它是一个黑客:

initializeGridOptions() {
    this.gridOptions = {
      columnDefs: [
        { headerName: "Core #", field: "coreNumber", width: 100, sort: 'asc' },
      onRowSelected: this.onRowSelected,
    }
    this.gridOptions['_this'] = this;  // HACK
  }

  onRowSelected(event: any) {
    if (event.node.selected) {
      (this as any)._this.selectedNode = event.node.data;
    }
  }

有没有更好的办法?

【问题讨论】:

  • 试试onRowSelected: this.onRowSelected.bind(this)。或者将方法定义为箭头函数:onRowSelected = (event: any) => { ... }.
  • @ConnorsFan 谢谢。不知道您可以在 ag-grid 初始化中附加 .bind(this) 。如果您将此作为答案发布,我会将其标记为正确。
  • 我建议您确认重复。老实说,这个问题每天都会被问好几次。 :-)
  • 我有同样的问题,但在我的情况下这是未定义的......我不确定这怎么会发生!?如果您从 ag-grid.com ag-grid.com/javascript-grid-drag-and-drop/# 获取此演示并尝试在 onRowDrag(params) 中使用 console.log(this),您会得到未定义...但是这个线程解决了我的问题????

标签: angular ag-grid


【解决方案1】:

列举解决这个问题的各种方法 -
1、箭头函数的使用:

   onRowSelected : (event: any) => { ... }

2。 bind() 的使用:

onRowSelected: this.onRowSelected.bind(this)
如果您的 onRowSelected 紧密耦合到您的 组件,它仅用于该网格。

3.ag-grid的使用contextgridOption:

但是,如果您想在多个网格之间共享一个功能,并且假设在网格实用程序服务中拥有此功能。
然后你可以使用下面的方法。在gridOptions中,使用上下文选项

gridOptions = { context : {parentComponent: this}...}
onRowSelected: this.gridUtilityService.onRowSelected

onRowSelected 中,您可以使用 :
const ctx = params.context.parentComponent 访问上下文以引用组件变量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-12
    • 2020-03-08
    • 1970-01-01
    • 2022-12-13
    • 2021-02-09
    • 2021-11-12
    • 2018-01-16
    • 2021-03-27
    相关资源
    最近更新 更多