Wednesday, August 29, 2018

Primeng - Angular Datatable Tutorial with example

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

Primeng Tutorial

Primeng Angular Tutorials with examples

Primeng is an Angular open source framework for a collection of Rich UI libraries. It was developed by Primefaces. Please see this post for more information. In every application, There is a requirement to display the large data in table form from database in the User interface.
We can use either Html table or Custom Data table. Html table is used for lesser data and  We need to write custom code implementation for extra features like pagination, sorting, filtering.

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 Angular2, 4,5,6 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 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 project structure which contains all required initial components and configuration files required to run the angular project.
Angular cli project structure





























Integration primeng with Angular 

primeng is available as npm package. First Install primeng dependencies. Under the project directory, run the following commands This install primeng and font-awesome dependencies.
npm install primeng font-awesome
Install Animation module which is required dependency for primeng library
npm install @angular/animations --save

angular.json style configurations 

Add primeng styles and font-awesome styles in styles section of angular.json
"styles": [
  "../node_modules/font-awesome/css/font-awesome.min.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 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.
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 following templates. Each of this 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>

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 Example 

This is an example for 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

Related article


EmoticonEmoticon