PrimeNG Grid In angular with editing, Multiple sorting and filtering

In this post, we’ll start by looking at an example of how to use the PrimeNG DataTable component. In addition to retrieving data from the spring boot service and displaying it, it is used to display data in tabular format.

Step 1 :

Start a new Angular project by using the NPM command below.

ng new prime-grid

Step 2 :

Add the following package to your application

npm install primeng --save
npm install primeicons --save
npm i quill

Step 3

Open the angular.json file and add the following code in your style

"node_modules/primeng/resources/themes/saga-blue/theme.css",
"node_modules/primeng/resources/primeng.min.css",
"node_modules/primeicons/primeicons.css",
"node_modules/quill/dist/quill.snow.css"

Step 4

Create primeng.module.js file in your application using the following command

ng g m shared/primeng

Step 5

Open the primeng.module.ts and add the following code

import { NgModule } from '@angular/core';
import { ConfirmationService, MessageService } from 'primeng/api';
import { ButtonModule } from 'primeng/button';
import { DropdownModule } from 'primeng/dropdown';
import { InputTextModule } from 'primeng/inputtext';
import { KeyFilterModule } from 'primeng/keyfilter';
import { TableModule } from 'primeng/table';

@NgModule({
  declarations: [],
  imports: [
    TableModule,
    DropdownModule,
    ButtonModule,
    InputTextModule,
    KeyFilterModule,
  ],
  exports: [
    TableModule,
    DropdownModule,
    ButtonModule,
    InputTextModule,
    KeyFilterModule,
  ],
  providers: [MessageService, ConfirmationService],
})
export class PrimengModule { }

Step 6

Open the app.component.ts and add the following code

import { Component } from '@angular/core';
import { MessageService } from 'primeng/api';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [MessageService],
  styles: [`
      :host ::ng-deep .p-cell-editing {
          padding-top: 0 !important;
          padding-bottom: 0 !important;
      }
  `]
})
export class AppComponent {
  products: Product[] = [];

  loading: boolean = true;

  activityValues: number[] = [0, 100];

  constructor(private messageService: MessageService) { }
  cols: any[] | any;
  ngOnInit() {
    this.products = [{
      id: "1000",
      code: "f230fh0g3",
      name: "Bamboo Watch",
      description: "Product Description",
      price: 65,
    },
    {
      id: "1001",
      code: "nvklal433",
      name: "Black Watch",
      description: "Product Description",
      price: 72,
    },
    {
      id: "1002",
      code: "zz21cz3c1",
      name: "Blue Band",
      description: "Product Description",
      price: 79,
    }]
    this.cols = [
      { field: 'code', header: 'Code' },
      { field: 'name', header: 'Name' },
      { field: 'description', header: 'Description' },
      { field: 'price', header: 'Price' }
  ];
  }

  getval(val: any) {
    console.log(val)
  }
  clonedProducts: { [s: string]: Product; } = {};

  onRowReorders(val: any) {
    this.cols = val.columns;
  }
  onRowEditInit(product: Product) {
    this.clonedProducts[product.id as any] = { ...product } as any;
  }

  onRowEditSave(product: Product) {
    if (product.price as any > 0) {
      delete this.clonedProducts[product.id as any];
      this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Product is updated' });
    }
    else {
      this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Invalid Price' });
    }
  }

  onRowEditCancel(product: Product, index: number) {
    this.products[index] = this.clonedProducts[product.id as any];
    delete this.products[product.id as any];
  }
}

export interface Product {
  id?:string;
  code?:string;
  name?:string;
  description?:string;
  price?:number;
  quantity?:number;
  inventoryStatus?:string;
  category?:string;
  image?:string;
  rating?:number;
}

Step 7 :

Open the app.component.html and add the following code

<div class="card">
  <p-table [value]="products" sortMode="multiple" editMode="row" dataKey="id" [rows]="10"
    [rowsPerPageOptions]="[10, 25, 50]" [reorderableColumns]="true" [columns]="cols" sortMode="multiple"
    [paginator]="true" [resizableColumns]="true" styleClass="p-datatable-gridlines" columnResizeMode="expand" styleClass="p-datatable-gridlines" (onColReorder)="onRowReorders($event)" responsiveLayout="scroll"
    [globalFilterFields]="[
  'code',
  'name',
  'description',
  'price'
]">
    <ng-template pTemplate="header" let-columns>
      <tr>
        <th pReorderableColumn pResizableColumn  *ngFor="let col of columns" style="padding: 0;">
          <div pReorderableColumn pResizableColumn  [pSortableColumn]="col.field" style="padding: 1rem 1rem;">
            {{col.header}}
            <p-sortIcon [field]="col.field"></p-sortIcon>
          </div>
        </th>
        <th style="width:8rem">Action</th>
      </tr>
      <tr>
        <th>
          <p-columnFilter type="text" field="code"></p-columnFilter>
        </th>
        <th>
          <p-columnFilter type="text" field="name"></p-columnFilter>
        </th>
        <th>
          <p-columnFilter type="description" field="name"></p-columnFilter>
        </th>
        <th>
          <p-columnFilter type="text" field="quantity"></p-columnFilter>
        </th>
        <th>
        </th>
      </tr>
    </ng-template>
    <ng-template pTemplate="body" let-product let-editing="editing" let-ri="rowIndex">
      <tr [pEditableRow]="product">
        <td>
          <p-cellEditor>
            <ng-template pTemplate="input">
              <input pInputText type="text" [(ngModel)]="product.code">
            </ng-template>
            <ng-template pTemplate="output">
              {{product.code}}
            </ng-template>
          </p-cellEditor>
        </td>
        <td>
          <p-cellEditor>
            <ng-template pTemplate="input">
              <input pInputText type="text" [(ngModel)]="product.name" required>
            </ng-template>
            <ng-template pTemplate="output">
              {{product.name}}
            </ng-template>
          </p-cellEditor>
        </td>
        <td>
          <p-cellEditor>
            <ng-template pTemplate="input">
              <input pInputText type="text" [(ngModel)]="product.description" required>
            </ng-template>
            <ng-template pTemplate="output">
              {{product.description}}
            </ng-template>
          </p-cellEditor>
        </td>
        <td>
          <p-cellEditor>
            <ng-template pTemplate="input">
              <input pInputText type="text" [(ngModel)]="product.price">
            </ng-template>
            <ng-template pTemplate="output">
              {{product.price | currency: 'USD'}}
            </ng-template>
          </p-cellEditor>
        </td>
        <td style="text-align:center">
          <button *ngIf="!editing" pButton pRipple type="button" pInitEditableRow icon="pi pi-pencil"
            (click)="onRowEditInit(product)" class="p-button-rounded p-button-text"></button>
          <button *ngIf="editing" pButton pRipple type="button" pSaveEditableRow icon="pi pi-check"
            (click)="onRowEditSave(product)" class="p-button-rounded p-button-text p-button-success mr-2"></button>
          <button *ngIf="editing" pButton pRipple type="button" pCancelEditableRow icon="pi pi-times"
            (click)="onRowEditCancel(product, ri)" class="p-button-rounded p-button-text p-button-danger"></button>
        </td>
      </tr>
    </ng-template>
  </p-table>
</div>

Step 8 :

Run Your Application

npm start

Output:-

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories