1

As what has been suggested elsewhere,

setColumnDefs is not working for some ag-grids

How to initialize ag-grid api in angular2 application

I have already initialized the gridOptions in my class constructor. But when I tried to setColumnDefs, it still gave me error:

TypeError: Cannot read property 'setColumnDefs' of undefined

What else am I missing here?

export class ConfigurationComponent implements OnInit {
  constructor(
    private configurationService: ConfigurationService,
    ) 
    {
      this.gridOptions = {
        enableSorting: false,
        rowData: this.tableData,
        columnDefs: this.tableColumns,
        onGridReady: () => {
          this.gridOptions.api.sizeColumnsToFit();
          this.gridOptions.api.setColumnDefs(this.tableColumns);
          alert(this.gridOptions.api);
        }
      }
    }

  tableData: string[] = [];
  tableList: string[] = [];
  tableName: string;
  tableColumns: [{headerName: string, field: string}] = [{headerName: "", field: ""}];
  tableRecord: {};
  gridOptions: GridOptions;

  ngOnInit() {   
    this.retrieveTableList();
  }

  retrieveTableList(){
    /*blah blah*/
  }

  retrieveTableData(){
    /*blah blah*/
    this.configurationService.retrieveTableData(this.schemaFullname, this.tableName).subscribe(data => {
      /* GETTING tableColumn HERE from the service*/

      this.gridOptions.api.setColumnDefs(this.tableColumns);

    }, error => {
      console.error(error);
      this.alertService.error("Get table data error", "No table data retrieved from data source for " + this.tableName);
    })
  }
}
xzk
  • 827
  • 2
  • 18
  • 43

1 Answers1

2

As your comment says,

It works now after I added [gridOptions]="gridOptions" in html.

Do you know why it worked?

As in your code, you are defining gridOptions in your constructor. In your onGridReady function, nobody knows from where api property (and sizeColumnsToFit, etc methods) gets added.

  this.gridOptions = {
    enableSorting: false,
    rowData: this.tableData,
    columnDefs: this.tableColumns,
    onGridReady: () => {
      this.gridOptions.api.sizeColumnsToFit();
      this.gridOptions.api.setColumnDefs(this.tableColumns);
      alert(this.gridOptions.api);
    }
  }

When you add [gridOptions]="gridOptions" in your component, component uses the gridOptions object and injects other apis for you. Hence, it works afterwards.

Paritosh
  • 11,144
  • 5
  • 56
  • 74