Primeng datatable tutorial | Angular p-table complete example


In this blog post, We are going learn the Primeng Angular Datatable example with tutorials.

Primeng table Tutorial

Primeng Angular Tutorials with examples

Primeng Angular Tutorials with examples

Primeng is an Angular open-source framework for a collection of Rich UI libraries. Primefaces is the author of primeng framework. Please see this post for more information. In every application, there is a need to display the large data in table form from the database in the User interface.

What is the use of table components in a web application? For example, You have to write an admin interface of eCommerce UI application like amazon, As an admin of application, you have operations like CRUD operations as well as shown the data in the admin panel of your eCommerce application. So you have to use table component to have control over products like search fields, filter, showing all fields, There are three reasons to choose a table on representing data on the browser.

First All, It helps users to display paginated data when there are many records, Secondly, It provides a good experience to display than display records at once. Users are visible and easily filter records on all records. Thus, the table feature has advantages for users.

We can use either the HTML table or Custom Data table. Primeng provides an inbuilt table that provides a lot of features (Pagination, sorting, filtering.) as described below, Hence It helps developers to write lesser code instead of writing custom code.

Features

It provides rich data table UI with a lot of features.

  •   Pagination
  •   Sorting  and Filtering based on columns
  •   Grouping columns
  •   Export to PDF document
  •   Row, Column expand and group
  •   Scroll and toggle
  •   Context Menu
  •   Edit, resize and Reorder
  •   Responsive

This example works in Angular 2,4,6,7,8 and 9 versions include latest versions

Generate Angular Application with CLI

Please see my previous post about Primeng Angular application from Scratch I am listing out important steps for Angular CLI Installation and Generate Project.

Install angular CLI tool using npm command


npm install -g @angular/cli

Create Angular project -

 ng new primeng-datatable

This creates an Angular project with all default configurations and initial components with the project structure, Install all dependencies Run the project using ng serve Go to the project directory, and issue the command

 ng serve

The application starts and listens at default port 4200, Application can be accessed with http://localhost:4200.

Angular CLI Project Structure

Following is the project structure which contains all required initial components and configuration files required to run the angular project.

Angular cli project structure

Integrate primeng npm in Angular 

primeng is available as an npm package. First Install dependencies using primeng npm command Under the project directory, run the following commands This install primeng and primeicons dependencies.

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

Install Animation module which is required dependency for primeng library

npm install @angular/animations --save

angular.json style configurations 

Add primeng styles and icons in styles section of angular.json. primeng icons uses primeface icons in table.

You can check more about prime icons

"styles": [
  "../node_modules/primeicons/primeicons.css",
  "../node_modules/primeng/resources/primeng.min.css",
  "../node_modules/primeng/resources/themes/omega/theme.css",
]

App Module changes - app.module.ts Integrate BrowserAnimationsModule Many components required to have a dependency of Angular animation module

Import BrowserAnimationsModule in main app module.
import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; // added this

Next step is to import TableModule into application module to have access to all primeng table components and properties

import {TableModule} from 'primeng/table';

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

import { AppComponent } from './app.component';
import {TableModule} from 'primeng/table';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; // added this

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    TableModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Data Table Example 

We will see the basic static data binding. For example, We are displaying a list of users’ data - id, name, email. Data table requires users to object in the form of an array. Component changes

In angular component, get the data and stored under User object.

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

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

  users: User[];

  cols: any[];
  ngOnInit() {
    this.users = [
      { id: '1', name: 'kiran',email:'kiran@gmail.com' },
      { id: '2', name: 'tom',email:'tom@gmail.com' },
      { id: '3', name: 'john',email:'john@gmail.com' },
      { id: '4', name: 'Frank',email:'frank@gmail.com' },

  ];
    this.cols = [
        { field: 'id', header: 'Id' },
        { field: 'name', header: 'Name' },
        { field: 'email', header: 'Email' },
    ];
}
}

export interface User {
  id;
  name;
  email;
}

Template html changes

