setColumnDefs在Angular 5

时间:2018-05-07 08:57:58

标签: javascript angular ag-grid

正如其他地方所建议的那样,

setColumnDefs is not working for some ag-grids

How to initialize ag-grid api in angular2 application

我已经在类构造函数中初始化了gridOptions。但是当我尝试setColumnDefs时,它仍然给了我错误:

TypeError:无法读取未定义

的属性'setColumnDefs'

我还缺少什么?

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);
    })
  }
}

1 个答案:

答案 0 :(得分:1)

正如你的评论所说,

  

现在我在html中添加[gridOptions] =“gridOptions”后就可以了。

你知道它为什么有效吗?

在代码中,您在构造函数中定义gridOptions。在onGridReady函数中,没有人知道api属性(以及sizeColumnsToFit等方法)的添加位置。

  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);
    }
  }

在组件中添加[gridOptions]="gridOptions"时,组件会使用gridOptions对象并为您注入其他apis。因此,它之后起作用。