ag-grid gridOptions.api undefined in angular 2

孤街醉人 提交于 2019-11-30 19:46:53

The gridOptions api will be set and ready to use once the grid's gridReady event has been called.

At the line you're testing for it, gridOptions is just an empty Object, and even after you do this:

this.gridOptions = <GridOptions>{
     columnDefs: this.columnDefs(),
     ...other lines

It still won't have the api available - hook into the gridReady or angular's ngOnInit events and you'll be able to invoke the api safely.

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.

It's because of component lifecycles. In constructor it's not initialized yet. (I'm assuming you assigned gridOptions object to your grid properly.)

Try using it in

ngOnInit() { 
    console.log(this.gridOptions.api)
}

From the documentation

ngOnInit Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.

Get more info about lifecycles here.

Try this:

export class MyComponent implements OnInit {
  selected = () => console.log('ID: ', this.gridOptions.api.getSelectedRows()[0].id);

  gridOptions: GridOptions = {
    columnDefs: [
        {headerName: 'ID', field: 'id', width: 80},
        { ... }
    ],
    rowSelection: 'single'
  }

  ngOnInit() {
    this.gridOptions.rowData = this.gridData;
    this.gridOptions.onSelectionChanged - this.selected;
  }

It worked for me!

I was using vue.js Had same issue. But when I included :gridOptions="gridOptions" in my ag-grid-vue component that solved my problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!