Saturday 7 July 2018

CRUD operation , all pipes using Angularjs5 and web api2


WEB API :

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

namespace WebApplication2.Controllers
{
    [RoutePrefix("api/Testservice")]
    public class TestserviceController : ApiController
    {
        [Route("Tests")]
        [HttpGet]
        public IHttpActionResult Tests()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.TESTs.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
           
        }

        [Route("Test/{TID:int}", Name ="Test")]
        [HttpGet]
        public IHttpActionResult Test(int TID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.TESTs.Find(TID));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }

        [Route("Save")]
        [HttpPost]
        public IHttpActionResult Save(TEST tst)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(tst).State = EntityState.Added;
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("Test", new { TID = tst.TID })), "Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }

        [Route("Update/{TID:int}")]
        [HttpPut]
        public IHttpActionResult Update([FromUri]int TID,[FromBody]TEST tst)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                 
                    obj.Entry(tst).State = EntityState.Modified;
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }

        [Route("Delete/{TID:int}")]
        [HttpDelete]
        public IHttpActionResult Delete([FromUri]int TID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {

                    obj.Entry(obj.TESTs.Find(TID)).State = EntityState.Deleted;
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }


    }
}

Angularjs View :

<form class="form-horizontal" #frmTest="ngForm">
    <div class="form-group " [class.has-error]="TID.invalid && TID.touched" [class.has-success]="TID.valid">
        <label class="control-label col-lg-4">TID</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="TID" [(ngModel)]="TEST.TID" #TID="ngModel" required />
            <span class="help-block" *ngIf="TID.invalid && TID.touched">
                TID should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="NAME.invalid && NAME.touched" [class.has-success]="NAME.valid">
        <label class="control-label col-lg-4">NAME</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="NAME" [(ngModel)]="TEST.NAME" #NAME="ngModel" required />
            <span class="help-block" *ngIf="NAME.invalid && NAME.touched">
                Name should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="GENDER.invalid && GENDER.touched" [class.has-success]="GENDER.valid">
        <label class="control-label col-lg-4">GENDER</label>
        <div class="col-lg-4">
            <input type="radio"  name="GENDER" [(ngModel)]="TEST.GENDER" #GENDER="ngModel" required value="Male" />Male
            <input type="radio" name="GENDER" [(ngModel)]="TEST.GENDER" #GENDER="ngModel" required value="Female" />Female
            <span class="help-block" *ngIf="GENDER.invalid && GENDER.touched">
                Please select a gender.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="SALARY.invalid && SALARY.touched" [class.has-success]="SALARY.valid">
        <label class="control-label col-lg-4">SALARY</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="SALARY" [(ngModel)]="TEST.SALARY" #SALARY="ngModel" required />
            <span class="help-block" *ngIf="SALARY.invalid && SALARY.touched">
                Salary should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="DOB.invalid && DOB.touched" [class.has-success]="DOB.valid">
        <label class="control-label col-lg-4">DOB</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="DOB" [(ngModel)]="TEST.DOB" #DOB="ngModel" required />
            <span class="help-block" *ngIf="DOB.invalid && DOB.touched">
                DOB should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="MARK.invalid && MARK.touched" [class.has-success]="MARK.valid">
        <label class="control-label col-lg-4">MARK</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="MARK" [(ngModel)]="TEST.MARK" #MARK="ngModel" required />
            <span class="help-block" *ngIf="MARK.invalid && MARK.touched">
                Mark should not blank.
            </span>
        </div>
    </div>
    <div class="form-group " [class.has-error]="PERCENTAGE.invalid && PERCENTAGE.touched" [class.has-success]="PERCENTAGE.valid">
        <label class="control-label col-lg-4">PERCENTAGE</label>
        <div class="col-lg-4">
            <input type="text" class="form-control" name="PERCENTAGE" [(ngModel)]="TEST.PERCENTAGE" #PERCENTAGE="ngModel" required />
            <span class="help-block" *ngIf="PERCENTAGE.invalid && PERCENTAGE.touched">
                Percentage should not blank.
            </span>
        </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(frmTest.invalid)" >
            <input type="button" class="btn btn-primary" value="Update" style="width:80px" (click)="update(frmTest.invalid)">
            <input type="button" class="btn btn-primary" value="Reset" style="width:80px" (click)="reset()">
        </div>
    </div>
    <div class="row">
        <table style="width:1000px" class="table table-bordered table-condensed table-hover table-responsive table-striped">
            <thead class="bg bg-primary">
                <tr>
                    <th>Sl No.</th>
                    <th>TID</th>
                    <th>NAME</th>
                    <th>GENDER</th>
                    <th>SALARY</th>
                    <th >DOB</th>
                    <th>MARK</th>
                    <th>PERCENTAGE</th>
                    <th>ACTION</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let c of list;let i=index">
                    <td>{{i+1}}</td>
                    <td>{{c.TID}}</td>
                    <td>{{c.NAME|uppercase|CusomPipe:c.GENDER}}</td>
                    <td>{{c.GENDER|lowercase}}</td>
                    <td>{{c.SALARY|currency:'UST':false}}</td>
                    <td>{{c.DOB|date:"dd-MMM-y"}}</td>
                    <td>{{c.MARK|number:'1.2-2'}}</td>
                    <td>{{c.PERCENTAGE|percent}}</td>
                    <td>
                        <a (click)="edit(c.TID)">Edit</a> |
                        <a (click)="del(c.TID)">Delete</a>
                    </td>
                </tr>
            </tbody>
        </table>

    </div>
    
</form>

Angularjs Model :

export class ITEST {
    TID: number;
    NAME: string;
    GENDER: string;
    SALARY: number;
    DOB: Date;
    MARK: number;
    PERCENTAGE: number;
}


Angularjs Services :

import { Injectable } from '@angular/core';
import { Http, Headers, Request, Response, RequestOptions, RequestMethod } from '@angular/http';
import { ITEST } from '../test/test.model';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class TestServices {
    constructor(private _http: Http) { }
    Get(tid: number): Promise<ITEST> {
        return this._http.get('http://localhost:3592/api/Testservice/Test/' + tid)
            .map((res: Response) => <ITEST>res.json())
            .toPromise();
    }
    Gets(): Observable<ITEST[]> {
        return this._http.get('http://localhost:3592/api/Testservice/Tests')
            .map((res: Response) => <ITEST[]>res.json());
    }
    Save(doc: ITEST): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Post, headers: headerOptions });
        return this._http.post('http://localhost:3592/api/Testservice/Save', JSON.stringify(doc), requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
    Update(doc: ITEST): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
        return this._http.put('http://localhost:3592/api/Testservice/Update/' + doc.TID, JSON.stringify(doc), requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
    Delete(tid: number): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Delete, headers: headerOptions });
        return this._http.delete('http://localhost:3592/api/Testservice/Delete/' + tid, requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
}

Angularjs Componet :

import { Component, OnInit } from '@angular/core';
import { ITEST } from '../test/test.model';
import { TestServices } from '../test/test.service';

@Component({
  selector: 'app-test-create',
  templateUrl: './test-create.component.html',
  styleUrls: ['./test-create.component.css']
})
export class TestCreateComponent implements OnInit {
  TEST: ITEST;
  list: ITEST[];
  constructor(private _ts: TestServices) { }

  ngOnInit() {
    this.reset();
    this.fill();
  }
  save(isValid: boolean): void {
    if (isValid === false) {
      this._ts.Save(this.TEST).then(data => {
        alert(data);
        this.reset();
        this.fill();
      });
    }
  }
  update(isValid: boolean): void {
    if (isValid === false) {
      this._ts.Update(this.TEST).then(data => {
        alert(data);
        this.reset();
        this.fill();
      });
    }
  }
  fill(): void {
    this._ts.Gets().subscribe(data => this.list = data);
  }
  edit(tid: number): void {
    this._ts.Get(tid).then(data => this.TEST = data);
  }
  del(tid: number): void {
    if (confirm('Do you want to delete it ?')) {
      this._ts.Delete(tid).then(data => {
        alert(data);
        this.fill();
      });
    }

  }
  reset(): void {
    this.TEST = {
      TID: null,
      NAME: null,
      GENDER: null,
      SALARY: null,
      DOB: null,
      MARK: null,
      PERCENTAGE: null
    };
  }
}


Angularjs Custom Pipe :

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

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

    }

}



Sunday 1 July 2018

CRUD operation & costume directive in angularjs5 & webapi2


View Model :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication2.Models
{
    public class DOCTORVM
    {
        public int DID { get; set; }
        public string NAME { get; set; }
        public string ADDRESS { get; set; }
        public string PASSWORD { get; set; }
        public string CPASSWORD { get; set; }
        public string GENDER { get; set; }
        public bool? ISMARRIED { get; set; }
        public int? CID { get; set; }
        public int? SID { get; set; }
        public List<int> HLIST { get; set; }
    }
}

Web API :

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

namespace WebApplication2.Controllers
{
    [RoutePrefix("api/Doctorservices")]
    public class DoctorservicesController : ApiController
    {
        [HttpGet]
        [Route("Countries")]
        public IHttpActionResult Countries()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Ok(obj.COUNTRies.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("Hobbies")]
        public IHttpActionResult Hobbies()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Ok(obj.HOBBies.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("Doctors")]
        public IHttpActionResult Doctors()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Ok(obj.DOCTORs.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("Doctor/{DID:int}",Name ="doctor")]
        public IHttpActionResult Doctor(int DID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    DOCTORVM vm = obj.DOCTORs.Select(e => new DOCTORVM { DID = e.DID, NAME = e.NAME, ADDRESS = e.ADDRESS, PASSWORD = e.PASSWORD,CPASSWORD=e.PASSWORD , GENDER = e.GENDER, ISMARRIED = e.ISMARRIED, CID = e.CID, SID = e.SID, HLIST = obj.HMAPs.Where(m => m.STID == DID).Select(p => p.HID.Value).ToList() }).SingleOrDefault(n => n.DID == DID);
                    return Ok(vm);
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("State/{CID:int}")]
        public IHttpActionResult State(int CID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    return Ok(obj.STATEs.Where(e=>e.CID==CID).ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPost]
        [Route("Save")]
        public IHttpActionResult Save(DOCTORVM vm)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    DOCTOR doc = new DOCTOR();
                    doc.DID = vm.DID;
                    doc.NAME = vm.NAME;
                    doc.ADDRESS = vm.ADDRESS;
                    doc.PASSWORD = vm.CPASSWORD;
                    doc.GENDER = vm.GENDER;
                    doc.ISMARRIED = vm.ISMARRIED;
                    doc.ISMARRIED = vm.ISMARRIED;
                    doc.CID = vm.CID;
                    doc.SID = vm.SID;
                    obj.DOCTORs.Add(doc);
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.HLIST.Select(e => new HMAP { HID = e, STID = vm.DID }));
                    obj.SaveChanges();
                    return Created(new Uri(Url.Link("doctor", new { DID = vm.DID })),"Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPut]
        [Route("Update/{DID:int}")]
        public IHttpActionResult Update([FromUri]int DID,[FromBody]DOCTORVM vm)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    DOCTOR doc = obj.DOCTORs.Find(DID);
                    doc.NAME = vm.NAME;
                    doc.ADDRESS = vm.ADDRESS;
                    doc.GENDER = vm.GENDER;
                    doc.ISMARRIED = vm.ISMARRIED;
                    doc.ISMARRIED = vm.ISMARRIED;
                    doc.CID = vm.CID;
                    doc.SID = vm.SID;
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.STID == DID));
                    obj.SaveChanges();
                    obj.HMAPs.AddRange(vm.HLIST.Select(e => new HMAP { HID = e, STID = vm.DID }));
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpDelete]
        [Route("Delete/{DID:int}")]
        public IHttpActionResult Delete([FromUri]int DID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    DOCTOR doc = obj.DOCTORs.Find(DID);
                    obj.DOCTORs.Remove(doc);
                    obj.SaveChanges();
                    obj.HMAPs.RemoveRange(obj.HMAPs.Where(e => e.STID == DID));
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }




    }
}


Angularjs View :

<form #frmDoct="ngForm" class="form-horizontal">
    <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" name="DID" [(ngModel)]="DOCTOR.DID" #DID="ngModel" class="form-control" required />
            <span class="help-block" *ngIf="DID.invalid && DID.touched">DID should be not blank.</span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="NAME.invalid && NAME.touched" [class.has-success]="NAME.valid">
        <label class="control-label col-lg-4">NAME</label>
        <div class="col-lg-4">
            <input type="text" name="NAME" [(ngModel)]="DOCTOR.NAME" #NAME="ngModel" class="form-control" required />
            <span class="help-block" *ngIf="NAME.invalid && NAME.touched">Name should be not blank.</span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="ADDRESS.invalid && ADDRESS.touched" [class.has-success]="ADDRESS.valid">
        <label class="control-label col-lg-4">ADDRESS</label>
        <div class="col-lg-4">
            <textarea name="ADDRESS" [(ngModel)]="DOCTOR.ADDRESS" #ADDRESS="ngModel" class="form-control" required ></textarea>
            <span class="help-block" *ngIf="ADDRESS.invalid && ADDRESS.touched">Address should be not blank.</span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="PASSWORD.invalid && PASSWORD.touched" [class.has-success]="PASSWORD.valid">
        <label class="control-label col-lg-4">PASSWORD</label>
        <div class="col-lg-4">
            <input type="password" name="PASSWORD" minlength="6"  [(ngModel)]="DOCTOR.PASSWORD" #PASSWORD="ngModel" class="form-control" required />
            <span class="help-block">
                <span *ngIf="PASSWORD.errors?.required && PASSWORD.touched">Password should be not blank.</span>
                <span *ngIf="PASSWORD.errors?.minlength && PASSWORD.touched">Password min length is 6.</span>
            </span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="CPASSWORD.invalid && CPASSWORD.touched" [class.has-success]="CPASSWORD.valid">
        <label class="control-label col-lg-4">CONFIRM PASSWORD</label>
        <div class="col-lg-4">
            <input type="password" name="CPASSWORD" minlength="6" appCompareValidator="PASSWORD"  [(ngModel)]="DOCTOR.CPASSWORD" #CPASSWORD="ngModel" class="form-control" required />
            <span class="help-block">
                <span *ngIf="CPASSWORD.errors?.required && CPASSWORD.touched">Confirm password should be not blank.</span>
                <span *ngIf="CPASSWORD.errors?.minlength && CPASSWORD.touched">Confirm password min length is 6.</span>
                <span *ngIf="CPASSWORD.errors?.notEqual  && CPASSWORD.touched && !CPASSWORD.errors?.minlength &&  !CPASSWORD.errors?.required">Password and confirm pasword must be same.</span>
            </span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="GENDER.invalid && GENDER.touched" [class.has-success]="GENDER.valid">
        <label class="control-label col-lg-4">GENDER</label>
        <div class="col-lg-4">
            <input type="radio" name="GENDER" [(ngModel)]="DOCTOR.GENDER" #GENDER="ngModel" value="Male" required />Male
            <input type="radio" name="GENDER" [(ngModel)]="DOCTOR.GENDER" #GENDER="ngModel" value="Female" required />Female
            <span class="help-block" *ngIf="GENDER.invalid && GENDER.touched">Please select a gender.</span>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-lg-4">ARE YOU MARRIED ?</label>
        <div class="col-lg-4">
            <input type="checkbox" name="ISMARRIED" [(ngModel)]="DOCTOR.ISMARRIED" #ISMARRIED="ngModel"/>
        </div>
    </div>
    <div class="form-group" [class.has-error]="CID.invalid && CID.touched" [class.has-success]="CID.valid">
        <label class="control-label col-lg-4">COUNTRY</label>
        <div class="col-lg-4">
            <select name="CID" (change)="fillddl()" [(ngModel)]="DOCTOR.CID" #CID="ngModel" class="form-control" required >
                <option [ngValue]="null">Select</option>
                <option *ngFor="let c of listc" [value]="c.CID">{{c.CNAME}}</option>
            </select>
            <span class="help-block" *ngIf="CID.invalid && CID.touched">Please select a country.</span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="SID.invalid && SID.touched" [class.has-success]="SID.valid">
        <label class="control-label col-lg-4">STATE</label>
        <div class="col-lg-4">
            <select name="SID" [(ngModel)]="DOCTOR.SID" #SID="ngModel" class="form-control" required>
                <option [ngValue]="null">Select</option>
                <option *ngFor="let c of lists" [value]="c.SID">{{c.SNAME}}</option>
            </select>
            <span class="help-block" *ngIf="SID.invalid && SID.touched">Please select a state.</span>
        </div>
    </div>
    <div class="form-group" [class.has-error]="HLIST.invalid && HLIST.touched" [class.has-success]="HLIST.valid">
        <label class="control-label col-lg-4">HOBBY</label>
        <div class="col-lg-4">
            <select name="HLIST" multiple [(ngModel)]="DOCTOR.HLIST" #HLIST="ngModel" class="form-control" required>
                <option *ngFor="let c of listh" [value]="c.HID">{{c.HNAME}}</option>
            </select>
            <span class="help-block" *ngIf="HLIST.invalid && HLIST.touched">Please select a hobby.</span>
        </div>
    </div>
    <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" class="btn btn-primary" (click)="save(frmDoct.invalid)" />
            <input type="button" value="Update" style="width:80px" class="btn btn-primary" (click)="update(frmDoct.invalid)" />
            <input type="button" value="Reset" style="width:80px" class="btn btn-primary" (click)="reset()" />
           
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-lg-4"></label>
        <div class="col-lg-4">
            <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
                <thead class="bg bg-primary">
                    <tr>
                        <th>DID</th>
                        <th>NAME</th>
                        <th>ACTION</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let c of list">
                        <td>{{c.DID}}</td>
                        <td>{{c.NAME}}</td>
                        <td>
                            <a (click)="edit(c.DID)">Edit</a> |
                            <a (click)="del(c.DID)">Delete</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</form>

Angularjs Costume Directive :

import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
import { Directive, Input } from '@angular/core';

@Directive({
    selector: '[appCompareValidator]',
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: CompareDirective,
        multi: true
    }]
})
export class CompareDirective implements Validator {
    @Input() appCompareValidator: string;
    validate(control: AbstractControl): { [key: string]: any } | null {
        const controlToCompare = control.parent.get(this.appCompareValidator);
        if (controlToCompare && controlToCompare.value !== control.value) {
            return { 'notEqual': true };
        }

        return null;
    }
}

Angularjs Model :

export interface Idoctor {
    DID: number;
    NAME: string;
    ADDRESS: string;
    PASSWORD: string;
    CPASSWORD: string;
    GENDER: string;
    ISMARRIED: boolean;
    CID: number;
    SID: number;
    HLIST: number[];
}

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

export interface Istate {
    SID: number;
    SNAME: string;
    CID: number;
}

export interface Ihobby {
    HID: number;
    HNAME: string;
    STATUS: boolean;
}

Angularjs Services :

import { Injectable } from '@angular/core';
import { Idoctor, Icountry, Istate, Ihobby } from './doctor.model';
import { Http, Headers, Request, RequestMethod, Response, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';


@Injectable()
export class DoctorService {
    constructor(private _http: Http) { }
    Getc(): Promise<Icountry[]> {
        return this._http.get('http://localhost:3592/api/Doctorservices/Countries')
            .map((res: Response) => <Icountry[]>res.json())
            .toPromise();
    }
    Geth(): Promise<Ihobby[]> {
        return this._http.get('http://localhost:3592/api/Doctorservices/Hobbies')
            .map((res: Response) => <Ihobby[]>res.json())
            .toPromise();
    }
    Getd(): Promise<Idoctor[]> {
        return this._http.get('http://localhost:3592/api/Doctorservices/Doctors')
            .map((res: Response) => <Idoctor[]>res.json())
            .toPromise();
    }
    Get(did: number): Promise<Idoctor> {
        return this._http.get('http://localhost:3592/api/Doctorservices/Doctor/' + did)
            .map((res: Response) => <Idoctor>res.json())
            .toPromise();
    }
    Gets(cid: number): Promise<Istate[]> {
        return this._http.get('http://localhost:3592/api/Doctorservices/State/' + cid)
            .map((res: Response) => <Istate[]>res.json())
            .toPromise();
    }
    Save(doc: Idoctor): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Post, headers: headerOptions });
        return this._http.post('http://localhost:3592/api/Doctorservices/Save', JSON.stringify(doc), requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
    Update(doc: Idoctor): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
        return this._http.put('http://localhost:3592/api/Doctorservices/Update/' + doc.DID, JSON.stringify(doc), requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
    Delete(did: number): Promise<string> {
        const headerOptions = new Headers({ 'Content-Type': 'application/json', cache: false });
        const requestOptions = new RequestOptions({ method: RequestMethod.Delete, headers: headerOptions });
        return this._http.delete('http://localhost:3592/api/Doctorservices/Delete/' + did, requestOptions)
            .map((res: Response) => <string>res.json())
            .toPromise();
    }
}

Angularjs Component:

import { Component, OnInit } from '@angular/core';
import { Idoctor, Icountry, Istate, Ihobby } from '../doctors/doctor.model';
import { DoctorService } from './doctor.services';

@Component({
  selector: 'app-doctor-create',
  templateUrl: './doctor-create.component.html',
  styleUrls: ['./doctor-create.component.css']
})
export class DoctorCreateComponent implements OnInit {
  DOCTOR: Idoctor;
  listc: Icountry[];
  lists: Istate[];
  listh: Ihobby[];
  list: Idoctor[];

  constructor(private ds: DoctorService) { }

  ngOnInit() {
    this.reset();
    this.fill();
  }
  fx(cid: number): void {
    this.ds.Gets(cid).then(data => {
      if (data == null) {
        alert('Service return null value.');
      } else {
        this.lists = data;
      }
    });
  }
  fillddl(): void {
    this.fx(this.DOCTOR.CID);
  }
  reset(): void {
    this.DOCTOR = {
      DID: null,
      NAME: null,
      ADDRESS: null,
      PASSWORD: null,
      CPASSWORD: null,
      GENDER: null,
      ISMARRIED: true,
      CID: null,
      SID: null,
      HLIST: []
    };
    this.ds.Getc().then(data => {
      if (data == null) {
        alert('Service return null value.');
      } else {
        this.listc = data;
      }
    });
    this.ds.Geth().then(data => {
      if (data == null) {
        alert('Service return null value.');
      } else {
        this.listh = data;
      }
    });
  }
  fill(): void {
    this.ds.Getd().then(data => this.list = data);
  }
  edit(id: number): void {
    this.ds.Get(id).then(data => {
      this.fx(data.CID);
      this.DOCTOR = data;
    });
  }
  del(id: number): void {
    if (confirm('Do you want to delete it ?')) {
      this.ds.Delete(id).then(data => {
        alert(data);
        this.fill();
      });
    }

  }
  save(isValid: boolean): void {
    if (isValid === false) {
      this.ds.Save(this.DOCTOR).then(data => {
        alert(data);
        this.reset();
        this.fill();
      });
    }
  }
  update(isValid: boolean): void {
    if (isValid === false) {
      this.ds.Update(this.DOCTOR).then(data => {
        alert(data);
        this.reset();
        this.fill();
      });
    }
  }
}