We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Thursday, December 27, 2018

CRUD operation in Angular 7 using Web api and Sql Database


Hi, Today I am going to perform crud operation in Angular 7 using web API and database of SQL Server. Here we will create API and then we will consume the API using Angular 7. And we will use Angular Material theme, It will help us to create a rich, interactive and device-oriented UI for our Web app. And we will see, How to check validation of the fields. We will write angular code by using visual studio code. In visual studio code, we can Generate components, routes, services and pipes in easy way with a simple command. Now Let's see step by step.
Step1:

First we will create a database and table using SQL database.

Now, open SQL Server and create a table like below image.






Step2:

Now, we will create web API for Create, Replace, Update and Delete (CRUD) operations. So open visual studio >> file >> new >> project >> Select Web Application. After that click ok and we can see a window then select WebAPI in window template.



Click Ok


Step3:

Now, we will go in models folder >> Right click >>Add >> New Item >> select Data in left panel >>ADO.NET Entity Data Model 



Now, click Add button then select EF Designer from database >> Next >> After that give your sql credential and select database. Then click Add button and select your table and click finish button

Note: Here, I am using database first approach but we can use also code first approach according to our requirement.

Step 4:

Now, we will write code to perform CRUD operation. So go the Controller folder in our API Application and right click >> Add >> Controller >> Select Web API 2 Controller-Empty 




Now, go our controller class  and set the routing for more user friendly and write below code.


using System;
using System.Linq;
using System.Web.Http;
using CRUDAPI.Models;

namespace CRUDAPI.Controllers
{
    [RoutePrefix("Api/Employee")]
    public class EmployeeAPIController : ApiController
    {
        WebApiDbEntities objEntity = new WebApiDbEntities();
       
        [HttpGet]
        [Route("AllEmployeeDetails")]
        public IQueryable<EmployeeDetail> GetEmaployee()
        {
            try
            {
                return objEntity.EmployeeDetails;
            }
            catch(Exception)
            {
                throw;
            }
        }

        [HttpGet]
        [Route("GetEmployeeDetailsById/{employeeId}")]
        public IHttpActionResult GetEmaployeeById(string employeeId)
        {
            EmployeeDetail objEmp = new EmployeeDetail();
            int ID = Convert.ToInt32(employeeId);
            try
            {
                 objEmp = objEntity.EmployeeDetails.Find(ID);
                if (objEmp == null)
                {
                    return NotFound();
                }

            }
            catch (Exception)
            {
                throw;
            }
          
            return Ok(objEmp);
        }

        [HttpPost]
        [Route("InsertEmployeeDetails")]
        public IHttpActionResult PostEmaployee(EmployeeDetail data)
        {
           
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {
                objEntity.EmployeeDetails.Add(data);
                objEntity.SaveChanges();
            }
            catch(Exception)
            {
                throw;
            }



            return Ok(data);
        }
       
        [HttpPut]
        [Route("UpdateEmployeeDetails")]
        public IHttpActionResult PutEmaployeeMaster(EmployeeDetail employee)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                EmployeeDetail objEmp = new EmployeeDetail();
                objEmp = objEntity.EmployeeDetails.Find(employee.EmpId);
                if (objEmp != null)
                {
                    objEmp.EmpName = employee.EmpName;
                    objEmp.Address = employee.Address;
                    objEmp.EmailId = employee.EmailId;
                    objEmp.DateOfBirth = employee.DateOfBirth;
                    objEmp.Gender = employee.Gender;
                    objEmp.PinCode = employee.PinCode;

                }
                int i = this.objEntity.SaveChanges();

            }
            catch(Exception)
            {
                throw;
            }
            return Ok(employee);
        }
        [HttpDelete]
        [Route("DeleteEmployeeDetails")]
        public IHttpActionResult DeleteEmaployeeDelete(int id)
        {
            //int empId = Convert.ToInt32(id);
            EmployeeDetail emaployee = objEntity.EmployeeDetails.Find(id);
            if (emaployee == null)
            {
                return NotFound();
            }

            objEntity.EmployeeDetails.Remove(emaployee);
            objEntity.SaveChanges();

            return Ok(emaployee);
        }
    }

}

Step:5

We have finished API part. Now, we will create Angular part i.e. we will consume API using angular 7 and we will use visual studio code editor. If you don't have Visual studio code in your system then first you have to download and install. For download you go this link.

First we have to make sure our system has installed of angular CLI  or not.  If don't have installed then first we need to install.

Open command prompt and type below code and press enter

npm install -g @angular/cli


Now, open visual studio code and create project name.

Open TERMINAL in visual studio code and type below syntax in command for create a project 


ng new AngularCRUD 


After that, hit Enter. it will take a little bit time after that we can see the our project name






Now , we can create a component any meaning full name and related to our functionality. I will create a component with employee name

So, again go to the TERMINAL and go our angular project location using below command

cd projectName



now we will write a command for create a component 

ng g c employee 

Press enter

Note: you can use c or component fir create component

Step:6

Now, we will create a service 

Open the TERMINAL and write below command

ng g s employee

Press Enter and you can see it will create two files




Now, we will create a class like model class. Open TERMINAL and write below command.

ng g class employee


Now write all properties in employee class to related Employee.


export class Employee {
    EmpId: string;
    EmpName: string;
    DateOfBirth: Date;
    EmailId: string;
    Gender: string;
    Address: string;
    PinCode: string;
}

Now open employee.service.ts and first import necessary class and library


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Employee } from './employee';

After that we write all methods related to consume web in employee.service.ts
 @Injectable({
  providedIn: 'root'
})

export class EmployeeService {
  url = 'http://localhost:65389/Api/Employee';
  constructor(private http: HttpClient) { }
  getAllEmployee(): Observable<Employee[]> {
    return this.http.get<Employee[]>(this.url + '/AllEmployeeDetails');
  }
  getEmployeeById(employeeId: string): Observable<Employee> {
    return this.http.get<Employee>(this.url + '/GetEmployeeDetailsById/' + employeeId);
  }
  createEmployee(employee: Employee): Observable<Employee> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.post<Employee>(this.url + '/InsertEmployeeDetails/',
    employee, httpOptions);
  }
  updateEmployee(employee: Employee): Observable<Employee> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.put<Employee>(this.url + '/UpdateEmployeeDetails/',
    employee, httpOptions);
  }
  deleteEmployeeById(employeeid: string): Observable<number> {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    return this.http.delete<number>(this.url + '/DeleteEmployeeDetails?id=' + employeeid,
 httpOptions);
  }

}

Now, we are done with our service related code but, we have to consume api from other port or domain. So, angular will block the URL and we called this issue as CORS(Cross Origin Resource Sharing).

First, we will see how to resolve this problem?

Now, we will go in to our web API project.

For that, we have to download "CORS" in Web API project. Go to NuGet Package Manager and download the following file.



After that, go to App_Start folder in Web API project and then WebApiConfig.cs class. Here, modify the Register method with the below code.

Add namespace.


    using System.Web.Http.Cors;

var cors = new EnableCorsAttribute("*","*","*");//origins,headers,methods 

            config.EnableCors(cors);


Step:7

Now, we will do design part using html and also we will use Angular Material theme for create a rich, interactive and device-oriented UI for our Web app.

Before that ,we have to install Angular Material theme. For installing this theme open TERMINAL and write the below code.



npm install --save @angular/material @angular/cdk @angular/animations
If you want to more details about angular material then go this link

After installed we can check in package.json file




After that, we will import all library in app.module.ts and also import for date picker because we will use date picker for using date of birth 

Now, open app.module.ts class and write below code


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { EmployeeService } from './employee.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import {
  MatButtonModule, MatMenuModule, MatDatepickerModule, MatNativeDateModule , MatIconModule, MatCardModule, MatSidenavModule, MatFormFieldModule,
  MatInputModule, MatTooltipModule, MatToolbarModule
} from '@angular/material';
import { MatRadioModule } from '@angular/material/radio';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EmployeeComponent } from './employee/employee.component';

@NgModule({
  declarations: [
    AppComponent,
    EmployeeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    MatButtonModule,
    MatMenuModule,
    MatDatepickerModule,
    MatNativeDateModule,
    MatIconModule,
    MatRadioModule,
    MatCardModule,
    MatSidenavModule,
    MatFormFieldModule,
    MatInputModule,
    MatTooltipModule,
    MatToolbarModule,
    AppRoutingModule
  ],
  providers: [HttpClientModule, EmployeeService,MatDatepickerModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now we have to import library in styles.css file

@import '@angular/material/prebuilt-themes/indigo-pink.css';

Step:8

Now, we will design our html page.

Open employee.component.html  and write below code

<div class="container">

<mat-card>
  <mat-toolbar color="accent">
    <div align="center" style="color:white;text-align: right;">
      CRUD operation in Angular 7 using Web api and Sql Database
    </div>  
  </mat-toolbar>
<br><br>
  <mat-card-content>
    <form [formGroup]="employeeForm" (ngSubmit)="onFormSubmit(employeeForm.value)">
            <table>
              <tr>
                <td class="tbl1">
                  <mat-form-field class="demo-full-width">
                    <input formControlName="EmpName" matTooltip="Enter Employee Name" matInput placeholder="Employee Name">
                  </mat-form-field>
                  <mat-error>
                    <span *ngIf="!employeeForm.get('EmpName').value && employeeForm.get('EmpName').touched"></span>
                  </mat-error>
                </td>
                <td class="tbl1">
                  <mat-form-field class="demo-full-width">
                    <input matInput [matDatepicker]="picker" matTooltip="Enter Date Of Birth" formControlName="DateOfBirth" placeholder="Choose Date Of Birth">
                    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                    <mat-datepicker #picker></mat-datepicker>
                  </mat-form-field>
                  <mat-error>
                    <span *ngIf="!employeeForm.get('DateOfBirth').value && employeeForm.get('DateOfBirth').touched"></span>
                  </mat-error>
                </td>
                <td class="tbl1">
                  <mat-form-field class="demo-full-width">
                    <input formControlName="EmailId" matTooltip="Enter EmailId" matInput placeholder="EmailId">
                  </mat-form-field>
                  <mat-error>
                    <span *ngIf="!employeeForm.get('EmailId').value && employeeForm.get('EmailId').touched"></span>
                  </mat-error>
                </td>
              </tr>
              <tr>
                <td class="tbl1">
                  <span>Gender</span>
                  <br><br>
                  <mat-radio-group matTooltip="Enter Gender" formControlName="Gender">
                      <mat-radio-button value="0">Male</mat-radio-button>&nbsp;&nbsp;
                      <mat-radio-button value="1">Female</mat-radio-button>
                    </mat-radio-group>
                  <mat-error>
                    <span *ngIf="!employeeForm.get('Gender').value && employeeForm.get('Gender').touched"></span>
                  </mat-error>
                </td>
                <td class="tbl1">
                  <mat-form-field class="demo-full-width">
                    <input matTooltip="Enter Address" formControlName="Address" matInput placeholder="Address">
                  </mat-form-field>
                  <mat-error>
                    <span *ngIf="!employeeForm.get('Address').value && employeeForm.get('Address').touched"></span>
                  </mat-error>
                </td>
                <td class="tbl1">
                  <mat-form-field class="demo-full-width">
                    <input formControlName="PinCode" matTooltip="Enter Pine Code" matInput placeholder="PinCode">
                  </mat-form-field>
                  <mat-error>
                    <span *ngIf="!employeeForm.get('PinCode').value && employeeForm.get('PinCode').touched"></span>
                  </mat-error>
                </td>
              </tr>
              <tr>
                <td></td>
                <td  class="content-center">
                  <button type="submit" mat-raised-button color="accent" matTooltip="Click Submit Button" [disabled]="!employeeForm.valid">Submit</button>&nbsp;&nbsp;&nbsp;&nbsp;
                  <button type="reset" mat-raised-button color="accent" matTooltip="Click Reset Button" (click)="resetForm()">Reset</button>
                </td>
                <td>
                  <p *ngIf="dataSaved" style="color:rgb(0, 128, 0);font-size:20px;font-weight:bold" Class="success" align="left">
                    {{massage}}
                  </p>
                </td>
              </tr>
            </table>
<br><br>
      <table class="table" >
          <tr ngclass="btn-primary">
            <th class="tbl2">Employee Name</th>
            <th class="tbl2">Date Of Birth</th>
            <th class="tbl2">Email Id</th>
            <th class="tbl2">Gender</th>
            <th class="tbl2">Address</th>
            <th class="tbl2">Pine Code</th>
            <th class="tbl2">Edit</th>
            <th class="tbl2">Delete</th>
          </tr>
          <tr *ngFor="let employee of allEmployees | async">
            <td class="tbl2">{{employee.EmpName}}</td>
            <td class="tbl2">{{employee.DateOfBirth | date }}</td>
            <td class="tbl2">{{employee.EmailId}}</td>
            <td class="tbl2">{{employee.Gender ==0? 'Male' : 'Female'}}</td>
            <td class="tbl2">{{employee.Address}}</td>
            <td class="tbl2">{{employee.PinCode}}</td>
            <td class="tbl2">
              <button type="button" class="btn btn-info" matTooltip="Click Edit Button" (click)="loadEmployeeToEdit(employee.EmpId)">Edit</button>
            </td>
            <td class="tbl2">
              <button type="button" class="btn btn-danger" matTooltip="Click Delete Button" (click)="deleteEmployee(employee.EmpId)">Delete</button>
            </td>
          </tr>

        </table>
    </form>
  </mat-card-content>
</mat-card>
</div>


Step9:

Now, open the app.component.html and write below code


<p>

  <app-employee></app-employee>
</p>

Step10:

Open employee.component.ts file and write below code

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { EmployeeService } from '../employee.service';
import { Employee } from '../employee';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  dataSaved = false;
  employeeForm: any;
  allEmployees: Observable<Employee[]>;
  employeeIdUpdate = null;
  massage = null;

  constructor(private formbulider: FormBuilder, private employeeService: EmployeeService) { }

  ngOnInit() {
    this.employeeForm = this.formbulider.group({
      EmpName: ['', [Validators.required]],
      DateOfBirth: ['', [Validators.required]],
      EmailId: ['', [Validators.required]],
      Gender: ['', [Validators.required]],
      Address: ['', [Validators.required]],
      PinCode: ['', [Validators.required]],
    });
    this.loadAllEmployees();
  }
  loadAllEmployees() {
    this.allEmployees = this.employeeService.getAllEmployee();
  }
  onFormSubmit() {
    this.dataSaved = false;
    const employee = this.employeeForm.value;
    this.CreateEmployee(employee);
    this.employeeForm.reset();
  }
  loadEmployeeToEdit(employeeId: string) {
    this.employeeService.getEmployeeById(employeeId).subscribe(employee => {
      this.massage = null;
      this.dataSaved = false;
      this.employeeIdUpdate = employee.EmpId;
      this.employeeForm.controls['EmpName'].setValue(employee.EmpName);
      this.employeeForm.controls['DateOfBirth'].setValue(employee.DateOfBirth);
      this.employeeForm.controls['EmailId'].setValue(employee.EmailId);
      this.employeeForm.controls['Gender'].setValue(employee.Gender);
      this.employeeForm.controls['Address'].setValue(employee.Address);
      this.employeeForm.controls['PinCode'].setValue(employee.PinCode);
    });

  }
  CreateEmployee(employee: Employee) {
    if (this.employeeIdUpdate == null) {
      this.employeeService.createEmployee(employee).subscribe(
        () => {
          this.dataSaved = true;
          this.massage = 'Record saved Successfully';
          this.loadAllEmployees();
          this.employeeIdUpdate = null;
          this.employeeForm.reset();
        }
      );
    } else {
      employee.EmpId = this.employeeIdUpdate;
      this.employeeService.updateEmployee(employee).subscribe(() => {
        this.dataSaved = true;
        this.massage = 'Record Updated Successfully';
        this.loadAllEmployees();
        this.employeeIdUpdate = null;
        this.employeeForm.reset();
      });
    }
  } 
  deleteEmployee(employeeId: string) {
    if (confirm("Are you sure you want to delete this ?")) { 
    this.employeeService.deleteEmployeeById(employeeId).subscribe(() => {
      this.dataSaved = true;
      this.massage = 'Record Deleted Succefully';
      this.loadAllEmployees();
      this.employeeIdUpdate = null;
      this.employeeForm.reset();

    });
  }
}
  resetForm() {
    this.employeeForm.reset();
    this.massage = null;
    this.dataSaved = false;
  }
}

Step11:

We have completed  all code functionality for our CRUD operation.  Now we will run and check the output.

Before  running the application  first save all files and then go to the TERMINAL and write the command for run the program.

ng serve -o


After that we can see the our output like below image.




Finally,We have completed CRUD operation using web api with  sql database and Angular 7 with Angular Material. Thank you for reading my article.


5 comments:

Unknown said...

where can i get the source code for the entire application.

Mithilesh Tech Solution said...
This comment has been removed by the author.
Mithilesh Tech Solution said...

Click below link and you go this site and you can on top, a download option.
https://www.c-sharpcorner.com/article/crud-operation-in-angular-7-using-web-api/

Unknown said...

Thank you for your prompt reply.

Unknown said...

Nice blog thank you for sharing with us angularjs online course