Saturday 29 December 2018

CURD operation using angularjs6 , datatable & webapi2




Webapi Code :

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication5.Models;

namespace WebApplication5.Controllers
{
    [RoutePrefix("api/Bbsrservices")]
    public class BbsrservicesController : ApiController
    {
        [HttpGet]
        [Route("Bbsrs")]
        public HttpResponseMessage Bbsrs()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.BBSRs.ToList());
                }
            }
            catch(Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpGet]
        [Route("Bbsr/{BID:int}" ,Name ="Bbsr")]
        public HttpResponseMessage Bbsrs(int BID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    BBSRVM vm = obj.BBSRs.Select(m => new BBSRVM { BID = m.BID, NAME = m.NAME }).FirstOrDefault(p => p.BID == BID);
                    vm.CLIST = obj.CTCs.Where(e => e.BID == BID).ToList();
                    return Request.CreateResponse(HttpStatusCode.OK, vm);
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpPost]
        [Route("Save")]
        public HttpResponseMessage Save(BBSRVM vm)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    BBSR bbsr = new BBSR();
                    bbsr.BID = vm.BID;
                    bbsr.NAME = vm.NAME;
                    obj.Entry(bbsr).State = EntityState.Added;
                    obj.SaveChanges();
                    obj.CTCs.AddRange(vm.CLIST.Select(p => new CTC { NAME = p.NAME, GENDER = p.GENDER, MSTATUS = p.MSTATUS, BID = vm.BID }));
                    obj.SaveChanges();
                    var req = Request.CreateResponse(HttpStatusCode.Created, "Data Saved.");
                    req.Headers.Location = new Uri(Url.Link("Bbsr", new { BID = vm.BID }));
                    return req;
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpPut]
        [Route("Update/{BID:int}")]
        public HttpResponseMessage Update([FromUri]int BID,[FromBody]BBSRVM vm)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    BBSR bbsr = obj.BBSRs.Find(BID);
                    bbsr.NAME = vm.NAME;
                    obj.Entry(bbsr).State = EntityState.Modified;
                    obj.SaveChanges();
                    obj.CTCs.RemoveRange(obj.CTCs.Where(e => e.BID == BID));
                    obj.SaveChanges();
                    obj.CTCs.AddRange(vm.CLIST.Select(p => new CTC { NAME = p.NAME, GENDER = p.GENDER, MSTATUS = p.MSTATUS, BID = p.BID }));
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Updated.");
                    
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [HttpDelete]
        [Route("Delete/{BID:int}")]
        public HttpResponseMessage Delete([FromUri]int BID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    BBSR bbsr = obj.BBSRs.Find(BID);
                    obj.Entry(bbsr).State = EntityState.Deleted;
                    obj.SaveChanges();
                    obj.CTCs.RemoveRange(obj.CTCs.Where(e => e.BID == BID));
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Deleted.");

                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }

    }
}


Angular Model :

export interface Ibbsr {
    BID: number;
    NAME: string;
    CLIST: Ictc[];
}

export interface Ictc {
    CID: number;
    NAME: string;
    GENDER: string;
    MSTATUS: string;
    BID: number;
}


Angularjs Service :

import { Injectable } from '@angular/core' ;
import { HttpClient, HttpHeaders } from '@angular/common/http' ;
import { Ibbsr } from './bbsr.model';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class BbsrService {
    baseUrl = 'http://localhost:2813/api/Bbsrservices';
    constructor(private http: HttpClient) { }

    Save(bbsr: Ibbsr): Promise<string> {
        return this.http.post<string>(`${this.baseUrl}/${'Save'}`
    , JSON.stringify(bbsr)
     , {headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
     .toPromise();
    }
    Update(bbsr: Ibbsr): Promise<string> {
        return this.http.put<string>(`${this.baseUrl}/${'Update'}/${bbsr.BID}`
    , JSON.stringify(bbsr)
     , {headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
     .toPromise();
    }
    Delete(bid: number): Promise<string> {
        return this.http.delete<string>(`${this.baseUrl}/${'Delete'}/${bid}`
     , {headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
     .toPromise();
    }
    Get(bid: number): Promise<Ibbsr> {
        return this.http.get<Ibbsr>(`${this.baseUrl}/${'Bbsr'}/${bid}`)
     .toPromise();
    }
    Gets(): Promise<Ibbsr[]> {
        return this.http.get<Ibbsr[]>(`${this.baseUrl}/${'Bbsrs'}`)
     .toPromise();
    }
}

List Component :


import { Component, OnInit, OnDestroy } from '@angular/core';
import { BbsrService } from './bbsr.service';
import { Ibbsr, Ictc} from './bbsr.model';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'app-listbbsr',
  templateUrl: './listbbsr.component.html',
  styleUrls: ['./listbbsr.component.css']
})
export class ListbbsrComponent implements OnDestroy, OnInit {
list: Ibbsr[];
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();
  constructor(private bs: BbsrService) { }

  ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 2
    };
    this.fill();
  }
  fill(): void {
    this.bs.Gets().then(data => {
      this.list = data;
      this.dtTrigger.next();
    });
  }
  del(id: number): void {

    if (confirm('Do you want to delete it ?') ) {
      this.bs.Delete(id).then(data => {
        this.fill();
      });
    }

  }
  ngOnDestroy(): void {
    this.dtTrigger.unsubscribe();
  }
}


List View :

<div class="form-group">
    <div class="col-lg-4">
        <input type="button" value="Add New" [routerLink]="['/create']" style="width:80px" class="btn btn-primary" />
     </div>

    <label class="control-label col-lg-4"></label>
</div><br><br>
<div style="border:1px solid #808080">
  <table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover table table-bordered table-bordered table-condensed table-hover table-responsive table-striped">
  <thead class="bg bg-primary">
    <tr>
      <th>Sl No.</th>
      <th>NAME</th>
      <th>ACTION</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let c of list;let i=index">
    <td>{{i+1}}</td>
    <td>{{c.NAME}}</td>
    <td>
      <input type="button" style="width:80px" value="Edit" class="btn btn-primary" [routerLink]='["/create",c.BID]' /> |
      <input type="button" style="width:80px" value="Delete" class="btn btn-primary" (click)="del(c.BID)"/>
    </td>
    </tr>
  </tbody>
</table>
</div>

Create Component :

import { Component, OnInit, ViewChild } from '@angular/core';
import { Ibbsr, Ictc } from './bbsr.model';
import { NgForm } from '@angular/forms';
import { BbsrService } from './bbsr.service';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-createbbsr',
  templateUrl: './createbbsr.component.html',
  styleUrls: ['./createbbsr.component.css']
})
export class CreatebbsrComponent implements OnInit {
@ViewChild('bbsrForm') public  bbsrFrm: NgForm;
bid: number;
BBSR: Ibbsr;
  constructor(private bs: BbsrService, private rc: Router, private ar: ActivatedRoute) { }
  ngOnInit() {
    this.bid = this.ar.snapshot.params['id'];
    this.CLR();
    if (this.bid !== 0) {
      this.bs.Get(this.bid).then(data => this.BBSR = data);
    }
  }
add(): void {
  this.BBSR.CLIST.push({NAME: null, GENDER: null, MSTATUS: null, BID: null, CID: null});
}
remove(d: Ictc): void {
this.BBSR.CLIST.splice(this.BBSR.CLIST.indexOf(d), 1);
}
save(): void {
if (this.bid === 0) {
  this.bs.Save(this.BBSR).then(data => {
    alert(data);
    this.CLR();
    this.rc.navigate(['/list']);
  });
} else {
  this.bs.Update(this.BBSR).then(data => {
    alert(data);
    this.CLR();
    this.rc.navigate(['/list']);
  });
}
this.bid = 0;
}
reset(): void {
  this.CLR();
}
  CLR(): void {
    this.BBSR = {
       BID: null,
       NAME: null,
      CLIST: new Array()
    };
    this.bbsrFrm.reset();
    this.add();
  }
}

Create View :

<form class="form-horizontal" #bbsrForm="ngForm">
  <div class="form-group" [class.has-success]="BID.valid" [class.has-error]="BID.invalid && BID.touched">
      <label class="control-label col-lg-4">BID</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" required [(ngModel)]="BBSR.BID" #BID="ngModel" name="BID" />
      </div>
      <span class="help-block" *ngIf="BID.invalid && BID.touched">
          Bid should not be blank.
      </span>
  </div>
  <div class="form-group" [class.has-success]="NAME.valid" [class.has-error]="NAME.invalid && NAME.touched">
      <label class="control-label col-lg-4">NAME</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" required [(ngModel)]="BBSR.NAME" #NAME="ngModel" name="NAME" />
      </div>
      <span class="help-block" *ngIf="NAME.invalid && NAME.touched">
          Name should not be blank.
      </span>
  </div>
</form>
<div class="form-group">
  <label class="control-label col-lg-4"></label>
  <div class="col-lg-8">
      <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
          <thead class="bg bg-danger">
              <tr >
                  <th>NAME</th>
                  <th>GENDER</th>
                  <th>MARITIAL STATUS</th>
                  <th style="text-align:center"><a (click)="add()">Add</a></th>
              </tr>
          </thead>
          <tbody>
              <tr *ngFor="let c of BBSR.CLIST;let i=index">
                  <td><input type="text" class="form-control" name="NAME" [(ngModel)]="c.NAME" /></td>
                  <td><input type="radio" name={{i}}  value="Male"  [(ngModel)]="c.GENDER" />Male&nbsp;
                    <input  type="radio" name={{i}} value="Female" [(ngModel)]="c.GENDER" />Female</td>
                  <td>
                      <select class="form-control" [(ngModel)]="c.MSTATUS" #MSTATUS="ngModel" name={{i}}>
                      <option [ngValue]="null">Select</option>
                      <option value='Married'>Married</option>
                      <option value='Unmarried'>Unmarried</option>
                      </select>
                  </td>
                  <td style="text-align:center">
                       <a (click)="remove(c)">Remove</a>
                  </td>
              </tr>
          </tbody>
      </table>
  </div>
</div>
<form class="form-horizontal">
  <div class="form-group">
    <label class="control-label col-lg-4"></label>
      <div class="col-lg-4">
         <input type="button" value="Submit" (click)="save()" style="width:80px" class="btn btn-primary" />
          <input type="button" value="Reset" (click)="reset()" style="width:80px" class="btn btn-primary" /><br><br>
          <a [routerLink]="['/list']">Back To List</a>
      </div>
   
  </div>
</form>



App View :

 <div style="padding:5px" class="container">
    
      <ul class="nav nav-tabs">
    
       <li routerLinkActive="Active">
    
         <a routerLink="list">Department</a>
    
       </li>
    
       <li routerLinkActive="Active">
    
          <a routerLink="list">Employee</a>
    
        </li>
    
      </ul>
    
    <br>
    
    <router-outlet></router-outlet>
    
    </div>
     



Tuesday 25 December 2018

Dynamic page in angularjs6 & webapi2


Web api code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication5.Models;

namespace WebApplication5.Controllers
{
    [RoutePrefix("api/Deptservice")]
    public class DeptserviceController : ApiController
    {
        [HttpGet]
        [Route("AllDepts")]
        public IHttpActionResult AllDepts()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.DEPTs.ToList());
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpGet]
        [Route("Dept/{DID:int}",Name ="Dept")]
        public IHttpActionResult Dept(int DID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    DEPTVM vm = obj.DEPTs.Select(p => new DEPTVM { DID = p.DID, DNAME = p.DNAME }).SingleOrDefault(e => e.DID == DID);
                    vm.ELIST = obj.EMPs.Where(m => m.DID == DID).ToList();
                    return Ok(vm);
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpPost]
        [Route("Save")]
        public IHttpActionResult Save(DEPTVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    DEPT dept = new Models.DEPT();
                    dept.DID = vm.DID;
                    dept.DNAME = vm.DNAME;
                    obj.DEPTs.Add(dept);
                    obj.SaveChanges();
                    obj.EMPs.AddRange(vm.ELIST.Select(p => new EMP { EID = p.EID, NAME = p.NAME, DID = vm.DID }));
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("Dept",new { DID=vm.DID })), "Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpPut]
        [Route("Update/{DID:int}")]
        public IHttpActionResult Update([FromUri]int DID, [FromBody]DEPTVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    DEPT dept = obj.DEPTs.Find(DID);
                    dept.DNAME = vm.DNAME;
                    obj.SaveChanges();
                    obj.EMPs.RemoveRange(obj.EMPs.Where(p => p.DID == DID));
                    obj.SaveChanges();
                    obj.EMPs.AddRange(vm.ELIST.Select(p => new EMP { EID = p.EID, NAME = p.NAME, DID = vm.DID }));
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpDelete]
        [Route("Delete/{DID:int}")]
        public IHttpActionResult Delete([FromUri]int DID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    DEPT dept = obj.DEPTs.Find(DID);
                    obj.DEPTs.Remove(dept);
                    obj.SaveChanges();
                    obj.EMPs.RemoveRange(obj.EMPs.Where(p => p.DID == DID));
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

    }
}

angular model code:

export interface Iemp {
    EID: number;
    NAME: string;
    DID: number;
}
export interface Idept {
    DID: number;
    DNAME: string;
    ELIST: Iemp[];
}

angular service code :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import {Idept, Iemp} from './dynamic.model';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class DynamicseriviceService {
baseUrl = 'http://localhost:2813/api/Deptservice';
  constructor(private http: HttpClient) { }
Gets(): Promise<Idept[]> {
  return this.http.get<Idept[]>(`${this.baseUrl}/${'AllDepts'}`)
  .toPromise();
}
Get(did: number): Promise<Idept> {
  return this.http.get<Idept>(`${this.baseUrl}/${'Dept'}/${did}`)
  .toPromise();
}
Save(vm: Idept): Promise<string> {
  return this.http.post<string>(`${this.baseUrl}/${'Save'}`
, JSON.stringify(vm)
 , { headers: new HttpHeaders({'Content-Type' : 'application/json' })}
 )
.toPromise();
}
Update(vm: Idept): Promise<string> {
  return this.http.put<string>(`${this.baseUrl}/${'Update'}/${vm.DID}`
, JSON.stringify(vm)
 , { headers: new HttpHeaders({'Content-Type' : 'application/json' })}
 )
.toPromise();
}
Delete(did: number): Promise<string> {
  return this.http.delete<string>(`${this.baseUrl}/${'Delete'}/${did}`
 , { headers: new HttpHeaders({'Content-Type' : 'application/json' })}
 )
.toPromise();
}
}

angular component code :

import { Component, OnInit, ViewChild } from '@angular/core';
import { Idept, Iemp } from './dynamic.model';
import { DynamicseriviceService } from './dynamicserivice.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-createdynamic',
  templateUrl: './createdynamic.component.html',
  styleUrls: ['./createdynamic.component.css']
})
export class CreatedynamicComponent implements OnInit {
 DEPT: Idept;
 list: Iemp[];
 listd: Idept[];
 @ViewChild('ctcForm') public frmDept: NgForm;
  constructor(private ds: DynamicseriviceService) { }

  ngOnInit() {
    this.CLR();
    this.fill();
  }
  CLR(): void {
    this.DEPT = {
      DID: null,
      DNAME: null,
      ELIST: new Array()
    };
    this.frmDept.reset();
    this.add();
  }
add(): void {
  this.DEPT.ELIST.push({EID: null, NAME: null, DID: null});
}
save(): void {
  this.ds.Save(this.DEPT).then(data => {
    alert(data);
    this.CLR();
    this.fill();
  });
}
update(): void {
  this.ds.Update(this.DEPT).then(data => {
    alert(data);
    this.CLR();
    this.fill();
  });
}
del(did: number): void {
  if (confirm('Do you want to delte it')) {
    this.ds.Delete(did).then(data => {
      alert(data);
      this.fill();
          });
  }
}

edit(did: number): void {
  this.ds.Get(did).then(data => this.DEPT = data);
}
fill(): void {
this.ds.Gets().then(data => { this.listd = data; });
}
reset(): void {
  this.CLR();
}
sub(d: Iemp): void {
  if (this.DEPT.ELIST.length > 1 ) {
    this.DEPT.ELIST.splice(this.DEPT.ELIST.indexOf(d), 1);
  }
}
}

angular view code :

<form class="form-horizontal" #ctcForm="ngForm">
    <div class="form-group" [class.has-error]="DID.invalid && DID.touched" [class.has-success]="DID.valid">
        <label class="control-label col-lg-4">DID</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" [(ngModel)]="DEPT.DID" #DID="ngModel" name="DID" required />
        </div>
        <span class="help-block" *ngIf="DID.invalid && DID.touched">
            DID should not be blank.
        </span>
    </div>
    <div class="form-group" [class.has-error]="DNAME.invalid && DNAME.touched" [class.has-success]="DNAME.valid">
        <label class="control-label col-lg-4">DNAME</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" [(ngModel)]="DEPT.DNAME" #DNAME="ngModel" name="DNAME" required />
        </div>
        <span class="help-block" *ngIf="DNAME.invalid && DNAME.touched">
            Dname should not be blank.
        </span>
    </div>
  </form>
    <div class="form-group">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-6">
            <table  class="table table-bordered table-bordered table-condensed table-hover table-responsive table-striped">
                <thead class="bg bg-danger">
                <tr style="text-align:center"><td>EID</td><td>NAME</td><td>ACTION</td></tr>
              </thead>
                <tr *ngFor="let c of DEPT.ELIST">
                  <td style="width:20px">
                    <input  type="text" class="form-control" [(ngModel)]="c.EID">
                  </td>
                  <td style="width:100px">
                    <input  type="text" class="form-control" [(ngModel)]="c.NAME">
                  </td>
                  <td style="width:10px">
                    <a style="color:green;" (click)="add()">Add</a> |
                    <a style="color:red;" (click)="sub(c)">Remove</a>
                  </td>
                </tr>
              </table>
        </div>
    </div>
    <form class="form-horizontal">
    <div class="form-group ">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-4">
           <input type="button" value="Save" style="width:80px" (click)="save()" class="btn btn-primary" />
            <input type="button" value="Update" style="width:80px" (click)="update()" class="btn btn-primary" />
            <input type="button" value="Reset" style="width:80px" (click)="reset()" class="btn btn-primary" />
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-6">
            <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
                <thead class="bg bg-primary">
                    <tr>
                        <th>Sl No.</th>
                        <th>DNAME</th>
                        <th>ACTION</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let c of listd;let i=index">
                        <td>{{i+1}}</td>
                        <td>{{c.DNAME}}</td>
                        <td>
                            <a (click)="edit(c.DID)">Edit</a> |
                            <a (click)="del(c.DID)">Delete</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
  </form>



Sunday 23 December 2018

Image upload & download in angularjs6 & webapi2



web api code :

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication5.Models;

namespace WebApplication5.Controllers
{
    [RoutePrefix("api/Imageuploadservice")]
    public class ImageuploadserviceController : ApiController
    {
        [Route("Allimages")]
        [HttpGet]
        public HttpResponseMessage Allimages()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.IMAGEUPLOADS.ToList());
                }

            }
            catch(Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [Route("Image/{ID:int}",Name ="Image")]
        [HttpGet]
        public HttpResponseMessage Image(int ID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.IMAGEUPLOADS.Find(ID));
                }

            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [Route("Save")]
        [HttpPost]
        public HttpResponseMessage Save()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    var HttpRequest =System.Web.HttpContext.Current.Request;
                    var Postedfile = HttpRequest.Files["IMAGE"];
                    System.IO.FileInfo fi = new System.IO.FileInfo(Postedfile.FileName);
                    string path = System.Web.HttpContext.Current.Server.MapPath("~/Images/" + fi.Name);
                    if (Postedfile.ContentLength > 0)
                        Postedfile.SaveAs(path);
                    IMAGEUPLOAD vm = new Models.IMAGEUPLOAD();
                    vm.ID = int.Parse(HttpRequest["ID"]);
                    vm.NAME = HttpRequest["NAME"];
                    vm.PATH = "http://localhost:2813/images/" + fi.Name;
                    obj.Entry(vm).State = EntityState.Added;
                    obj.SaveChanges();
                    var req = Request.CreateResponse(HttpStatusCode.Created, "Data Saved.");
                    req.Headers.Location=new Uri(Url.Link("Image",new  {ID = vm.ID }));
                    return req;
                }

            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [Route("Update")]
        [HttpPut]
        public HttpResponseMessage Update()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    IMAGEUPLOAD vm = new Models.IMAGEUPLOAD();
                    var HttpRequest = System.Web.HttpContext.Current.Request;
                    var Postedfile = HttpRequest.Files["IMAGE"];
                    int ID = int.Parse(HttpRequest["ID"]);
                    vm = obj.IMAGEUPLOADS.Find(ID);
                    vm.NAME = HttpRequest["NAME"];
                    if (Postedfile!=null)
                    {
                        System.IO.FileInfo fi = new System.IO.FileInfo(Postedfile.FileName);
                        string path = System.Web.HttpContext.Current.Server.MapPath("~/Images/" + fi.Name);
                        if (Postedfile.ContentLength > 0)
                            Postedfile.SaveAs(path);
                        vm.PATH = "http://localhost:2813/images/" + fi.Name;
                    }
                    obj.Entry(vm).State = EntityState.Modified;
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Updated.");
                 
                }

            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
        [Route("Delete/{ID:int}")]
        [HttpDelete]
        public HttpResponseMessage Delete(int ID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    IMAGEUPLOAD vm = obj.IMAGEUPLOADS.Find(ID);
                    obj.Entry(vm).State = EntityState.Deleted;
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Deleted.");

                }

            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
        }

    }
}



Angular js view :


<form class="form-horizontal" #imageForm="ngForm">
  <div class="form-group" [class.has-success]="ID.valid" [class.has-error]="ID.invalid && ID.touched">
      <label class="control-label col-lg-4">ID</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" required [(ngModel)]="IMAGE1.ID" #ID="ngModel" name="ID"/>
      </div>
      <span class="help-block" *ngIf="ID.invalid && ID.touched">
          ID should not be blank.
      </span>
  </div>
  <div class="form-group" [class.has-success]="NAME.valid" [class.has-error]="NAME.invalid && NAME.touched">
    <label class="control-label col-lg-4">NAME</label>
    <div class="col-lg-4">
        <input type="text" class="form-control" required [(ngModel)]="IMAGE1.NAME" #NAME="ngModel" name="NAME"/>
    </div>
    <span class="help-block" *ngIf="NAME.invalid && NAME.touched">
        Name should not be blank.
    </span>
</div>
<div class="form-group" >
    <label class="control-label col-lg-4">IMAGE</label>
    <div class="col-lg-4">
        <img style="height:50px;width:50px" [src]="imagepath"  >
        <input (change)="fillimage($event.target.files)" type="file" class="form-control" [(ngModel)]="IMAGE1.IMAGE"  #IMAGE="ngModel" name="IMAGE"/>
    </div>
 
</div>
<div class="form-group" >
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-4">
            <input type="button" class="btn btn-primary" value="Save" style="width:80px" (click)="save()" />
            <input type="button" class="btn btn-primary" value="Update" style="width:80px" (click)="update()" />
            <input type="button" class="btn btn-primary" value="Reset" style="width:80px" (click)="reset(imageForm)" />
        </div>
</div>
<div class="form-group" >
    <label class="control-label col-lg-4"></label>
    <div class="col-lg-8">
       <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
           <thead class="bg bg-primary">
               <tr>
                   <th>Sl No.</th>
                   <th>Name</th>
                   <th>Image</th>
                   <th>Download</th>
                   <th>Action</th>
               </tr>
           </thead>
           <tbody>
               <tr *ngFor="let c of list;let i=index">
                   <td>{{i+1}}</td>
                   <td>{{c.NAME}}</td>
                   <td><img [src]='c.PATH' style="width:50px; height:50px" /></td>
                   <td><a [href]='c.PATH' download>Download</a></td>
                   <td>
                       <a (click)="edit(c.ID)">Edit</a> |
                       <a (click)="del(c.ID)">Delete</a>
                   </td>
               </tr>
           </tbody>
       </table>
    </div>
</div>
</form>

Angular js Componet  :


import { Component, OnInit, ViewChild } from '@angular/core';
import { Iimage } from './image.model';
import { ImageService } from './image.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-createimage',
  templateUrl: './createimage.component.html',
  styleUrls: ['./createimage.component.css']
})
export class CreateimageComponent implements OnInit {
  IMAGE1: Iimage;
  list: Iimage[];
imagepath: string;
@ViewChild('imageForm') public imForm: NgForm;
  constructor(private ps: ImageService) { }
  ngOnInit() {
    this.CLR();
    this.fill();
    this.imagepath = '';
  }
  fillimage(im: FileList): void {
    this.IMAGE1.IMAGE = im.item(0);
    const reader = new FileReader();
    reader.onload = (event: any) => {
      this.imagepath = event.target.result;
    };
   reader.readAsDataURL(this.IMAGE1.IMAGE);
  }
  save(): void {
    this.ps.Save(this.IMAGE1).then(data => {
      alert(data);
      this.CLR();
      this.fill();
      this.imagepath = null;
    });
  }
  update(): void {
    this.ps.Update(this.IMAGE1).then(data => {
      alert(data);
      this.CLR();
      this.fill();
      this.imagepath = null;
    });
  }
  fill(): void {
    this.ps.Gets().then(data => this.list = data );
  }
  edit(id: number): void {
    this.ps.Get(id).then(data => {
      this.IMAGE1.ID = data.ID;
      this.IMAGE1.NAME = data.NAME;
      this.imagepath = data.PATH;
    });
  }
  del(id: number): void {
   if (confirm('Do you want to delte it ?')) {
     this.ps.Delete(id).then(data => {
       alert(data);
       this.fill();
     });
   }
  }
  reset(im: NgForm): void {
    im.reset();
    this.imagepath = null;
  }
CLR(): void {
  this.IMAGE1 = {
     ID: null,
     NAME: null,
     IMAGE: null
  };
  this.imForm.reset();
}
}

Angularjs Services :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Iimage, Iimage2 } from './image.model';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class ImageService {
    constructor(private http: HttpClient) { }
    baseUrl = 'http://localhost:2813/api/Imageuploadservice';
    Gets(): Promise<Iimage[]> {
        return this.http.get<Iimage[]>(`${this.baseUrl}/${'Allimages'}`)
            .toPromise();
    }
    Get(id: number): Promise<Iimage2> {
        return this.http.get<Iimage2>(`${this.baseUrl}/${'Image'}/${id}`)
            .toPromise();
    }
    Save(im: Iimage): Promise<string> {
        const formData: FormData = new FormData();
        formData.append('ID', im.ID.toString());
        formData.append('NAME', im.NAME);
        formData.append('IMAGE', im.IMAGE, im.IMAGE.name);
        return this.http.post<string>(`${this.baseUrl}/${'Save'}`
            , formData
        ).toPromise();
    }
    Update(im: Iimage): Promise<string> {
        const formData: FormData = new FormData();
        formData.append('ID', im.ID.toString());
        formData.append('NAME', im.NAME);
        if (im.IMAGE != null) {
            formData.append('IMAGE', im.IMAGE, im.IMAGE.name);
        }
        return this.http.put<string>(`${this.baseUrl}/${'Update'}`
            , formData
        ).toPromise();
    }
    Delete(id: number): Promise<string> {
        return this.http.delete<string>(`${this.baseUrl}/${'Delete'}/${id}`)
            .toPromise();
    }
}

Angular js Model :


export interface Iimage {
    ID: number;
    NAME: string;
    IMAGE: File;
}

export interface Iimage2 {
    ID: number;
    NAME: string;
    PATH: string;
}

Use of data table in angularjs6 & Webapi

Press Me

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


Add below code in angular-cli.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 { DataTablesModule } from 'angular-datatables'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, DataTablesModule ], providers: [], bootstrap: [ AppComponent ] })
Angularjs Model code :
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Inote } from '../note/note.model'; import { NoteServices } from '../note/note.services'; import { Subject } from 'rxjs/Subject'; @Component({ selector: 'app-createdatatable', templateUrl: './createdatatable.component.html', styleUrls: ['./createdatatable.component.css'] }) export class CreatedatatableComponent implements OnDestroy, OnInit { dtOptions: DataTables.Settings = {}; dtTrigger: Subject<any> = new Subject(); list: Inote[]; constructor(private ns: NoteServices) { } ngOnInit() { this.dtOptions = { pagingType: 'full_numbers', pageLength: 2 }; this.fill(); } fill(): void { this.ns.Getn().then(data => { this.list = data; this.dtTrigger.next(); }); } ngOnDestroy(): void { this.dtTrigger.unsubscribe(); } }
Angularjs View Code :
<div style="border:1px solid #808080"> <table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover table table-bordered table-bordered table-condensed table-hover table-responsive table-striped"> <thead class="bg bg-primary"> <tr> <th>Sl No.</th> <th>NAME</th> <th>SALARY</th> </tr> </thead> <tbody> <tr *ngFor="let c of list;let i=index"> <td>{{i+1}}</td> <td>{{c.NAME}}</td> <td>{{c.SALARY}}</td> </tr> </tbody> </table> </div>

Wednesday 19 December 2018

CURD operation using reactive forms with validation in angularjs6





WEB API CODE :

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication5.Models;

namespace WebApplication5.Controllers
{
    [RoutePrefix("api/Delhiservice")]
    public class DelhiserviceController : ApiController
    {
        [HttpGet]
        [Route("Countries")]
        public HttpResponseMessage Countries()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.COUNTRies.ToList());
                }
            }
            catch(Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpGet]
        [Route("Delhis")]
        public HttpResponseMessage Delhis()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.DELHIs.ToList());
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpGet]
        [Route("Delhi/{DID:int}", Name ="Delhi")]
        public HttpResponseMessage Delhi(int DID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Request.CreateResponse(HttpStatusCode.OK, obj.DELHIs.Find(DID));
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpPost]
        [Route("Save")]
        public HttpResponseMessage Save(DELHI vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(vm).State = EntityState.Added;
                    obj.SaveChanges();
                    var req = Request.CreateResponse(HttpStatusCode.Created, "Data Saved.");
                    req.Headers.Location = new Uri(Url.Link("Delhi", new { DID = vm.DID }));
                    return req;
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }

        [HttpPut]
        [Route("Update/{DID:int}")]
        public HttpResponseMessage Update([FromUri]int DID,[FromBody]DELHI vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(vm).State = EntityState.Modified;
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Updated.");
                    
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
        [HttpDelete]
        [Route("Delete/{DID:int}")]
        public HttpResponseMessage Delete([FromUri]int DID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(obj.DELHIs.Find(DID)).State = EntityState.Deleted;
                    obj.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, "Data Deleted.");

                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }

    }
}

ANGULARJS MODEL :

export interface Idelhi {
    DID: number;
    NAME: string;
    PASSWORD: string;
    ADDRESS: string;
    EMAIL: string;
    GENDER: string;
    CID: number;
    TERMS: boolean;
}

export interface Icountry {
    CID: number;
    CNAME: string;
}


ANGULAR SERVICE :


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Idelhi, Icountry } from './delhi.model';
import { ErrorObservable } from 'rxjs/Observable/ErrorObservable';
import { catchError } from 'rxjs/operators';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';


@Injectable()
export class DelhiServices {
    baseUrl = 'http://localhost:2813/api/Delhiservice';
    constructor(private _http: HttpClient) {

    }
    Getc(): Promise<Icountry[]> {
        return this._http.get<Icountry[]>(`${this.baseUrl}/${'Countries'}`)
            .toPromise();
    }
    Getd(): Promise<Idelhi[]> {
        return this._http.get<Idelhi[]>(`${this.baseUrl}/${'Delhis'}`)
            .toPromise();
    }
    Get(did: number): Promise<Idelhi> {
        return this._http.get<Idelhi>(`${this.baseUrl}/${'Delhi'}/${did}`)
            .toPromise();
    }
    Save(delhi: Idelhi): Promise<string> {
        return this._http.post<string>(`${this.baseUrl}/${'Save'}`
            , JSON.stringify(delhi)
            , { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }
        )
            .toPromise();
    }
    Update(delhi: Idelhi): Promise<string> {
        return this._http.put<string>(`${this.baseUrl}/${'Update'}/${delhi.DID}`
            , JSON.stringify(delhi)
            , { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }
        )
            .toPromise();
    }
    Delete(did: number): Promise<string> {
        return this._http.delete<string>(`${this.baseUrl}/${'Delete'}/${did}`
            , { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }
        )
            .toPromise();
    }

    private handleError(errorResponse: HttpErrorResponse) {
        if (errorResponse.error instanceof ErrorEvent) {
           console.log('Client side error' + errorResponse.error.message);
        } else {
            console.log('Server side error' + errorResponse);
        }
    }
}

ANGULARJS PIPE CODE :

import { Pipe, PipeTransform } from '@angular/core';


@Pipe({
    name: 'CustomPipe'
})
export class DelhiPipe implements PipeTransform {
     transform(value: string, gender: string): string {
         if ( gender.toLowerCase() === 'male' ) {
             return 'Mr. ' + value;
         } else {
             return 'Miss. ' + value;
         }
     }
}



ANGULARJS LIST COMPONENT :


import { Component, OnInit } from '@angular/core';
import { DelhiServices } from './delhi.services';
import { Idelhi } from './delhi.model';
import { Router } from '@angular/router';

@Component({
  selector: 'app-listdelhi',
  templateUrl: './listdelhi.component.html',
  styleUrls: ['./listdelhi.component.css']
})
export class ListdelhiComponent implements OnInit {
list: Idelhi[];
  constructor(private ds: DelhiServices, private router: Router) { }

  ngOnInit() {
    this.fill();
  }
fill(): void {
this.ds.Getd().then(data => this.list = data);
}
add(): void {
  this.router.navigate(['/create']);
}
edit(did: number): void {
  this.router.navigate(['/create', did]);
}
del(did: number): void {
  if (confirm('Do you want to delete it ?')) {
    this.ds.Delete(did).then(data => {
      this.fill();
    });
  }
}
}

ANGULARJS CREATE COMPONENT :  

import { Component, OnInit } from '@angular/core';
import {FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Idelhi, Icountry} from './delhi.model';
import { DelhiServices } from './delhi.services';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-createdelhi',
  templateUrl: './createdelhi.component.html',
  styleUrls: ['./createdelhi.component.css']
})
export class CreatedelhiComponent implements OnInit {
delhiForm: FormGroup;
DELHI: Idelhi;
listc: Icountry[];
list: Idelhi[];
did: number;
  constructor(private fb: FormBuilder, private ds: DelhiServices, private router: Router, private ar: ActivatedRoute ) { }

  ngOnInit() {
    this.delhiForm = this.fb.group({
      DID: [null, Validators.required],
      NAME: [null, Validators.required],
      PASSWORD: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(8)]],
      ADDRESS: [null, Validators.required],
      EMAIL: [null, [Validators.required, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')]],
      GENDER: [null, Validators.required],
      CID: [null, Validators.required],
      TERMS: [true, Validators.requiredTrue]
    });
    this.CLR();
    this.ds.Getc().then(data => this.listc = data);
    this.did = this.ar.snapshot.params['id'];
    if (this.did > 0) {
     this.ds.Get(this.did).then(data => {
       this.delhiForm.setValue({
          DID: data.DID,
          NAME: data.NAME,
          PASSWORD: data.PASSWORD,
          ADDRESS: data.ADDRESS,
          EMAIL: data.EMAIL,
          GENDER: data.GENDER,
          CID: data.CID,
          TERMS: data.TERMS
       });
     });
    }
  }
  reset(): void {
  this.CLR();
  }
  save(): void {
    this.DELHI.DID = this.delhiForm.value.DID;
    this.DELHI.NAME = this.delhiForm.value.NAME;
    this.DELHI.PASSWORD = this.delhiForm.value.PASSWORD;
    this.DELHI.ADDRESS = this.delhiForm.value.ADDRESS;
    this.DELHI.EMAIL = this.delhiForm.value.EMAIL;
    this.DELHI.GENDER = this.delhiForm.value.GENDER;
    this.DELHI.CID = this.delhiForm.value.CID;
    this.DELHI.TERMS = this.delhiForm.value.TERMS;
    if (this.delhiForm.valid) {
      if (this.did > 0) {
        this.ds.Update(this.DELHI).then(data => {
           this.CLR();
         });
      } else {
        this.ds.Save(this.DELHI).then(data => {
           this.CLR();
         });
      }
      this.router.navigate(['/list']);
    }
  }
CLR(): void {
this.DELHI = {
  DID: null,
  NAME: null,
  PASSWORD: null,
  ADDRESS: null,
  EMAIL: null,
  GENDER: null,
  CID: null,
  TERMS: null
};
this.delhiForm.reset();
this.delhiForm.patchValue({
  TERMS: true
});
}
}


ANGULARJS LIST VIEW :

<div class="form-group">
        <div class="col-lg-4">
                <input type="button" (click)="add()" class="btn btn-primary" value="Add New" width="80px" />
        </div>
    <label class="control-label col-lg-4"></label>
  </div><Br><br>

<div class="form-group">
  
  <div class="col-lg-8">
     <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
         <thead class="bg bg-primary">
             <tr>
                 <th>Sl No.</th>
                 <th>NAME</th>
                 <th>GENDER</th>
                 <th>ACTION</th>
             </tr>
         </thead>
         <tbody>
             <tr *ngFor="let c of list;let i=index">
                 <td>{{i+1}}</td>
                 <td>{{c.NAME|CustomPipe : c.GENDER}}</td>
                 <td>{{c.GENDER}}</td>
                 <td>
                     <input type="button" class="btn btn-primary" (click)="edit(c.DID)" value="Edit" style="width:80px"  /> |
                     <input type="button" class="btn btn-primary" (click)="del(c.DID)" value="Delete" style="width:80px" />
                 </td>
             </tr>
         </tbody>
     </table>
  </div>
  <label class="control-label col-lg-4"></label>
</div>


ANGULARJS CREATE VIEW :

<form class="form-horizontal" [formGroup]="delhiForm">
  <div class="form-group" [ngClass]="{'has-error':delhiForm.get('DID').errors && (delhiForm.get('DID').touched || delhiForm.get('DID').dirty)}">
      <label class="control-label col-lg-4">DID</label>
      <div class="col-lg-4">
          <input type="text" class="form-control" formControlName="DID" />
      </div>
      <span *ngIf="delhiForm.get('DID').errors && (delhiForm.get('DID').touched || delhiForm.get('DID').dirty)">
          <span *ngIf="delhiForm.get('DID').errors.required"> DID should not be blank.</span>
      </span>
  </div>
  <div class="form-group" [ngClass]="{'has-error':delhiForm.get('NAME').errors && (delhiForm.get('NAME').touched || delhiForm.get('NAME').dirty)}">
    <label class="control-label col-lg-4">NAME</label>
    <div class="col-lg-4">
        <input type="text" class="form-control" formControlName="NAME" />
    </div>
    <span *ngIf="delhiForm.get('NAME').errors && (delhiForm.get('NAME').touched || delhiForm.get('NAME').dirty)">
        <span *ngIf="delhiForm.get('NAME').errors.required"> Name should not be blank.</span>
    </span>
</div>

<div class="form-group" [ngClass]="{'has-error':delhiForm.get('PASSWORD').errors && (delhiForm.get('PASSWORD').touched || delhiForm.get('PASSWORD').dirty)}">
    <label class="control-label col-lg-4">PASSWORD</label>
    <div class="col-lg-4">
        <input type="password" class="form-control" formControlName="PASSWORD" />
    </div>
    <span *ngIf="delhiForm.get('PASSWORD').errors && (delhiForm.get('PASSWORD').touched || delhiForm.get('PASSWORD').dirty)">
        <span *ngIf="delhiForm.get('PASSWORD').errors.required">Password should not be blank.</span>
        <span *ngIf="delhiForm.get('PASSWORD').errors.minlength">Password minlength is 6.</span>
        <span *ngIf="delhiForm.get('PASSWORD').errors.maxlength">Password maxlength is 8.</span>
    </span>
</div>

<div class="form-group" [ngClass]="{'has-error':delhiForm.get('ADDRESS').errors && (delhiForm.get('ADDRESS').touched || delhiForm.get('ADDRESS').dirty)}">
    <label class="control-label col-lg-4">ADDRESS</label>
    <div class="col-lg-4">
        <textarea class="form-control" formControlName="ADDRESS"></textarea>
    </div>
    <span *ngIf="delhiForm.get('ADDRESS').errors && (delhiForm.get('ADDRESS').touched || delhiForm.get('ADDRESS').dirty)">
        <span *ngIf="delhiForm.get('ADDRESS').errors.required">Address should not be blank.</span>
    </span>
</div>

<div class="form-group" [ngClass]="{'has-error':delhiForm.get('EMAIL').errors && (delhiForm.get('EMAIL').touched || delhiForm.get('EMAIL').dirty)}">
    <label class="control-label col-lg-4">EMAIL</label>
    <div class="col-lg-4">
        <input type="text" class="form-control" formControlName="EMAIL" />
    </div>
    <span *ngIf="delhiForm.get('EMAIL').errors && (delhiForm.get('EMAIL').touched || delhiForm.get('EMAIL').dirty)">
        <span *ngIf="delhiForm.get('EMAIL').errors.required">Email should not be blank.</span>
        <span *ngIf="delhiForm.get('EMAIL').errors.pattern">Invalid email id.</span>
    </span>
</div>

<div class="form-group" [ngClass]="{'has-error':delhiForm.get('GENDER').errors && (delhiForm.get('GENDER').touched || delhiForm.get('GENDER').dirty)}">
    <label class="control-label col-lg-4">GENDER</label>
    <div class="col-lg-4">
        <input type="radio" value="Male"  formControlName="GENDER" />Male
        <input type="radio" value="Female"  formControlName="GENDER" />Female
    </div>
    <span *ngIf="delhiForm.get('GENDER').errors && (delhiForm.get('GENDER').touched || delhiForm.get('GENDER').dirty)">
    <span *ngIf="delhiForm.get('GENDER').errors.required">Please select a gender.</span>
    </span>
</div>

<div class="form-group" [ngClass]="{'has-error':delhiForm.get('CID').errors && (delhiForm.get('CID').touched || delhiForm.get('CID').dirty)}">
    <label class="control-label col-lg-4">COUNTRY</label>
    <div class="col-lg-4">
        <select class="form-control" formControlName="CID">
            <option [ngValue]="null">Select</option>
            <option *ngFor="let c of listc" [value]="c.CID">{{c.CNAME}}</option>
        </select>
    </div>
    <span *ngIf="delhiForm.get('CID').errors && (delhiForm.get('CID').touched || delhiForm.get('CID').dirty)">
        <span *ngIf="delhiForm.get('CID').errors.required">Please select a country.</span>

    </span>
</div>
<div class="form-group" [ngClass]="{'has-error':delhiForm.get('TERMS').errors && (delhiForm.get('TERMS').touched || delhiForm.get('TERMS').dirty)}">
    <label class="control-label col-lg-4">TERMS & CONDITION</label>
    <div class="col-lg-4">
        <input type="checkbox" [value]="TERMS" formControlName="TERMS">  
    </div>
    <span *ngIf="delhiForm.get('TERMS').errors && (delhiForm.get('TERMS').touched || delhiForm.get('TERMS').dirty)">
        <span *ngIf="delhiForm.get('TERMS').errors.required">Please select a term.</span>
    </span>
