0

Can anyone explain why this.agGrid is undefined in the ngOnChanges method? It is being set in onGridReady which is executed before the ngOnChanges method.

In my component.ts file

  private onGridReady(agGrid) {
    this.agGrid = agGrid  // set property
    console.log(1, this.agGrid)

  }
  ngOnChanges(changed) {
    console.log(2, this.agGrid)  // property undefined
  }

console output:

1 Object { type: "gridReady", api: {…}, columnApi: {…} }
2 undefined

Any idea why this.agGrid is not defined in ngOnChanges?

Edit (showing how onGridReady is called):

html

<ag-grid-angular
    class="ag-theme-balham"
    style="width: 100%; height: 100%;"
    [gridOptions]="gridOptions">
</ag-grid-angular>

more of the ts file

  private createGridOptions() {
    const gridOptions = {};
    gridOptions['onGridReady'] = this.onGridReady;
    return gridOptions;
  }
  ngOnInit() {
    this.gridOptions = this.createGridOptions();
  }
user2263572
  • 5,435
  • 5
  • 35
  • 57

1 Answers1

1

You are assigning the function directly. This is effectively the same as calling onGridReady inside a function() { }. Inside a function() { }, the keyword this refers to the function itself.

You are not updating the agGrid property on the component - you are setting a property on the function itself.

If you want to refer to the outer scope - the component in this case - you should use an arrow function.

gridOptions['onGridReady'] = (agGrid) => this.onGridReady(agGrid);

DEMO: https://stackblitz.com/edit/angular-ay79o3

In this demo, button 1 will never set the name property on the component due to how it is called. Button 2 will set the name property on the component because it is called inside an arrow function.

Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40