Search code examples
angularag-gridag-grid-angular

ag-grid tabToNextCell Implementation


I'm having trouble using tabToNextCell with ag-grid in Angular. I'm wanting to add a new row when someone tabs to the end of the table. I am set up as follows:

<ag-grid-angular
  [columnDefs]="columnDefs"
  [rowData]="bidders$ | async"
  [tabToNextCell]="onTab"
  [stopEditingWhenCellsLoseFocus]="true"
  class="ag-theme-alpine"
  domLayout='autoHeight'
  style="width: 100%;"
>
</ag-grid-angular>

And in my component, onTab and addBidder look like this:

  onTab({nextCellPosition, previousCellPosition}: TabToNextCellParams): CellPosition {
    if(!nextCellPosition) {
      this.addBidder()
      return previousCellPosition;
    }
    return nextCellPosition;
  }

  addBidder() {
    this.biddersService.addBidder();
  }

However, when I tab to the end and trigger the call to this.addBidder(), this is undefined and I get the following error:

ERROR TypeError: Cannot read properties of undefined (reading 'addBidder')

If I put in a breakpoint where it calls this.addBidder(), and inspect things, this is undefined at that point. So, I feel like there's some sort of trick to how the onTab function should be constructed.

Also, I tried passing the addBidder() method to the onTab() method in the [tabToNextCell] assignment and that doesn't work either:

Template:

<ag-grid-angular
  [columnDefs]="columnDefs"
  [rowData]="bidders$ | async"
  [tabToNextCell]="onTab(addBidder)"
  [stopEditingWhenCellsLoseFocus]="true"
  class="ag-theme-alpine"
  domLayout='autoHeight'
  style="width: 100%;"
>
</ag-grid-angular> 

And in the component, I changed onTab to the following:

  onTab(func: any) {
    return ({nextCellPosition, previousCellPosition}: TabToNextCellParams): CellPosition => {
      if (!nextCellPosition) {
        func();
        return previousCellPosition;
      }
      return nextCellPosition;
    };
  }

However, this is undefined when calling this.biddersService.addBidder() inside of the addBidder() method within the component.


Solution

  • OK...after struggling with this for too long, I realized I could make onTab an arrow function and that would handle the this problem:

      onTab = ({nextCellPosition, previousCellPosition}: TabToNextCellParams): CellPosition => {
        if (!nextCellPosition) {
          this.addBidder();
          return previousCellPosition;
        }
        return nextCellPosition;
      };
    

    Defining OnTab as above works!