How To Add Ag-Grid In Angular

Hello Friends, In this article, we will discuss about how to add Ag-Grid in the Angular application. ag-Grid provides a feature to display the data in a proper grid format with filtering and sorting features already included in it and many more.

First, we need to add the AG Grid NPM packages. run the following command in the terminal.

npm install --save ag-grid-community ag-grid-angular

Now, add the AG Grid Angular module to our app module (src/app/app.module.ts):

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { AgGridModule } from 'ag-grid-angular';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AgGridModule.withComponents([])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

The next step is to add the AG Grid styles add the following code in src/styles.scss:

@import "../node_modules/ag-grid-community/dist/styles/ag-grid.css";
@import "../node_modules/ag-grid-community/dist/styles/ag-theme-alpine.css";

Next, let’s declare the grid configuration. Add following code in src/app/app.component.ts:

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

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {

    columnDefs = [
    {
      headerName: '',
      field: '',
      minWidth: 180,
      headerCheckboxSelection: true,
      checkboxSelection: true,
    },
        { field: 'make',sortable: true, filter: true  },
        { field: 'model',sortable: true, filter: true  },
        { field: 'price',sortable: true, filter: true }
    ];

    rowData = [
        { make: 'Toyota', model: 'Celica', price: 10000 },
        { make: 'Ford', model: 'Mondeo', price: 45000 },
        { make: 'Porsche', model: 'Boxter', price: 60000 }
    ];
}

Next, add the ag-grid component using the following code in app/app.component.html.

<ag-grid-angular style="width: 100%; height: 500px;" 
  class="ag-theme-alpine" 
  [rowData]="rowData"
  [columnDefs]="columnDefs" 
  [rowSelection]="'multiple'">
</ag-grid-angular>

 

Now run the application and the output looks like the following screen.

I hope this article helps you and you will like it.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories