Manish Kumar February 2016

How to initialize ag-grid api in angular2 application

I am working on an application built using angular2 with typescript. I am using ag-grid to display data in grid but not able to find the grid api.

/// <reference path="../../../typings/jquery/jquery.d.ts" />


import {Component} from 'angular2/core';
import {Hero, HeroService}   from './hero.service';
var gridOptions;
var heroService;
import * as core from 'angular2/core';
declare var ag: any;
ag.grid.initialiseAgGridWithAngular2({ core: core });
@Component({
    selector: 'gridapp',
    template: `<ag-grid-ng2 #gapp class="ag-fresh" style="height: 300px; width:850px" [gridOptions]="gridOptions" [columnDefs]="columnDefs" [rowData]="rowData" enableSorting="true" enableColResize="true" enableFilter="true"></ag-grid-ng2>`,
    directives: [(<any>window).ag.grid.AgGridNg2],
    providers: [HeroService]
})
export class GridViewComponent {

    private columnDefs: Object[];
    private rowData: Object[];



    constructor(private _heroService: HeroService) {
        console.log("in Grid constructor...");
        heroService = this._heroService;
        this.columnDefs = [
            { headerName: "ID", field: "id", sortingOrder: ["asc", "desc"], editable: false, width: 100 },
            { headerName: "Name", field: "name", sortingOrder: ["asc", "desc"], editable: false, hide: false },

        ];

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

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

        }


    }


}

Now when I am trying to execute any method of this.gridOptions.api it is throwing error that "gridOptions.api is undefined. Examples mentioned on ag-grid

Answers


dfsq February 2016

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

Post Status

Asked in February 2016
Viewed 1,703 times
Voted 4
Answered 1 times

Search




Leave an answer