Friday, May 17, 2019

Data Table with sorting, pagination, row count and search


Data Table

Installation

NPM

You need to install its dependencies before getting the latest release using NPM:
npm install jquery --save
npm install datatables.net --save
npm install datatables.net-dt --save
npm install angular-datatables --save
npm install @types/jquery --save-dev
npm install @types/datatables.net --save-dev

Setup

angular.json

Add the dependencies in the scripts and styles attributes to angular.json:
"styles": [
"node_modules/datatables.net-dt/css/jquery.dataTables.css"
    ],
"scripts": [
"node_modules/jquery/dist/jquery.js",
"node_modules/datatables.net/js/jquery.dataTables.js"
     ],

NgModule

Import the DataTablesModule at the appropriate level of your app.
import { NgModule } from'@angular/core';
import { BrowserModule } from'@angular/platform-browser';
import { DataTablesModule } from'angular-datatables';
import { AppComponent } from'./app.component';

@NgModule({
declarations: [
AppComponent
  ],
imports: [
BrowserModule,
DataTablesModule
  ],
providers: [],
bootstrap: [ AppComponent ]
})
exportclassAppModule {}


Please update your tsconfig.json and add the following blocks:
 
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
    ],
"lib": [
"es2018",
"dom"
    ],
//Custom added for datatable
"paths": {
"@angular/*": [
"../node_modules/@angular/*"
      ]
    }

  }
}

 

App.component.html
<divstyle="text-align:center">
<h1>
    Welcome to {{ title }}!
</h1>
</div>

<divstyle="margin: 30px auto; width:600px;">
<tabledatatable[dtOptions]="dtOptions"class="row-border hover">
<tfoot>
<tr>
<th><inputtype="text"placeholder="Search ID"name="search-id"/></th>
<th><inputtype="text"placeholder="Search First Name"name="search-first-name"/></th>
<th><inputtype="text"placeholder="Search Last Name"name="search-last-name"/></th>
</tr>
</tfoot>
</table>
</div>

App.component.ts
import { AfterViewInit, Component, OnInit, ViewChild } from'@angular/core';
import { DataTableDirective } from'angular-datatables';

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

exportclassAppComponentimplementsOnInit, AfterViewInit {

title = 'Employee Details';

@ViewChild(DataTableDirective)

datatableElement: DataTableDirective;
dtOptions: DataTables.Settings = {};
ngOnInit(): void {
this.dtOptions = {
ajax:'assets/jsonData.json',
columns: [{
title:'ID',
data:'id'
      }, {
title:'First name',
data:'firstName'
      }, {
title:'Last name',
data:'lastName'
      }]
    };
  }

ngAfterViewInit(): void {
this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.columns().every(function () {

// Footer textbox search start
constthat = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this['value']) {
that
              .search(this['value'])
              .draw();
          }
        });
// Footer textbox search End

      });
    });
  } 
}

jsonData.json
{
"data": [
        {
"id": "01",
"firstName": "Smith",
"lastName": "KNR"
        },
        {
"id": "02",
"firstName": "Johnson",
"lastName": "ch"
        },
        {
"id": "03",
"firstName": "Williams",
"lastName": "Smith"
        },
        {
"id": "04",
"firstName": "Jones",
"lastName": "Abhraham"
        },
        {
"id": "05",
"firstName": "Brown",
"lastName": "Antony"
        },
        {
"id": "06",
"firstName": "Wood",
"lastName": "KVSC"
        },
        {
"id": "07",
"firstName": "Davis",
"lastName": "Bincy"
        },
        {
"id": "08",
"firstName": "Miller",
"lastName": "Wilson"
        },
        {
"id": "09",
"firstName": "Wilson",
"lastName": "Wilson"
        },
        {
"id": "10",
"firstName": "Wood",
"lastName": "KVSC"
        },
        {
"id": "11",
"firstName": "Barnes",
"lastName": "Barnes"
        },
        {
"id": "12",
"firstName": "Henderson",
"lastName": "Henderson"
        },
        {
"id": "13",
"firstName": "Coleman",
"lastName": "Nag"
        },
        {
"id": "14",
"firstName": "Jenkins",
"lastName": "Jenkins"
        },
        {
"id": "15",
"firstName": "Perry",
"lastName": "Perry"
        },
        {
"id": "16",
"firstName": "Powell",
"lastName": "Powell"
        }
    ]
}

Output


























Monday, May 13, 2019

Parallel Service

Parallel Service
-------------------

ng g s services/hello

ng g s services/customers

ng g c components/parallel


services/hello.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from "rxjs/observable";
@
Injectable()
export
class HelloService {
  constructor(private _http: Http) { }  public getThnikSterData() {
    return this._http.get("http://test-routes.herokuapp.com/test/hello")
      .map((res: Response) => {
        return res.json();
      }).catch(this._handleError);
  }

  public _handleError(err) {
    console.error("Error Raised...." + err);
    return Observable.throw(err || "Internal Server Error !");
  }

}


If you get error in Observable Please install  npm install --save rxjs-compat@6

List of Observable (or) rxjs fixed error :

  1. npm install rxjs-compat
  2. npm install --save rxjs-compat@6
  3. npm install --save rxjs-compat@6.0.0 --save

note:- If you have error in rxjs & Observable once install above npm rxjs and Observable will fixed error. but not show Observable once will restart Visual Code it will fixed.


services/customers.service.ts
import { Injectable } from '@angular/core'; import{Http, Response} from '@angular/http'; import 'rxjs/Rx';
import {Observable } from "rxjs/observable";

@Injectable()
export class CustomersService {   constructor(private _http:Http) { }   public getCustomers(){     return this._http.get("https://www.w3schools.com/angular/customers.php")     .map((res:Response)=>{       return res.json();     }).catch(this._handleError);   }
  public _handleError(err){     console.error("Error Raised..."+err);     return Observable.throw(err || "Internal Error!");   }
}


components/parallel.component.ts
import { Component, OnInit } from '@angular/core';
import { HelloService } from "../../services/hello.service";
import { CustomersService } from "../../services/customers.service";
import { Observable } from "rxjs/Observable";
import { HttpErrorResponse } from "@angular/common/http";

@Component({
  selector: 'app-parallel',
  templateUrl: './parallel.component.html',
  styleUrls: ['./parallel.component.css']
})

export class ParallelComponent implements OnInit {
  private result_one: any;
  private result_two: any;

  constructor(private _service_one:HelloService,
              private _service_two:CustomersService) { }

  ngOnInit() {
    Observable.forkJoin([this._service_one.getThnikSterData(),
                         this._service_two.getCustomers()])

                         .subscribe(res=>{
                           this._service_one=res[0];
                           this._service_two=res[1]
                         },(err:HttpErrorResponse)=>{
                           if(err.error instanceof Error){
                            console.log("Client Side Error !");
                           }else{
                             console.log("Server side Error !");
                           }
                         });
  }
}

components/parallel.component.html

<h4 style="color: blueviolet">{{result_one | json}}</h4>
<h4>{{result_two | json}}</h4>


index.html
<app-parallel></app-parallel>


app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ParallelComponent } from './components/parallel/parallel.component';

import { HelloService } from "./services/hello.service";
import { CustomersService } from "./services/customers.service";

import { HttpModule } from "@angular/http";
@NgModule({
  declarations: [
    AppComponent,
    ParallelComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [HelloService, CustomersService],
  bootstrap: [ParallelComponent]
})
export class AppModule { }



OUTPUT