NashTech Insights

Implementation of Ag-Grid in Angular Application: A Comprehensive Guide

Kuldeep
Kuldeep
Table of Contents

In the world of internet improvement, growing feature-rich and interactive records tables are a common requirement for plenty of packages. Fortunately, there are various libraries and gear available to simplify this project. One such tool is AgGrid, an exceedingly customizable records grid for JavaScript/Angular applications. In this complete manual, we can stroll you through the procedure of enforcing AgGrid in an Angular utility, covering the whole lot from setup to superior features.

Angular and Ag-grid image

Introduction to Ag-Grid

AgGrid is an effective and versatile JavaScript grid library that is designed to deal with massive datasets effortlessly. It provides an extensive variety of capabilities, including sorting, filtering, cellular modifying, pagination, and more, making it a famous preference for building facts-intensive applications.

In this blog, we will stroll you through the manner of integrating AgGrid into Angular software to create a desk that presents diverse unfastened APIs for checking out. (api.publicapis.org/entries)

Setting Up an Angular Project

To get started with creating an Angular project and installing AgGrid, follow these steps:

  • Create a New Angular Project:
    • Open a terminal or command prompt.
    • Install the Angular CLI globally if you haven’t already: npm install -g @angular/cli
    • Create a new Angular project: ng new angular-ag-grid-demo
    • Navigate into the project directory: cd angular-ag-grid-demo
  • Install Ag-Grid via npm:
    • npm install ag-grid-angular ag-grid-community

With these steps, you have set up a new Angular project and installed Ag-Grid, making it available for use within your application.

Creating an Ag-Grid Component

Let’s create an Ag-Grid component called DemoTableComponent. This component will display data using Ag-Grid. Here’s the code for the component:

TS file(DemoTableComponent):
export class DemoTableComponent {

  @Input() tableRows!: any[];
  @Input() tableHeaders: ColDef[] = [];
  @ViewChild(AgGridAngular) agGrid!: AgGridAngular;
  public defaultColDef: ColDef = {
    flex: 1,
    minWidth: 20,
    sortable: true,
    filter: true,
    floatingFilter: true,
    resizable: true,
    suppressMenu: true,
    wrapHeaderText: true,
    autoHeaderHeight: true
  };
}

  • @Input Decorator: is used to receive data for tableRows and tableHeaders from parent components.
  • @ViewChild Decorator: is used to access the Ag-Grid instance with the variable agGrid.
  • Default Column Definitions:
    • flex: 1: The columns have a flexible width.
    • minWidth: 20: The minimum column width is set to 20 pixels.
    • sortable: true: Columns are sortable.
    • filter: true: Columns can have the option to be filtered.
    • floatingFilter: true: Floating filters enabled.
    • resizable: true: Columns are resizable.
    • suppressMenu: true: Context menu for columns suppressed.
    • wrapHeaderText: true: Header text deliberately wraps.
    • autoHeaderHeight: true: automatically adjusts the header height.

HTML file (DemoTableComponent)
<div class="ag-theme-alpine table-view ">
  <ag-grid-angular
    [style.height]="'565px'"
    [columnDefs]="tableHeaders"
    [defaultColDef]="defaultColDef"
    [rowData]="tableRows"
    [pagination]="tableRows.length >= 10"
    [paginationPageSize]="10"
    [suppressDragLeaveHidesColumns]="true">
  </ag-grid-angular>
</div>

  • [style.height]=”‘565px'”: Sets the height of the Ag-Grid container to 565 pixels.
  • [columnDefs]=”tableHeaders”: Binds column definitions to tableHeaders.
  • [defaultColDef]=”defaultColDef”: Binds default column definitions to defaultColDef.
  • [rowData]=”tableRows”: Binds row data to tableRows.
  • [pagination]=”tableRows.length >= 10″: Enables pagination if there are 10 or more rows.
  • [paginationPageSize]=”10″: Sets the number of rows per page to 10.
  • [suppressDragLeaveHidesColumns]=”true”: Suppresses hiding columns when dragging them out of the grid.

These features and configurations collectively allow for the creation of a dynamic and interactive data table using Ag-Grid in an Angular application.

Fetching Data Using a Service

In the context of our application, an ApiDataService is responsible for interacting with external data sources, such as APIs or databases, to gather the necessary data. By leveraging Angular’s inherent HttpClient module, the service can efficiently execute HTTP requests to fetch this data.

import { Injectable } from '@angular/core';
import {Observable} from "rxjs";
import {HttpClient} from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class ApiDataService {

  // URL to the Data Source
  private apiUrl = 'https://api.publicapis.org/entries';

  constructor(private http: HttpClient) {
  }

  getData(): Observable<any> {
    // Fetch API data using HttpClient
    return this.http.get(this.apiUrl);
  }
}

DemoTableComponent injects the ApiDataService, enabling the component to invoke the getData method and subscribe to the data stream. this.apiDataService.getData().subscribe()

Setting Up the App Component

In your Angular application, the AppComponent is responsible for loading data and configuring the Ag-Grid component. Here’s the code for the AppComponent:

import {Component, OnDestroy, OnInit} from '@angular/core';
import {ApiDataService} from "./api-data.service";
import {ColDef, ColGroupDef} from "ag-grid-community";
import {Subscription} from "rxjs";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  tableRows: any[] = [];
  tableHeaders: (ColDef | ColGroupDef)[] = [];
  isLoading = true;
  dataSubscription!: Subscription;

  constructor(private apiDataService: ApiDataService) {
  }

  ngOnInit(): void {
    this.loadData()
  }

  loadData(): void {
    this.dataSubscription = this.apiDataService.getData().subscribe((data: any) => {
      this.tableHeaders = Object.keys(data.entries[0]).map((key) => ({
        headerName: key,
        field: key,
        ...(key === 'Link' && {
          cellRenderer: (params: any) => `<a href="${params.value}" target="_blank">${params.value}</a>`,
        }),
      }));
      this.tableRows = data.entries;
      this.isLoading = false;
    });
  }

  ngOnDestroy(): void {
    if (this.dataSubscription) {
      this.dataSubscription.unsubscribe();
    }
  }
}

This piece of code demonstrates the process of obtaining information through the ApiDataService. It dynamically creates table headers, controls data display, and handles subscriptions to guarantee a user-friendly and effective interaction.

Creating the Ag-Grid in the Template

In the template of the AppComponent, you can use the app-demo-table component to display the Ag-Grid. Here’s an example of how you can include it:

<div class="container" *ngIf="!isLoading">
  <app-demo-table [tableRows]="tableRows" [tableHeaders]="tableHeaders"></app-demo-table>
</div>

Cleaning Up and Preventing Memory Leaks

Developers may inadvertently hold onto subscriptions in Angular components even after they no longer need them, potentially causing memory leaks. To avoid this, we use the ngOnDestroy lifecycle hook to unsubscribe from the data subscription. To ensure proper cleanup when the component is no longer in use, add the dataSubscription property and unsubscribe from it in the ngOnDestroy method. This helps prevent memory leaks in your Angular component.

ngOnDestroy(){
    // Unsubscribes subscription when the component is destroyed
    if (this.dataSubscription) {
      this.dataSubscription.unsubscribe();
    }
}

Testing Ag-Grid in Angular

To ensure the functionality and reliability of the DemoTableComponent and AppComponent, we can write test cases using Angular’s testing utilities. This involves creating mock services, simulating component behavior, and asserting expected outcomes. Detailed test cases can validate that we create the chart, fetch data, and manage subscriptions correctly.

To test components using the UI, you can indeed run your Angular application using ng serve and access it at localhost:4200.

This is What UI looks like:

AgGrid-Example

Conclusion

By following the steps detailed in this comprehensive guide, one has successfully integrated Ag-Grid into their Angular application. The integration at hand empowers users to generate robust and dynamic data tables, facilitating the effective administration and showcasing of extensive datasets. The utilization of Ag-Grid ensures a seamless user experience throughout the process.
In summary, Ag-Grid proves to be an indispensable tool for generating dynamic and feature-rich data tables in Angular applications. This empowers developers to effortlessly deliver impactful data presentations to their users.

Git-Hub Repository Link: Angular-ag-grid-demo

Visit Official site for more information related to AgGrid.

Kuldeep

Kuldeep

An expert-level Java Consultant with experience building large-scale, loosely coupled, state-of-the-art enterprise applications. Excellent experience in writing microservices, building integration applications, and working on SAAS-based applications. Strong focus on creating a positive working environment and gaining valuable insights.

Leave a Comment

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

Suggested Article

%d bloggers like this: