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 { }




No comments:

Post a Comment