This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Angular - API with SQL Server


In this tutorials we will learn step by step process to create employee page in a Web API using Angular. Here, we have divided the task with 3 parts as following:

  1. SQL Server
  2. .NET API
  3. Angular

Part 1: SQL Server

Open SQL Server Management Studio, create a database named EmployeeDB and in this database create a table. Give that table a name like Employees. The below script to create Employees table.

USE [EmployeeDB]
GO

/****** Object: Table [dbo].[Employees] Script Date: 05-12-2022 00:40:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Employees](
[Id] [int] IDENTITY(1,1) NOT NULL,
[EmployeeType] [int] NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Designation] [nvarchar](max) NOT NULL,
[Salary] [int] NOT NULL,
CONSTRAINT [PK_dbo.Employees] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Part 2: .NET API

Open Visual Studio and create a new project.

Angular API SQL Server

Now Click on the next button and give project name EmployeeResgistration.

Angular API SQL Server

Now click on the Next button and select API looks like as:

Angular API SQL Server

Now click on the create button. Project structure looks like:

Angular API SQL Server

Now open Web.Config file and add connection string inside connectionStrings section.

<add name="EmployeeDb" connectionString="Server=DESKTOP-G82VNVU;Initial Catalog=EmployeeDB; Persist Security Info=True; Integrated Security=True" providerName="System.Data.SqlClient" />

Now Add a employeeContext file and add the following code inside it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using ResgistrationEmployee.Models;

namespace ResgistrationEmployee
{
    public class EmployeeContext : DbContext
    {
        private object _dsDbContext;

        public EmployeeContext() : base("EmployeeDb")
        {

        }
        public DbSet Employees { get; set; }
    }
}

Now create a employee controller and add the following code to the controller.

using EmployeeResgistration.Models;
using Microsoft.AspNetCore.Cors;
using ResgistrationEmployee;
using ResgistrationEmployee.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace EmployeeResgistration.Controllers
{
    [Route("api/employee")]
    public class EmployeeController : ApiController
    {
        EmployeeContext _dbContext = new EmployeeContext();

        [HttpGet]
        public IEnumerable GetAllEmployees()
        {
            return _dbContext.Employees.ToList();
        }
        [HttpPost]
        public IHttpActionResult Post(Employee employee)
        {
            try
            {
                _dbContext.Employees.Add(employee);
                _dbContext.SaveChanges();
                return Ok(new { Message =""});
            }
            catch (Exception ex)
            {

                return BadRequest();
            }

        }

        [HttpDelete]
        public IHttpActionResult Delete(int id)
        {
            try
            {
                var details = _dbContext.Employees.FirstOrDefault(x => x.Id == id);
                _dbContext.Employees.Remove(details);
                _dbContext.SaveChanges();
                return Ok();
            }
            catch (Exception)
            {

                return BadRequest();
            }

        }
        [HttpPut]
        public IHttpActionResult Put(Employee[] employee)
        {
            try
            {
                foreach (var item in employee)
                {
                    var details = _dbContext.Employees.FirstOrDefault(x => x.Id == item.Id);
                    details.Designation = item.Designation;
                    details.EmployeeType = item.EmployeeType;
                    details.Salary = item.Salary;
                    details.Name = item.Name;
                    _dbContext.SaveChanges();
                }
                return Ok();
            }
            catch (Exception)
            {

                return BadRequest();
            }

        }
    }
}

Now run the API application and will see GET, POST, DELETE and PUT API now running.

Angular API SQL Server

Part 3: Angular

Firstly We create a component named registration-form and add the following code registration-form.component.html

<form [formGroup]="reactiveform" (ngSubmit)="onSubmit()"> 

<br>
<br>
<div class="row">
<div> 
<label>Select Employee Type</label> 
<select formControlName="employeeType">
<option value="">---Select Employee Type---</option>
<option value="0">Permanent</option>
<option value="1">Contract</option>
</select>
</div> 
</div>
<br>
<div class="row">
<div> 
<label style="padding-left: 31px;" > Employee Name</label> 
<input type="text" name="name" formControlName="name" placeholder="Enter Name"> 
<div *ngIf="reactiveform.get('name').touched && reactiveform.get('name').invalid">
<div *ngIf="reactiveform.get('name').errors.required">
<span style="color: red;">Name is required.</span>
</div>
</div> 
</div>
</div> <br>
<div class="row">
<div> <label> Employee Designation</label> 
<input type="text" name="designation" formControlName="designation" placeholder="Enter Designation"> 
<div *ngIf="reactiveform.get('designation').touched && reactiveform.get('designation').invalid">
<div *ngIf="reactiveform.get('designation').errors.required">
<span style="color: red;">Designation is required.</span>
</div>
</div> 
</div>
</div> <br>
<div class="row">
<div> <label style="padding-left: 31px;"> Employee salary</label> 
<input type="text" name="salary" formControlName="salary" placeholder="Enter Salary"> 
<div *ngIf="reactiveform.get('salary').touched && reactiveform.get('salary').invalid">
<div *ngIf="reactiveform.get('salary').errors.required">
<span style="color: red;"> Salary is required.</span>
</div>
</div> 
</div>
</div><br><br>
<button style="margin-left: 100px;" type="submit" [disabled]="!reactiveform.valid">Submit</button> 
</form>

Now add the following code registration-form.component.cs

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ServiceService } from '../shared/service.service';

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

  reactiveform: any;
  empList: any;
  constructor(private _service: ServiceService,
    private fb: FormBuilder
  ) { }

  ngOnInit(): void {
    this.reactiveform = this.fb.group({
      id: ['0', Validators.required],
      employeeType: ['', Validators.required],
      name: ['', Validators.required],
      designation: ['', Validators.required],
      salary: ['', Validators.required],
    });
  }
  onSubmit() {
    this._service.addformdata(this.reactiveform.value).subscribe({
      next: () => {
        alert("data saved");
      },
      error: error => {
      }
    })
  }
}

Now create a common folder and add the following .cs files named as employee-model.ts and service.service.ts.

Now add the following code inside employee-model.ts file

export class EmployeeModel {
    id: number=0
    employeeType: number=0
    name: string=""
    designation: string=""
    salary: number=0
}

Now add the following code inside service.service.ts. file

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { environment } from 'src/environments/environment';
import { EmployeeModel } from './employee-model';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class ServiceService {

  constructor(private http: HttpClient) { } 
  
  addformdata(form:EmployeeModel):Observable{
    return this.http.post(`${environment.baseUrl}`,form);
  };
}

Now add the following code inside environment.ts

export const environment = {
production: false,
baseUrl:'https://localhost:44340/api/employee'
};

Now add the following code to import HTTP in app.module.ts file

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule,routingComponent } from './app-routing.module';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    routingComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now add the following code to import HTTP in app-routing.module.ts file

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { RegistrationFormComponent } from './registration-form/registration-form.component';

const routes: Routes = [
  {path:"form",component:RegistrationFormComponent}
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponent=[RegistrationFormComponent];

Now run the application.

Angular API SQL Server6

Now click on the registration link. registration form looks like as:

Angular API SQL Server

Now enter the field value and click on the submit button to save data in SQL server Table.

Angular API SQL Server

The Employee table with inserted data.

Angular API SQL Server

Download Angular-.NET API and SQL Server code


Prev Next