4

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?

user441058
  • 1,188
  • 1
  • 16
  • 32
  • 2
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan Nov 02 '18 at 00:19
  • Try `onRowSelected: this.onRowSelected.bind(this)`. Or define the method as an arrow function: `onRowSelected = (event: any) => { ... }`. – ConnorsFan Nov 02 '18 at 00:20
  • @ConnorsFan thanks. didn't know you could append .bind(this) in the ag-grid initialization. If you post this as an answer I'll mark it as correct. – user441058 Nov 02 '18 at 00:27
  • I suggest that you confirm the duplicate. To be honest, this question is asked several times every day. :-) – ConnorsFan Nov 02 '18 at 00:28
  • i had the same issue but in my case this was undefined... i'm not sure how this could happen!? If you takte this demo from ag-grid.com https://www.ag-grid.com/javascript-grid-drag-and-drop/# and try to `console.log(this)` in `onRowDrag(params)` you get undefined... however this thread solved my issue – denns Nov 25 '19 at 07:18

1 Answers1

11

Enumerating the various ways you could solve this problem -
1. Use of arrow function:

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

2. Use of bind() :

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.

3.Use of ag-grid context gridOption:

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

Pratik Bhat
  • 7,166
  • 2
  • 35
  • 57