Skip to content

How to include ag grid

Chris Curnow edited this page Mar 16, 2016 · 3 revisions

###Dependencies In your package.json file, specify dependency on ag-grid AND ag-grid-ng2. The ag-grid package contains the core ag-grid engine and the ag-grid-ng2 contains the Angular 2 component.

"dependencies": {
    ...
    "ag-grid": "3.3.x",
    "ag-grid-ng2": "3.3.x"
}

The major and minor versions should match. Every time a new major or minor version of ag-Grid is released, the component will also be released. However for patch versions, the component will not be released.

Then

npm update

###Use

Now you can include ag-grid in any component:

import {AgGridNg2} from 'ag-grid-ng2/main';

....

@Component({
    directives: [AgGridNg2],
    ...
})

You can either include the CSS as imports in your main CSS file, or for prototyping add these lines to the index file:

<link href="node_modules/ag-grid/styles/ag-grid.css" rel="stylesheet" />
<link href="node_modules/ag-grid/styles/theme-fresh.css" rel="stylesheet" />

Now you are ready to use ng-grid in your app. Here's some sample code:

export class userList implements OnActivate {
    private gridOptions: GridOptions;
    private showGrid: boolean;
    private rowCount: string;
    private columnDefs: any[];
    private listData = [];

constructor()
    {
      this.gridOptions = <GridOptions>{};
      this.createColumnDefs();
      this.showGrid = true;``
      this.listData = []; // either set up listData here with dummy data or get it from a remote service
    }

onRowClicked($event) {
  let id = this.listData[row]['id'] \\presuming id is an attribute in your data
  \\ do something, ie show detail
  \\ ....
};

 createColumnDefs()  {
     this.columnDefs =[ { headerName: "User Number", field: "userNumber", width:80},
      { headerName: "User Name", field: "userName", width:150},
     { headerName: "Date of Birth", field: "dob", width:80},
     { headerName: "Department", field: "department", width:100 },
     { headerName: "Role", field: "role", width:100 }
    ]
       
  }
}

And the HTML:

<ag-grid-ng2
    class="ag-fresh"
    style="width:100%; height:800px; margin-bottom:20px;"
    [gridOptions]="gridOptions"
    [columnDefs]="columnDefs"
    [rowData]="listData"

    enableColResize
    enableSorting
    rowSelection="single"
    suppressCellSelection
    rowHeight="26"
    (rowClicked)="onRowClicked($event)">
</ag-grid-ng2>

Reference: https://ag-grid.com/best-angular-2-data-grid/index.php