Implementing ag-Grid in Angular 2

Reading Time: 4 minutes

What is ag-Grid?

ag-Grid is a JavaScript Data Grid for Building Enterprise Web Applications. It is one of the most widely used grid. It provides features like sorting, filtering, selection, re-sizing and many more.

Here’s an inspiring article of how ag-grid was developed.

Prerequisite :

To understand how to implement ag-Grid in your Angular 2 application, you need to have a basic knowledge of Angular 2 and typescript.

Following are the documentations that you can refer :

  1.  Angular 2
  2. Typescript

So, LET’S BEGIN !!!

Follow these steps to set up ag-Grid in your Angular 2 application :

Step 1 :

First of all, you need to add dependencies to your project. In your package.json, add the following code :

"dependencies": {
 ...
 "ag-grid": "6.1.0",
 "ag-grid-ng2": "6.1.0"
 }

Make sure to have the latest version of ag-Grid.

Step 2 :

Update System.config.js to use ag-grid in your project.

System.config({
 packages: {
  ...
  'ag-grid-ng2': {
    defaultExtension: "js"
   },
  'ag-grid': {
    defaultExtension: "js"
  }
 },
 map: {
  ...
  'ag-grid-ng2': 'node_modules/ag-grid-ng2',
  'ag-grid': 'node_modules/ag-grid'
 }
});

Step 3 :

Import AgGridModule in the Module where you want to use it.

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