</div>
<div class="form-group" >
    <label class="control-label col-lg-4"></label>
    <div class="col-lg-4">
        <input type="button" value="Submit" class="btn btn-primary" (click)="save()" style="width:80px">
        <input type="button" value="Reset" class="btn btn-primary" (click)="reset()" style="width:80px"><Br><Br>
        <a [routerLink]="['/list']">Back to List</a>    
    </div>
</div>
</form>

ANGULARJS ROUTE CODE :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
import { FormsModule } from '@angular/forms';
import { EmpService } from '../app/emps/emp.services';
import { HttpModule } from '@angular/http';
import { StapServices } from '../app/staps/create-stap/stap.services';
import { SelectRequiredValidatorDirective } from './shared/stap.Directive';
import { FacultyServices } from './faculties/faculty.services';
import { StudentServices } from './student/student.service';
import { DoctorService } from './doctors/doctor.services';
import { AppComponent } from './app.component';
import { CreateEmpComponent } from './emps/create-emp.component';
import { CreateStapComponent } from './staps/create-stap/create-stap.component';
import { StapListComponent } from './staps/create-stap/stap-list.component';
import { CreateFacultiesComponent } from './faculties/create-faculties.component';
import { CreateStudentComponent } from './student/create-student.component';
import { DoctorCreateComponent } from './doctors/doctor-create.component';
import { CompareDirective } from './shared/compare.Directive';
import { TestCreateComponent } from './test/test-create.component';
import { TestServices } from './test/test.service';
import { CusomPip } from './test/custom.pipe';
import { CreateRestComponent } from './rest/create-rest.component';
import { RestService } from './rest/rest.service';
import { Restpipe } from './rest/rest.custom.pipe';
import { CreateSalesComponent } from './sales/create-sales.component';
import { SalesService } from './sales/sales.services';
import { FilterPipe } from './sales/sales.pipe';
import { RouterModule, Routes } from '@angular/router';
import { ListComponent } from './rate/list.component';
import { RateCreateComponent } from './rate/rate-create.component';
import { RateService } from './rate/rate.service';
import { HttpClientModule } from '@angular/common/http';
import { RatePipe } from './rate/rate.pipe';
import { DeptlistComponent } from './dept/deptlist.component';
import { CreateDeptComponent } from './dept/create-dept.component';
import { DeptServices } from './dept/dept.services';
import { DeptPipe } from './dept/dept.pipe';

import { DoorServices } from '../app/door/door.services';
import { WcreateComponent } from './window/wcreate.component';
import { WindowServices } from './window/window.services';
import { CreatepenComponent } from './pen/createpen.component';
import { PenServices } from './pen/pen.services';
import { CreateComponent } from './author/create.component';
import { AuthorServices } from './author/author.services';
import { Checkpipe } from './author/author.pipe';
import { CreatebookComponent } from './book/createbook.component';
import { BookServices } from './book/book.services';
import { BookPipe } from './book/book.pipe';
import { CreatenoteComponent } from './note/createnote.component';
import { NoteServices } from './note/note.services';
import { NotePipe1 } from './note/note.pipe';
import { CreatestoreComponent } from './store/createstore.component';
import { StoreServices } from './store/store.services';
import { StorePipe } from './store/store.pipe';
import { CreateluckyComponent } from './lucky/createlucky.component';
import { LuckyServices } from './lucky/lucky.services';
import { LuckyPipe } from './lucky/lucky.pipe';
import { CreateunluckyComponent } from './unlucky/createunlucky.component';
import { UnluckyService } from './unlucky/unlucky.services';
import { UnluckyPipe } from './unlucky/unlucky.pipe';
import { CreatemumbaiComponent } from './mumbai/createmumbai.component';
import { MumbaiService } from './mumbai/mumbai.services';
import { MumbaiPipe } from './mumbai/mumbai.pipe';
import { CreatepuneComponent } from './pune/createpune.component';
import { ReactiveFormsModule } from '@angular/forms';
import { Puneservice } from './pune/pune.service';
import { CreatethaneComponent } from './thane/createthane.component';
import { CreatecstComponent } from './cst/createcst.component';
import { CstServices } from './cst/cst.services';
import { CreatedelhiComponent } from './delhi/createdelhi.component';
import { DelhiServices } from './delhi/delhi.services';
import { ListdelhiComponent } from './delhi/listdelhi.component';
import { PagenotfoundComponent } from './delhi/pagenotfound.component';
import { DelhiPipe } from './delhi/delhi.pipe';

const appRoutes: Routes = [
  { path: 'list', component: ListdelhiComponent },
  { path: 'create/:id', component: CreatedelhiComponent },
  { path: 'create', component: CreatedelhiComponent },
  { path: '', redirectTo: '/list', pathMatch: 'full' },
  { path: '**', component: PagenotfoundComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    CreateEmpComponent,
    CreateStapComponent,
    SelectRequiredValidatorDirective,
    StapListComponent,
    CreateFacultiesComponent,
    CreateStudentComponent,
    DoctorCreateComponent,
    CompareDirective,
    TestCreateComponent,
    CusomPip,
    CreateRestComponent,
    ListComponent,
    RateCreateComponent,
    Restpipe,
    FilterPipe,
    RatePipe,
    DeptPipe,
    CreateSalesComponent,
    DeptlistComponent,
    CreateDeptComponent,
    CreateComponent,
    WcreateComponent,
    CreatepenComponent,
    Checkpipe,
    CreatebookComponent,
    BookPipe,
    CreatenoteComponent,
    NotePipe1,
    CreatestoreComponent,
    StorePipe,
    CreateluckyComponent,
    LuckyPipe,
    CreateunluckyComponent,
    UnluckyPipe,
    CreatemumbaiComponent,
    MumbaiPipe,
    CreatepuneComponent,
    CreatethaneComponent,
    CreatecstComponent,
    CreatedelhiComponent,
    ListdelhiComponent,
    PagenotfoundComponent,
    DelhiPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    HttpClientModule,
    RouterModule.forRoot(appRoutes),
    ReactiveFormsModule
  ],
  providers: [EmpService, DeptServices, RateService, SalesService, StapServices,
    FacultyServices, StudentServices, DoctorService, TestServices,
    RestService, DoorServices, WindowServices, PenServices, AuthorServices
    , BookServices, NoteServices, StoreServices, LuckyServices, DelhiServices, UnluckyService, CstServices, MumbaiService, Puneservice],
  bootstrap: [AppComponent]
})
export class AppModule { }