Create WebAPI Application
New-> Web->ASP.Net WebApplication –“WebAPI” -> OK
Select WebAPI OK

Create Database called “WebAPIDB”
USE [WebAPIDB]
GO

/****** Object:  Table [dbo].[Employee]    Script Date: 1/8/2020 9:46:07 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Employee](
       [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
       [FirstName] [varchar](50) NULL,
       [LastName] [varchar](50) NULL,
       [EmpCode] [varchar](50) NULL,
       [Position] [varchar](50) NULL,
       [Office] [varchar](50) NULL,
PRIMARY KEY CLUSTERED
(
       [EmployeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Add ADO.Net Model
Model right click -> add ADO.Net Entity data model -> “DBModels”-> Generate from database-> Build app
Right click on Controllers-> add “web api 2 controller with actions entity framework”
Controller name => “EmployeeController”
Model Class: “Employee (WebAPI.Models)
Data context: DBModel (WebAPI.Models)
Remove (ModelState.IsValid) statements
Create angular application “ng new angularCRUD”
To run “ng serve –open”
Generate component “gn g c employees” -> Remove TS file
Right click on Employees folder and open terminal create two components
“Ng g c employee” & “ng g c employee-list”
Create folder called “shared” ->then create service class “ng g s employee”, remove test file
Create model class -> “ng g class employee.model” -> remove .Model in ts file.
Add following code in model class
export class Employee{
  EmployeeIDnumber;
  FirstNamestring;
  LastNamestring;
  EmpCodestring;
  Positionstring;
  Officestring;
}


npm install @angular/http@latest
npm install ngx-toastr --save

Open Getbootstrap.com -> click get started copy css cdn path and add in index.html
Index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularCRUD</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
</head>
<body>
  <app-root></app-root>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
</body>
</html>

appComponent.html
<div class="container">
  <app-employees ></app-employees>
</div>


Employeescomponent.html
<div style="text-align: center;">
  <h2 class="jumbotron bg-secondary text-white">
    Employee Register
  </h2>
</div>
<div class="row">
  <div class="col-md-6">
    <app-employee></app-employee>
  </div>
  <div class="col-md-6">
    <app-employee-list></app-employee-list>
  </div>
</div>


Employees.component.ts
import { ComponentOnInit } from '@angular/core';
import { EmployeeService } from './shared/employee.service';

@Component({
  selector: 'app-employees',
  templateUrl: './employees.component.html',
  styleUrls: ['./employees.component.css'],
  providers:[EmployeeService]
})
export class EmployeesComponent implements OnInit {

  constructor(private employeeServiceEmployeeService) { }

  ngOnInit() {
  }

}


EmployeeService.ts
import { Injectable } from '@angular/core';

import { Employee } from './employee.model';

import { HttpResponseHeadersRequestOptionsRequestMethodRequest } from '@angular/http';
import { Observable } from 'rxjs';
import { mapfilterscan } from 'rxjs/operators';
//import 'rxjs/add/operator/map';
//import 'rxjs/add/operator/toPromise';

//import './rxjs-operators';

@Injectable()
export class EmployeeService {
  selectedEmployeeEmployee;
  employeeListEmployee[];

  constructor(private httpHttp) { }

  postEmployee(empEmployee) {
    var body = JSON.stringify(emp);
    var headerOptions = new Headers({ 'content-type': 'application/json' });
    var requestOptions = new RequestOptions({ method: RequestMethod.Postheaders: headerOptions });
    return this.http.post('http://localhost:52537/api/Employees'bodyrequestOptions).pipe(map(x => x.json()));
  }

  putEmployee(idemp) {
    var body = JSON.stringify(emp);
    var headerOptions = new Headers({ 'content-type': 'application/json' });
    var requestOptions = new RequestOptions({ method: RequestMethod.Putheaders: headerOptions });
    return this.http.post('http://localhost:52537/api/Employees/' + idbodyrequestOptions).pipe(map(x => x.json()));
  }

  getEmployeeList() {
    this.http.get('http://localhost:52537/api/Employees').pipe(map((dataResponse=> { return data.json() as Employee[]; })).toPromise().then(x => { this.employeeList = x; })
  }

  deleteEmployee(idnumber) {
    return this.http.delete('http://localhost:52537/api/Employees/' + id).pipe(map(res => res.json()));
  }
}


Employee.component.html
<form class="emp-form" #employeeForm="ngForm" (ngSubmit)="onSubmit(employeeForm)">
  <input type="hidden" name="EmployeeID" #EmployeeID="ngModel" [(ngModel)]="employeeService.selectedEmployee.EmployeeID"/>
  <div class="form-row">
    <div class="form-group col-md-6">
      <input type="text" class="form-control" name="FirstName" #FirstName="ngModel" [(ngModel)]="employeeService.selectedEmployee.FirstName" placeholder="First Name" required />
      <div class="validation-error" *ngIf="FirstName.invalid && FirstName.touched">This Field is Required</div>
    </div>
    <div class="form-group col-md-6">
      <input class="form-control" name="LastName" #LastName="ngModel" [(ngModel)]="employeeService.selectedEmployee.LastName" placeholder="Last Name" required/>
      <div class="validation-error" *ngIf="LastName.invalid && LastName.touched">This Field is Required</div>
    </div>
  </div>
  
  <div class="form-group">
    <input type="text" class="form-control" name="Position" #Position="ngModel" [(ngModel)]="employeeService.selectedEmployee.Position" placeholder="Position" />
  </div>

  <div class="form-row">
    <div class="form-group col-md-6">
      <input type="text" class="form-control" name="EmpCode" #EmpCode="ngModel" [(ngModel)]="employeeService.selectedEmployee.EmpCode" placeholder="Emp Code" />
    </div>
    <div class="form-group col-md-6">
      <input type="text" class="form-control" name="Office" #Office="ngModel" [(ngModel)]="employeeService.selectedEmployee.Office" placeholder="Office" />
    </div>
  </div>

  <div class="form-row">
    <div class="form-group col-md-6">
      
    </div>
    <div class="form-group col-md-3">
      <button [disabled]="!employeeForm.valid" type="submit" class="btn btn-lg btn-block btn-info"><i class="fa fa-floppy-o"></i>Submit</button>
    </div>
    <div class="form-group col-md-3">
      <button type="button" class="btn btn-lg btn-block btn-secondary" (click)="resetForm(employeeForm)"><i class="fa fa-repeat"></i>Reset</button>
    </div>
  </div>
</form>


Employee.component.ts
import { ComponentOnInit } from '@angular/core';
import { EmployeeService } from '../shared/employee.service';
import { NgForm } from '@angular/forms';

import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {

  constructor(private employeeServiceEmployeeServiceprivate toastrToastrService) { }

  ngOnInit() {
    this.resetForm();
  }

  resetForm(form?: NgForm) {
    if (form != null)
    form.reset();
    this.employeeService.selectedEmployee = {
      EmployeeID: null,
      FirstName: '',
      LastName: '',
      EmpCode: '',
      Position: '',
      Office: ''
    }
  }

  onSubmit(formNgForm) {
    debugger;
    if (form.value.EmployeeID == null) {
      this.employeeService.postEmployee(form.value).subscribe(data => {
        this.resetForm(form);
        this.employeeService.getEmployeeList();
        this.toastr.success('New Record Added Successfully.''Employee Register');
      })
    }
    else {
      this.employeeService.putEmployee(form.value.EmployeeIDform.value).subscribe(data => {
        this.resetForm(form);
        this.employeeService.getEmployeeList();
        this.toastr.info('Record Updated Successfully.''Employee Register');
      })
    }
  }
}


Employee-list.component.html
<br />
<div>
  <table class="table table-sm table-hover table-striped">
    <tr>
      <th scope="col">Employee Name</th>
      <th scope="col">Employee Code</th>
      <th scope="col">Position</th>
      <th scope="col">Office</th>
      <th scope="col">Edit / Delete</th>
    </tr>
    <tr *ngFor="let employee of employeeService.employeeList">
      <td>{{employee.FirstName}} - {{employee.LastName}}</td>
      <td>{{employee.EmpCode}}</td>
      <td>{{employee.Position}}</td>
      <td>{{employee.Office}}</td>
      <td>
        <a class="btn" (click)="showForEdit(employee)">
          <i class="fa fa-pencil-square-o"></i>
        </a>
        <a class="btn text-danger" (click)="onDelete(employee.EmployeeID)">
          <i class="fa fa-trash-o"></i>
        </a>
      </td>
    </tr>
  </table>
</div>


Employee-list.component.ts
import { ComponentOnInit } from '@angular/core';

import { EmployeeService } from '../shared/employee.service';
import { Employee } from '../shared/employee.model';

import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {

  constructor(private employeeServiceEmployeeServiceprivate toastrToastrService) { }

  ngOnInit() {
    this.employeeService.getEmployeeList();
  }

  showForEdit(empEmployee) {
    this.employeeService.selectedEmployee = Object.assign({},emp);
  }

  onDelete(idnumber) {
    if (confirm('Are you sure you want to delete?') == true) {
      this.employeeService.deleteEmployee(id).subscribe(x => {
        this.employeeService.getEmployeeList();
        this.toastr.warning('Record Deleted Successfully.''Employee Register');
      })
    }
  }
}




App.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

import { EmployeesComponent } from './employees/employees.component';
import { EmployeeListComponent } from './employees/employee-list/employee-list.component';
import { EmployeeComponent } from 'src/app/employees/employee/employee.component';

import { HttpModule } from '@angular/http';

import { ToastrModule } from 'ngx-toastr';

@NgModule({
  declarations: [
    AppComponent,
    EmployeesComponent,
    EmployeeComponent,
    EmployeeListComponent
  ],
  imports: [
    BrowserModuleFormsModuleHttpModuleToastrModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}


Styles.css
/* You can add global styles to this file, and also import other style files */

form.emp-form{
  background-color:#dbdbdb;
  border-radius:4px;
  padding:10px;
}

div.validation-error {
  color:red;
  text-align:center;
}

button:hovera.btn.hover {
cursor:pointer;
}


Main.ts
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));


In web api install using tools->nugget.. ->package manager console
Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.2.7
Add enable cors in WebAPIConfig
// Web API configuration and services
            config.EnableCors(new EnableCorsAttribute(origins: "http://localhost:4201", headers: "*", methods: "*"));

npm install @angular/animations


Sri Lanka .NET 
                Forum Member