How to initialize ag-grid api in angular2 application

风流意气都作罢 提交于 2019-12-01 08:27:05

You want to initialize gridOptions as a property of the class, not just a variable. So it should be this.gridOptions:

constructor(private _heroService: HeroService) {

    console.log("in Grid constructor...");

    this.columnDefs = [
        { headerName: "ID", field: "id", sortingOrder: ["asc", "desc"], editable: false, width: 100 },
        { headerName: "Name", field: "name", sortingOrder: ["asc", "desc"], editable: false, hide: false }
    ];

    this._heroService.getHeroes().then(heroes => this.rowData = heroes);

    this.gridOptions = {
        enableSorting: true,
        rowData: this.rowData,
        columnDefs: this.columnDefs,
        onReady: () => {
            this.gridOptions.api.sizeColumnsToFit();
            alert(this.gridOptions.api);
        }
    }
}

The above 'almost' got me there in ang 2 rc1 but I found i needed the Grid Options link in the html as well so

<ag-grid-ng2 id="mastergrid" #agGrid style="height: 100%; width:100%" class="ag-fresh"
         [gridOptions]="gridOptions" 
                [columnDefs]="columnDefs" 
                [showToolPanel]="showToolPanel" 
                [rowData]="rowData" 
                enableSorting 
                enableRangeSelection:true
                suppressRowClickSelection
                enableFilter  
                toolPanelSuppressValues 
                toolPanelSuppressGroups
                debug="false"
                draggable="false"
                rowHeight="22" 
                rowSelection='multiple'> 
        </ag-grid-ng2> 

and

ngOnInit(){
     this.gridOptions = <GridOptions>{
        onGridReady: () => {
             this.gridOptions.api.sizeColumnsToFit();
         }
     };
 }

this worked perfectly and the grid resized as the window moved. Thanks to dfsq as I would not have used the handy onGridReady either :)

In your ts file there is a gridOptions variable declared in class level. var gridOptions; But you are not assigning any value for it. So it's undefined.

Inside the constructor you are assigning a value for a gridOptions variable which is local to that method.

However the gridOptions you have bind with grid is the class level variable which is undefined. So you are getting an error. So modify the code like follows.

constructor(private _heroService: HeroService) {
    ....
    this.gridOptions = {
        enableSorting: true,
        rowData: this.rowData,
        ....
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!