Open In App

Angular PrimeNG Table Performance Tips

Last Updated : 23 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Angular PrimeNG Table is a powerful component that allows developers to create and display data in a tabular format with lots of useful features like pagination, sorting, filtering, and more. It is built on top of the Angular framework and uses the PrimeNG library for its UI components. It is highly customizable and allows developers to create tables with different styles and layout options.

In this article, we will discuss some tips and best practices for optimizing the performance of the PrimeNG Table component in Angular applications. By following the below guidelines, we can ensure that your Table performs smoothly and efficiently, even when dealing with large datasets.

Syntax:

<p-table 
   [value]="...">
   <ng-template pTemplate="header">
   ...
    </ng-template>
    <ng-template pTemplate="body" let-people>
   ...
   </ng-template>
</p-table>

Creating Angular application & Module Installation:

Step 1: First, make sure that you have the latest version of Node.js and Angular CLI installed on your system. If you don’t have them already, you can install them by running the following command:

npm install -g @angular/cli

Step 2: Next, create a new Angular project by running the following command:

ng new my-project

Step 3: Once the project is created, navigate to the project directory by running the following command:

cd my-project

Step 4: Now, install PrimeNG by running the following command:

npm install primeng --save
npm install primeicons --save

Step 5: After installing PrimeNG, you need to import the Table module in your Angular project. To do this, open the src/app/app.module.ts file and add the following line:

import { TableModule } from 'primeng/table';

This line imports the Table module from the PrimeNG library.

Step 6: Next, add the TableModule to the imports array of the AppModule:

@NgModule({
 imports: [
   // other imports
   TableModule
 ],
 // other properties
})
export class AppModule { }

Project Structure: It would look something like this:

 

Here, we have created a project that will display a table using the PrimeNG library. The table loads data from a JSON file and uses pagination to display the data on pages. The JSON file contains a dataset of records, each with an ID, name, age, and state. The table displays these records in separate columns, with each row representing a single record. In order to optimize the performance of the table, we will use the following components:

  • Pagination: By displaying the data in pages, the table only loads a small portion of the data at a time, which will reduce the memory and processing requirements and improve the performance of the table.
  • Lazy loading: The data is loaded from the JSON file asynchronously, using the HttpClient service. This will allow the table to load the data in the background, without blocking the main thread or affecting the performance of the application.
  • Data filtering: The table includes a search box that allows the user to filter the data by name, age, or country. This reduces the amount of data that needs to be displayed and improves the performance of the table.
  • Responsive design: The table adjusts its layout and display options based on the size of the screen so that it looks good and is easy to use on devices of different sizes.
  • Customization: The table allows the user to customize the appearance and behavior of the table, such as the number of rows displayed per page, the colors and styles of the table cells, and the way the data is formatted and displayed.

By using these performance-optimizing components & methods, the table will be able to efficiently display and manipulate large datasets, while maintaining good performance and responsiveness.

There are a few data attributes that also impact the performance of the Table in Angular PrimeNG:

  • dataKey: This property helps to identify the record uniquely from the dataset. It is of string type & the default value is null. Here, this property helps to enable the selection by avoiding deep checking while comparing objects.
  • rowTrackBy: This property helps to optimize & avoid unnecessary DOM operations by delegating to ngForTrackBy, & uses the default algorithm to verify the identity of an object. It is of function type & the default value is null.

Example 1: In this example, we have created the Table that loads data from a JSON using a Lazy loading file and uses pagination to display the data in pages.

  • data.json: Create a random dataset

XML




[
    {
        "id": 1,
        "name": "Rajesh Kumar",
        "age": 30,
        "state": "Delhi"
    },
    {
        "id": 2,
        "name": "Priya Sharma",
        "age": 25,
        "state": "Maharashtra"
    },
    {
        "id": 3,
        "name": "Amit Singh",
        "age": 35,
        "state": "Karnataka"
    },
    {
        "id": 4,
        "name": "Ravi Choudhary",
        "age": 28,
        "state": "Tamil Nadu"
    },
    {
        "id": 5,
        "name": "Sonia Roy",
        "age": 32,
        "state": "West Bengal"
    },
]


  • app.module.ts

Javascript




import { AppRoutingModule } 
    from "./app-routing.module";
import { BrowserModule } 
    from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { TableModule } from "primeng/table";
import { HttpClientModule } 
    from "@angular/common/http";
import { AppComponent } from "./app.component";
import { DataService } from "./data.service";
import { PaginatorModule } from "primeng/paginator";
  
@NgModule({
    declarations: [AppComponent],
    imports: [
        BrowserModule,
        TableModule,
        HttpClientModule,
        PaginatorModule,
        AppRoutingModule
    ],
    providers: [DataService],
    bootstrap: [AppComponent]
})
export class AppModule { }


  • data.service.ts: Create a service to load the data from the JSON file

Javascript




import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
  
@Injectable({
    providedIn: 'root'
})
export class DataService {
  
    constructor(private http: HttpClient) { }
  
    getData() {
        return this.http.get('/assets/data.json');
    }
}


This file defines the DataService service, which has a single method getData that loads the data from the data.json file using the HttpClient service. Make sure that the DataService is correctly imported in your app.component.ts file and that you have added it to the providers array in the AppModule.

  • app.component.html

HTML




<h2 style="color: green;">
    GeeksforGeeks
</h2>
<h4>
    Angular PrimeNG Table Performance Tips
</h4>
<p-table [value]="data" 
         [paginator]="true" 
         [rows]="10" 
         [showCurrentPageReport]="true" 
         currentPageReportTemplate=
        "Showing {first} to {last} of {totalRecords} entries">
    <ng-template pTemplate="header">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
            <th>State</th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowData>
        <tr>
            <td>{{rowData.id}}</td>
            <td>{{rowData.name}}</td>
            <td>{{rowData.age}}</td>
            <td>{{rowData.state}}</td>
        </tr>
    </ng-template>
</p-table>


This file defines the template for the AppComponent component. It includes a p-table element from the PrimeNG library, which displays a table with pagination. The value attribute specifies the data to be displayed in the table, and the paginator attribute enables pagination. The rows attribute specifies the number of rows to be displayed per page.

The ng-template elements with the pTemplate attributes define the templates for the table header, body, and paginator. The let-rowData and let-paginator variables allow you to access the current row data and paginator instance in the templates.

  • app.component.ts

Javascript




import { Component, OnInit } from "@angular/core";
import { DataService } from "./data.service";
  
@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
    data: any[];
    totalRecords: number = 0;
    title: any;
  
    constructor(private dataService: DataService) {
        this.data = [];
    }
  
    ngOnInit() {
        this.dataService.getData().subscribe((data) => {
            this.data = Object.values(data);
            this.totalRecords = this.data.length;
            console.log(this.data);
        });
    }
}


The app.component.ts file is the main component of the Angular application. It is responsible for displaying the data in the PrimeNG table and handling pagination. The component has a single property, data, which is an array of objects representing the rows of the table. It also has a totalRecords property, which is the total number of records in the table. These properties are populated with data from the data.service when the component is initialized.

The component also has a constructor that injects an instance of the data.service so that it can be used to load the data from the JSON file. In the ngOnInit lifecycle hook, the component subscribes to the getData method of the data.service and sets the data and totalRecords properties with the returned data.

  • app-routing.module.ts: Module file that defines the routes for your Angular application. A route is a URL path that maps to a component. When the user navigates to a specific route, the corresponding component is displayed. This allows you to create a multi-page application with a single-page application (SPA) experience, where the user can navigate to different pages without reloading the entire application.

Javascript




import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
  
const routes: Routes = [];
  
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }


  • angular-cli.json: For the theme of the table, we can use the default luna-blue theme, for making changes in the theme you need to make changes here:
{
...
"styles": [
       "./node_modules/primeng/resources/primeng.min.css",
       "./node_modules/primeng/resources/themes/luna-blue/theme.css",
       "./node_modules/primeng/resources/primeng.min.css"
     ],
 ...
}

Output:

 

Reference: https://primefaces.org/primeng/table



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads