PrimeNG Tutorial - Inplace Cell Editing using DataTable Component

PrimeNG Tutorial - Inplace Cell Editing using DataTable Component

Overview

In previous tutorial we had implemented PrimeNG Tutorial - Datatable Hello World Example In this tutorial we will be performing inplace cell editing for modifying the PrimeNG DataTable.

Technology Stack

We will be making use of-
  • Angular 8
  • PrimeNG

Implementation


PrimeNG DatatableProject

Develop Angular Application

  • Install angular cli using the command-
    
    npm install -g @angular/cli
    

    Install Angular CLI
  • Create new Angular Project named library-data
    
    ng new library-data
    

    New Angular CLI
  • Go inside the created the created angular project and start Angular Project-
    
    ng serve
    

    Start Angular CLI
  • Go to Angular home page

    Angular Home Page

Use PrimeNG Components

  • Install PrimeNG
    
    npm install primeng --save
    

    PrimeNG Datatable Install
  • Install Prime Icons
    
    npm install primeicons --save
    

    Prime Datatable Icons Install
  • Install Font Awesome
    
    npm install font-awesome --save
    

    Font Datatable Awesome Install
  • Install Angular CDK
    
    npm install @angular/cdk --save
    

    PrimeNG Datatable Angular CDK
  • If we now go to package.json, we will see the following primeng dependencies
    PrimeNG package dependencies
  • Open the angular.json and add the following in the styles section
    
    "./node_modules/primeicons/primeicons.css",
      "./node_modules/primeng/resources/themes/nova-light/theme.css",
      "./node_modules/primeng/resources/primeng.min.css",
    

    PrimeNG style sheet
Create a new Component named displayBooks as follows-

ng generate component book-data

PrimeNG Component
In the app-routing.module.ts add the route as books for our new Books Component.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BookDataComponent } from './book-data/book-data.component';

const routes: Routes = [
  { path: 'books', component: BookDataComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Also in the app.component.html keep only the below code and remove the remaining-

<router-outlet></router-outlet>
Start the application using-

ng serve

PrimeNG serve
If we now go to localhost:4200/books we see the following-
PrimeNG Books Component

Adding the PrimeNG DataTable Component in Angular Application

For adding any PrimeNG Component in Angular we will be following below steps-
Add PrimeNG Component
  • Add the PrimeNG Drowpdown module to the app.module.ts
    
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { BookDataComponent } from './book-data/book-data.component';
    import {TableModule} from 'primeng/table';
    
    @NgModule({
      declarations: [
        AppComponent,
        BookDataComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        TableModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    
  • We will be creating a service named BookService which will be getting the Book data by making HTTP call. Currently we will not make http call to any exposed REST service but instead get it from a JSON file named books.json which we will create in assets folder.
    The book.json will be as follows-
    
    {
        "data": [
            {"name": "The Godfather", "price": 10, "author": "Mario Puzo"},
            {"name": "The Fellowship of the Ring", "price": 15, "author": "J.R.R. Tolkien"},
            {"name": "Harry Potter and the Deathly Hallows", "price": 20, "author": "J.K. Rowling  "}        
        ]
    }
    
    Create the BookService as follows-
    
    ng generate service book
    

    PrimeNG BookService
    Add the following to the Book Service-
    
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    export interface Book {
      name;
      price;
      author;
    }
    
    @Injectable({
      providedIn: 'root'
    })
    export class BookService {
    
      constructor(private http: HttpClient) {}
    
      getBooks() {
        return this.http.get<any>('assets/books.json')
          .toPromise()
          .then(res => <Book[]>res.data)
          .then(data => { return data; });
        }
    }
    
    For making use of the httpClient we will need to add the app-module.ts
    
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { BookDataComponent } from './book-data/book-data.component';
    import {TableModule} from 'primeng/table';
    import { FormsModule } from '@angular/forms';
    import { HttpClientModule } from '@angular/common/http';
    
    @NgModule({
      declarations: [
        AppComponent,
        BookDataComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        TableModule,
        FormsModule,
        HttpClientModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    Modify the book-data component to get the backing data for the primeng datatable by calling the above created service -
    
    import { Component, OnInit } from '@angular/core';
    import { BookService, Book } from '../service/book.service';
    
    @Component({
      selector: 'app-book-data',
      templateUrl: './book-data.component.html',
      styleUrls: ['./book-data.component.css']
    })
    export class BookDataComponent implements OnInit {
    
      books: Book[];
    
      constructor(private carService: BookService) { }
    
      ngOnInit() {
          this.carService.getCarsSmall().
          then(books => this.books = books);
      }
    
      myEditInit(event): void {
        console.log('Init Even Called');
      }
     
    }
    
  • Use the p-table tag in the book-data.component.html file. Also for editing table we will be making use of p-cellEditor tag.
    
    <p-table [value]="books" (onEditInit)="myEditInit($event)" (onEditCancel)="onEditCancel($event)">
        <ng-template pTemplate="header">
            <tr>
                <th>Name</th>
                <th>Author</th>
                <th>Price</th>
            </tr>
        </ng-template>
        <ng-template pTemplate="body" let-rowData>
            <tr>
                <td pEditableColumn>
                    <p-cellEditor>
                        <ng-template pTemplate="input">
                            <input pInputText type="text" [(ngModel)]="rowData.name">
                        </ng-template>
                        <ng-template pTemplate="output">
                            {{rowData.name}}
                        </ng-template>
                    </p-cellEditor>
                </td>
                <td pEditableColumn>
                    <p-cellEditor>
                        <ng-template pTemplate="input">
                            <input pInputText type="text" [(ngModel)]="rowData.author" required>
                        </ng-template>
                        <ng-template pTemplate="output">
                            {{rowData.author}}
                        </ng-template>
                    </p-cellEditor>
                </td>
                <td pEditableColumn>
                    <p-cellEditor>
                        <ng-template pTemplate="input">
                            <input pInputText type="text" [(ngModel)]="rowData.price">
                        </ng-template>
                        <ng-template pTemplate="output">
                            {{rowData.price}}
                        </ng-template>
                    </p-cellEditor>
                </td>
            </tr>
        </ng-template>
    </p-table>
    
  • If we now go to - localhost:4200/hello we see the following-
    PrimeNG DataTable Inplace Cell Editing

Downloads-

PrimeNG DataTable Component InPlace Cell Editing Example