@NgModule({
 imports: [
 BrowserModule,
 AgGridModule.forRoot(),
 ...
})

forRoot part is to ensure that the providers of AgGrid are injected at the root level.

Step 4:

And, the last thing is to include the CSS for ag-Grid. You can do it directly in your index.html

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

That’s it. The setup is complete.

Let’s move on to the implementation

Create a component where you want to use your grid.

@Component({
 selector: 'ag-grid',
 template: `
 <ag-grid-ng2 style="width: 80%; margin-left: 10%" #agGrid class="ag-material"
  [gridOptions]="myGridOptions">
 </ag-grid-ng2>`
})

export class MyGridComponent{ }

In the template, we have <ag-grid-ng2> tag. This is provided by the AgGridModule we imported before. The thing to notice is the “gridOptions” property, we have assigned it to a variable named “myGridOptions”, and therefore we need to initialize that variable in the component. Add the following code in the component :

    private myGridOptions: GridOptions = {};

This initializes an empty grid. Now, obviously, we need some data in our grid.

To add date to an ag-Grid, we have two properties of GridOptions:

  1. rowData
  2. columnDefs

we can initialize both of them on ngOninit. Import OnInit and implement it to the component, and add the following code :

import { OnInit } from '@angular/core';

export class MyGridComponent implements OnInit{

ngOnInit() {
 this.myGridOptions.rowData = this.createRowData();
 this.myGridOptions.columnDefs = this.createColumnDefs();
}

private createColumnDefs() {
 return [
  {headerName: "NAME", field: "name", width: 100}, 
  {headerName: "AGE", field: "age", width: 100},
  {headerName: "GENDER", field: "gender", width: 100}
  ]
}

//data gets mapped to the corresponding "field" key of the headers

private createRowData() {          
 return [
  {name: "Geller", age: 30, gender: "Male"},
  {name: "Geller", age: 28, gender: "Female"},
  {name: "Tribbiani", age: 29, gender: "Male"},
  {name: "Bing", age: 30, gender: "Male"},
  {name: "Green", age: 28, gender: "Female"},
  {name: "Buffay", age: 29, gender: "Female"}
  ];
 }
}

Here we have two methods that add the headers and row data into the grid.

This is how your grid should look like :

blog1_1

We are using the material theme, but you can choose whichever one you like from here.

Now, in a general scenario, you’ll be getting this data from a service. Let’s create a mock service for that. But before doing that, we should create a type for our data.

Create a file “friends.ts”, and create a class Friends as follows :

export class Friends{
  name: string;
  age: number;
  gender: string;
}

Now, for the mock service, create a file friends.service.ts, and add the following code :

import {Friends} from "./friends";
export class FriendsService{

  getDate() {
    let friends: Friends[] = [
      {name: "Geller", age: 30, gender: "Male"},
      {name: "Geller", age: 28, gender: "Female"},
      {name: "Tribbiani", age: 29, gender: "Male"},
      {name: "Bing", age: 30, gender: "Male"},
      {name: "Green", age: 28, gender: "Female"},
      {name: "Buffay", age: 29, gender: "Female"},
    ];
    return friends
  }
}

To use the service, add it to the providers section of your ngModule.

Now, we need to update our methods in the component. Rows will directly get mapped, because rowData property needs an array of any type, so all we need to do is update the createColumnDefs method.

constructor(private friendsService: FriendsService){}

ngOnInit() {
 let data: Friends[] = this.friendsService.getDate();
 this.myGridOptions.rowData = data;
 this.myGridOptions.columnDefs = this.createColumnDefs(data[0]);
}

private createColumnDefs(friends: Friends) {
 let keyNames = Object.keys(friends);
 let headers = [];
 keyNames.map(key => {
 headers.push({
 headerName: key.toUpperCase(),
 field: key,
 width: 100
 })
 });

 return headers;
}

We simply extract the keys from the data, add properties like width and field, and push it into an array.

Here’s the example project that you can refer to.

So that’s it. Now you can implement ag-Grid in your Angular 2 application. To use more features provided by ag-Grid, refer the documentation here.

KNOLDUS-advt-sticker

Written by 

Principal Architect at Knoldus Inc

21 thoughts on “Implementing ag-Grid in Angular 24 min read

  1. wow – that’s excellent. thank you for spending the time on putting the above together. did you notice in the recent release of ag-Grid you can also use HTML markup to defined your columns? personally i prefer the javascript way that you have – but people can have their own favorites.

    1. First of all, thank you for the appreciation.
      I just looked it up, it’s a pretty cool feature. I too prefer the java script way, but actually, this will come in handy for the project that I’m working on right now.

  2. I tried following the above steps.. When I tried to run the application.. It throws an error saying that.. Aggridcomponent factory class has no exported member called ‘Runtime Compiler’. Can you please help me if I am missing anything.

    1. Can you confirm that you have ag-grid-ng2 folder in node_modules? Is it a possibility that you forgot to run “npm install” after adding dependency?

  3. I keep getting the error below. Does anyone have any idea about this?

    EXCEPTION: Uncaught (in promise): Error: Error in ./TestComponent class TestComponent – inline template:5:0 caused by: No provider for BaseComponentFactory!
    Error: Error in ./TestComponent class TestComponent – inline template:5:0 caused by: No provider for BaseComponentFactory!
    at ViewWrappedError.ZoneAwareError (http://localhost:4200/polyfills.bundle.js:3323:33)
    at ViewWrappedError.BaseError [as constructor] (http://localhost:4200/vendor.bundle.js:41262:16)
    at ViewWrappedError.WrappedError [as constructor] (http://localhost:4200/vendor.bundle.js:41327:16)
    at new ViewWrappedError (http://localhost:4200/vendor.bundle.js:75970:16)
    at CompiledTemplate.proxyViewClass.DebugAppView._rethrowWithContext (http://localhost:4200/vendor.bundle.js:104406:23)
    at CompiledTemplate.proxyViewClass.DebugAppView.create (http://localhost:4200/vendor.bundle.js:104306:18)
    at CompiledTemplate.proxyViewClass.View_TestComponent_Host0.createInternal (/AppModule/TestComponent/host.ngfactory.js:16:19)
    at CompiledTemplate.proxyViewClass.AppView.createHostView (http://localhost:4200/vendor.bundle.js:103864:21)
    at CompiledTemplate.proxyViewClass.DebugAppView.createHostView (http://localhost:4200/vendor.bundle.js:104320:52)
    at ComponentFactory.create (http://localhost:4200/vendor.bundle.js:57205:25)
    at ViewContainerRef_.createComponent (http://localhost:4200/vendor.bundle.js:76617:62)
    at RouterOutlet.activate (http://localhost:4200/vendor.bundle.js:82404:40)
    at ActivateRoutes.placeComponentIntoOutlet (http://localhost:4200/vendor.bundle.js:35877:16)
    at ActivateRoutes.activateRoutes (http://localhost:4200/vendor.bundle.js:35844:26)
    at http://localhost:4200/vendor.bundle.js:35780:58

  4. Hi,

    I am trying to use ag-grid, ag-grid-ng2

    I am getting the below error while run “npm install”

    npm WARN ag-grid-ng2@6.1.0 requires a peer of @angular/core@2.x but none was installed.
    npm WARN ag-grid-ng2@6.1.0 requires a peer of @angular/compiler@2.x but none was installed.
    npm WARN angular2@2.0.0-beta.21 requires a peer of es6-shim@^0.35.0 but none was installed.
    npm WARN angular2@2.0.0-beta.21 requires a peer of reflect-metadata@0.1.2 but none was installed.
    npm WARN angular2@2.0.0-beta.21 requires a peer of rxjs@5.0.0-beta.6 but none was installed.
    npm WARN angular2@2.0.0-beta.21 requires a peer of zone.js@^0.6.12 but none was installed.

    Then when i run “npm start” getting below error

    node_modules/ag-grid-ng2/lib/agComponentFactory.d.ts(3,10): error TS2305: “” has no exported member ‘RuntimeCompiler’

    Does any one have idea..? Please share ..

    Thanks in Advance!!!

Comments are closed.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading