I am trying ag-grid in angular2 with typescript, for some reasons I am not able to use the ag-grid APIs, getting undefined error.,
here is the code..,
import { AgRendererComponent } from 'ag-grid-ng2/main';
import { GridOptions, RowNode } from 'ag-grid/main';
import { GridOptionsWrapper } from 'ag-grid/main';
import { GridApi } from 'ag-grid/main';
public gridOptions: GridOptions;
constructor()
{
this.gridOptions = <GridOptions>{};
alert(this.gridOptions);
alert(this.gridOptions.api); // *** getting undefined ***
this.gridOptions = <GridOptions>{
columnDefs: this.columnDefs(),
rowData: this.rowData,
onSelectionChanged: this.onSelectionChanged,
groupSelectsChildren: true,
suppressRowClickSelection: true,
rowSelection: 'multiple',
enableColResize: true,
enableSorting: true,
rowHeight: 45}
}//constructor
Please advise, Thanks
Updated with code in comment below
onGridReady() {
console.log(this.gridOptions.api); // here it work
this.selectedRows = this.gridOptions.api.getSelectedRows();
console.log(this.selectedRows);
}
private testClick(event): void {
try {
console.log(this.gridOptions.api); // here gives error
this.selectedRows = this.gridOptions.api.getSelectedRows();
console.log(this.selectedRows); //getting error saying undefined
}
}
Two issues...
First ,as others have mentioned, initialise a reference to the grid api in onGridReady like so
onGridReady(params) {
this.gridApi = params.api;
}
Secondly, when ag-grid calls one of your provided handlers (E.g. rowClicked), this
is no longer your angular component instance, so in your testClick()
method this.gridOptions === undefined
.
To access properties of your angular component in an AgGrid Event callback you should pass this
via GridOptions.context
like this:
this.gridOptions = <GridOptions>{
context: {parentComponent: this},
...other lines
AgGrid's events (generally) return a reference to this context object in the Event params..
rowClicked(rowClicked: RowClickedEvent) {
const localGridApiRef = rowClicked.context.parentComponent.gridApi;
// do stuff with the grid api...
const selectedRows = localGridApiRef.getSelectedRows();
};
Note: I'm not sure how you used testClick()
but my rowClicked()
would be interchangeable I expect...
Note 2 - The GridApi
is actually a property of RowClickedEvent
, so while getting it via the context object as shown is superfluous, it illustrates the point that accessing properties/methods of your angular component in an ag grid event can be done via AgGridEvent
's context
property.