1

I am using the ag-grid API in an Angular 2 app, inside the ngOnInit method.

In the onGridReady event like mentioned in this post, the API is accessible and things work fine.

However, I need to call the API in one of the following methods as well:

  • onRowDataChanged
  • onNewColumnsLoaded
  • onModelUpdated

This is not working because the API is undefined. In addition, for some reason I can also call the API in the onCellDoubleClicked and onCellClicked events.

This seem to be a bug. Does anyone know what is going on?

Please see the code bellow:

ngOnInit() {

    this.gridOptions = <GridOptions>{

        onGridReady: function (param) {
            param.api.sizeColumnsToFit(); // works fine
        },

        onCellDoubleClicked: function (param) {
            param.api.sizeColumnsToFit(); // works fine
        },

        onRowDataChanged: function (param) {
            param.api.sizeColumnsToFit(); // API is undefined
        },
    };
}
2

2 Answers 2

1

Alright, here is how I got it working.

  • First, capture the this reference for your angular component just to make sure that you will not have JavaScript scoping issues.

  • Then, capture the API reference when it is available inside the onGridReady event

  • Lastly, only call the API after the stack is empty, deferring all the API calls with the setTimeout function

So now the code looks more or less like this:

...
let self = this;
...
onGridReady: function (param) {
    self.api = param.api;
},

onRowDataChanged: function (param) {
    setTimeout(() => {
        self.api.sizeColumnsToFit()
        ...more API calls...
    }, 0);
},
...
Sign up to request clarification or add additional context in comments.

Comments

0

When there is an issue, ag grid will not create api properly, so api will be undefined.

In my case, there was an error in console about i forgot to import 'ag-grid-enterprise' (i was using rowModelType: 'serverSide'), so it fails to init.

So check if the options are valid and if it gives you any error on console.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.