the user list is binding to the value property of a table. A list of cars is bound to the value property whereas header and body templates are used to define the content of these sections. Each primeng table contains the following templates. Each of these templates wrapped under ng-template. Caption is a title or caption content for a table Header -  It is a header of the table. Provide a list of columns for a table and it is equivalent of thead tag of HTML table Body - It is a body that contains actual data and it is equivalent of tbody tag of HTML table footer - Content for a footer of the table and it is equivalent of tfoot tag of HTML table summary - Display below the table with summary content. List of objects bound to value property of p-table. There are two ways we configure table columns Static  Columns In this, Every column is configured in the template of the header section

<p-table [value]="users">
    <ng-template pTemplate="caption">
        Users List
          </ng-template>
  <ng-template pTemplate="header">
      <tr>
          <th>id</th>
          <th>name</th>
          <th>Email</th>
      </tr>
  </ng-template>
  <ng-template pTemplate="body" let-user>
      <tr>
          <td>{{user.id}}</td>
          <td>{{user.name}}</td>
          <td>{{user.email}}</td>
      </tr>
  </ng-template>
</p-table>

Adding dynamic columns

Here header template is configured using an array of objects. In the component, columns array is constructed with field and header keys. Following is an example of Dynamic column binding.

<p-table [columns]="cols" [value]="users">
  <ng-template pTemplate="caption">
Users List
  </ng-template>
  <ng-template pTemplate="header" let-columns>
      <tr>
          <th *ngFor="let col of columns">
              {{col.header}}
          </th>
      </tr>
  </ng-template>
  <ng-template pTemplate="body" let-user let-columns="columns">
      <tr>
          <td *ngFor="let col of columns">
              {{user[col.field]}}
          </td>
      </tr>
  </ng-template>
</p-table>

Both of the above codes produce the same output. Data are shown in a simple and easy way.

Primeng Angular 4 Table Example

Sort column ascending

This is an example of sorting table based on columns. on Table level, add sortMode="multiple” and each column with adding attribute pSortableColumn and p-sortIcon tag.

<p-table [columns]="cols" [value]="users" sortMode="multiple">
  <ng-template pTemplate="caption">
Users List
  </ng-template>
  <ng-template pTemplate="header" let-columns>
      <tr>
          <th *ngFor="let col of columns" [pSortableColumn]="col.field">
              {{col.header}}
              <p-sortIcon [field]="col.field"></p-sortIcon>

          </th>
      </tr>
  </ng-template>
  <ng-template pTemplate="body" let-user let-columns="columns">
      <tr>
          <td *ngFor="let col of columns">
              {{user[col.field]}}
          </td>
      </tr>
  </ng-template>
</p-table>

When a column is clicked for sorting, Table level content is adjusted as per column sorting.

Primeng Angular 6 Sort Table example

Pagination example 

When there are a lot of data like 10000 rows, These data can be represented in pages. Primeng table has pagination option, You have to configure below properties paginator-true/false - Enable pagination or not. rows - Number of rows displayed on each page.

<p-table [columns]="cols" [value]="users" sortMode="multiple"  [paginator]="true" [rows]="2">

Primeng Angular Table Pagination example Filter Example Filter option is used to reduce the data from the table.

<p-table [columns]="cols" [value]="users" sortMode="multiple" #dt  >
  <ng-template pTemplate="caption">
Users List
  </ng-template>
  <ng-template pTemplate="header" let-columns>
      <tr>
          <th *ngFor="let col of columns" [pSortableColumn]="col.field">
              {{col.header}}
              <p-sortIcon [field]="col.field"></p-sortIcon>
          </th>
      </tr>
      <tr>
          <th *ngFor="let col of columns" [ngSwitch]="col.field">
              <input pInputText type="text" (input)="dt.filter($event.target.value, col.field, col.filterMatchMode)">
          </th>
      </tr>
  </ng-template>
  <ng-template pTemplate="body" let-user let-columns="columns">
      <tr>
          <td *ngFor="let col of columns">
              {{user[col.field]}}
          </td>
      </tr>
  </ng-template>
</p-table>

Primeng Angular Table Filter example

Similar Posts