referencing 'this' in ag-grid events

拥有回忆 提交于 2019-12-06 13:52:05

问题


In ag-grid events, e.g. onRowSelected(), 'this' refers to the grid object. However, I need to reference component variables and don't know how to. What I did was this, but it is a hack:

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

Is there a better way?


回答1:


There are 2 ways of doing this :

  1. onRowSelected: this.onRowSelected.bind(this)
    This approach is useful if your onRowSelected is tightly coupled to your component and it is meant to be used only with that grid.
  2. However if you would want to share a single function across many grids and lets say have this function in a grid utility service.
    Then you can use the below approach. In gridOptions, use the context option

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

Within onRowSelected you can access context using :
const ctx = params.context.parentComponent to reference component varibles



来源:https://stackoverflow.com/questions/53111132/referencing-this-in-ag-grid-events

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