Introduction

In this article, I will create a demo project for student information.
Prerequisite

In this article, we will create a simple Angular 7 application in a step-by-step manner from scratch to perform the CRUD operations using Web API, Angular 7, and SQL Server.

Steps required for CRUD Operations.
  1. Create Database and table in SQL Server.
  2. Create Web API using ASP.NET Web API.
  3. Create a new project in Angular 7
For this article, I have created a database and two tables. For creating the database, we follow the following steps.
Step 1
Let's open SSMS (SQL Server Management Studio).
CRUD Operation Using Web API And Angular 7

Step 2

Connect to the SSMS.
CRUD Operation Using Web API And Angular 7
Step 3
I have created the database using the following query.
  1. create Database StudentCurd

Step 4

I have created a StudentData table.
  1. CREATE TABLE [dbo].[StudentData](
  2. [Id] [int] NOT NULL,
  3. [StudentName] [varchar](50) NULL,
  4. [FName] [varchar](50) NULL,
  5. [MName] [varchar](50) NULL,
  6. [ContactNo] [varchar](50) NULL,
  7. CONSTRAINT [PK_StudentData] PRIMARY KEY CLUSTERED
  8. (
  9. [Id] ASC
  10. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  11. ) ON [PRIMARY]

Now, the database looks like below.

CRUD Operation Using Web API And Angular 7

I have created a Web API using ASP.Net Web API. For creating the Web API, we need to follow the following steps.

Step 1

Open Visual Studio 2017 and go to File > New > Project.
CRUD Operation Using Web API And Angular 7
CRUD Operation Using Web API And Angular 7
Step 2
Select Web >> ASP.NET Web Application.
CRUD Operation Using Web API And Angular 7

Step 3

Then, select Web API and click OK.
CRUD Operation Using Web API And Angular 7
Step 4
Now, create a new Controller named Student.
CRUD Operation Using Web API And Angular 7
CRUD Operation Using Web API And Angular 7
Step 5
Now, import the database using Entity Framework.
CRUD Operation Using Web API And Angular 7
Step 6
Now, create a method (StudentInsert) for Insert and Update operation on student data in Student Controller.
  1. [Route("StudentInsert")]
  2. [HttpPost]
  3. public object StudentInsert(StudentVM objVM)
  4. {
  5. try
  6. {
  7. if (objVM.Id == 0)
  8. {
  9. var objlm = new StudentData();
  10. objlm.StudentName = objVM.StudentName;
  11. objlm.FName = objVM.FName;
  12. objlm.MName = objVM.MName;
  13. objlm.ContactNo = objVM.ContactNo;
  14. wmsEN.StudentDatas.Add(objlm);
  15. wmsEN.SaveChanges();
  16. return new ResultVM
  17. { Status = "Success", Message = "SuccessFully Saved." };
  18. }
  19. else
  20. {
  21. var objlm = wmsEN.StudentDatas.Where(s => s.Id == objVM.Id).ToList<StudentData>().FirstOrDefault();
  22. if (objlm.Id > 0)
  23. {
  24. objlm.StudentName = objVM.StudentName;
  25. objlm.FName = objVM.FName;
  26. objlm.MName = objVM.MName;
  27. objlm.ContactNo = objVM.ContactNo;
  28. wmsEN.SaveChanges();
  29. return new ResultVM
  30. { Status = "Success", Message = "SuccessFully Update." };
  31. }
  32. return new ResultVM
  33. { Status = "Error", Message = "Invalid." };
  34. }
  35. }
  36. catch (Exception ex)
  37. {
  38. return new ResultVM
  39. { Status = "Error", Message = ex.Message.ToString() };
  40. }
  41. }
Step 7
Now, create a method (GetStudentData) for fetching the student data in Student controller.
  1. [Route("GetStudentData")]
  2. [HttpGet]
  3. public object GetStudentData()
  4. {
  5. var obj = from u in wmsEN.StudentDatas
  6. select u;
  7. return obj;
  8. }

Step 8

Now, create a method (GetStudentById) for fetching the particluar student data in Student Controller.
  1. [Route("GetStudentById")]
  2. [HttpGet]
  3. public object GetStudentById(int Id)
  4. {
  5. return wmsEN.StudentDatas.Where(s => s.Id == Id).ToList<StudentData>().FirstOrDefault();
  6. }

Step 9

Now, create a method (GetStudentById) for deleting the data in Student Controller.
  1. [Route("DeleteStudent")]
  2. [HttpGet]
  3. public object DeleteStudent(int Id)
  4. {
  5. try
  6. {
  7. var objlm = wmsEN.StudentDatas.Where(s => s.Id == Id).ToList<StudentData>().FirstOrDefault();
  8. wmsEN.StudentDatas.Remove(objlm);
  9. wmsEN.SaveChanges();
  10. return new ResultVM
  11. { Status = "Success", Message = "SuccessFully Delete." };
  12. }
  13. catch (Exception ex)
  14. {
  15. return new ResultVM
  16. { Status = "Error", Message = ex.Message.ToString() };
  17. }
  18. }
Here is the complete code for StudentController.cs.
  1. using StudentCurdService.Models;
  2. using StudentCurdService.Models.VM;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Threading.Tasks;
  9. using System.Web.Http;
  10. namespace StudentCurdService.Controllers
  11. {
  12. [RoutePrefix("api/student")]
  13. public class StudentController : ApiController
  14. {
  15. StudentCurdEntities1 wmsEN = new StudentCurdEntities1();
  16. [Route("StudentInsert")]
  17. [HttpPost]
  18. public object StudentInsert(StudentVM objVM)
  19. {
  20. try
  21. {
  22. if (objVM.Id == 0)
  23. {
  24. var objlm = new StudentData();
  25. objlm.StudentName = objVM.StudentName;
  26. objlm.FName = objVM.FName;
  27. objlm.MName = objVM.MName;
  28. objlm.ContactNo = objVM.ContactNo;
  29. wmsEN.StudentDatas.Add(objlm);
  30. wmsEN.SaveChanges();
  31. return new ResultVM
  32. { Status = "Success", Message = "SuccessFully Saved." };
  33. }
  34. else
  35. {
  36. var objlm = wmsEN.StudentDatas.Where(s => s.Id == objVM.Id).ToList<StudentData>().FirstOrDefault();
  37. if (objlm.Id > 0)
  38. {
  39. objlm.StudentName = objVM.StudentName;
  40. objlm.FName = objVM.FName;
  41. objlm.MName = objVM.MName;
  42. objlm.ContactNo = objVM.ContactNo;
  43. wmsEN.SaveChanges();
  44. return new ResultVM
  45. { Status = "Success", Message = "SuccessFully Update." };
  46. }
  47. return new ResultVM
  48. { Status = "Error", Message = "Invalid." };
  49. }
  50. }
  51. catch (Exception ex)
  52. {
  53. return new ResultVM
  54. { Status = "Error", Message = ex.Message.ToString() };
  55. }
  56. }
  57. [Route("GetStudentData")]
  58. [HttpGet]
  59. public object GetStudentData()
  60. {
  61. var obj = from u in wmsEN.StudentDatas
  62. select u;
  63. return obj;
  64. }
  65. [Route("GetStudentById")]
  66. [HttpGet]
  67. public object GetStudentById(int Id)
  68. {
  69. return wmsEN.StudentDatas.Where(s => s.Id == Id).ToList<StudentData>().FirstOrDefault();
  70. }
  71. [Route("DeleteStudent")]
  72. [HttpGet]
  73. public object DeleteStudent(int Id)
  74. {
  75. try
  76. {
  77. var objlm = wmsEN.StudentDatas.Where(s => s.Id == Id).ToList<StudentData>().FirstOrDefault();
  78. wmsEN.StudentDatas.Remove(objlm);
  79. wmsEN.SaveChanges();
  80. return new ResultVM
  81. { Status = "Success", Message = "SuccessFully Delete." };
  82. }
  83. catch (Exception ex)
  84. {
  85. return new ResultVM
  86. { Status = "Error", Message = ex.Message.ToString() };
  87. }
  88. }
  89. }
  90. }
For this article, I have created an Angular project using Angular 7. For creating an Angular project, we need to follow the following steps.

Step 1

I have created a project using the following command in the Command Prompt.
  1. ng new studentcurd

Step 2

Open project in Visual Studio Code using the following commands.
  1. cd studentcurd
  1. code .
Open the project in Visual Studio Code.
CRUD Operation Using Web API And Angular 7
Step 3
Now, we install bootstrap in our project using the following command in the terminal.
  1. npm install --save bootstrap
Step 4
After installing bootstrap, we should import bootstrap in style.css.
  1. @import '~bootstrap/dist/css/bootstrap.min.css';

Step 5

I have created a folder named Student/Class/Service in the App Folder .

Step 6

Now, open a new terminal in VS Code using Ctrl+` or View > Terminal menu.
Step 7
I have created the StudentVM Class in the Class folder using the following command.
  1. ng g class studentVM

Step 8

I have added the following fields in StudentVM Class.
  1. export class StudentVM {
  2. Id:string;
  3. StudentName:string;
  4. FName:string;
  5. MName:string;
  6. ContactNo:string;
  7. }
Step 9
Create Student Service in Service folder using the following command.
  1. ng g service student

Step 10

In this class, we use HttpClient to call API Services and all kinds of HTTP Methods - GET and POST. And, I have imported the following references.
  1. import { Injectable } from '@angular/core';
  2. import {HttpClient} from '@angular/common/http';
  3. import {HttpHeaders} from '@angular/common/http';
  4. import { Observable } from 'rxjs';
  5. import { StudentVM } from '../Class/student-vm';

Step 11

Declare the API URL in student service using the following code.
  1. Url = 'http://localhost:54996/Api';

Step 12

I have declared methods for Add, Update, Delete, and Fetch operations in student service using the following code.
  1. getStudent():Observable<StudentVM[]>
  2. {
  3. return this.http.get<StudentVM[]>(this.Url + '/student/GetStudentData');
  4. }
  5. CreateStudent(OutletVM:StudentVM):Observable<StudentVM[]>
  6. {
  7. const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
  8. return this.http.post<StudentVM[]>(this.Url + '/student/StudentInsert/', OutletVM, httpOptions)
  9. }
  10. DeleteStudent(StudentId:string):Observable<number>
  11. {
  12. return this.http.get<number>(this.Url + '/student/DeleteStudent?Id='+StudentId);
  13. }
  14. getStudentById(StudentId: string): Observable<StudentVM> {
  15. return this.http.get<StudentVM>(this.Url + '/student/GetStudentById?Id=' + StudentId);
  16. }

The complete code for student.service.ts is given below.

  1. import { Injectable } from '@angular/core';
  2. import {HttpClient} from '@angular/common/http';
  3. import {HttpHeaders} from '@angular/common/http';
  4. import { Observable } from 'rxjs';
  5. import { StudentVM } from '../Class/student-vm';
  6. @Injectable({
  7. providedIn: 'root'
  8. })
  9. export class StudentService {
  10. Url = 'http://localhost:54996/Api';
  11. constructor(private http:HttpClient) { }
  12. getStudent():Observable<StudentVM[]>
  13. {
  14. return this.http.get<StudentVM[]>(this.Url + '/student/GetStudentData');
  15. }
  16. CreateStudent(OutletVM:StudentVM):Observable<StudentVM[]>
  17. {
  18. const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
  19. return this.http.post<StudentVM[]>(this.Url + '/student/StudentInsert/', OutletVM, httpOptions)
  20. }
  21. DeleteStudent(StudentId:string):Observable<number>
  22. {
  23. return this.http.get<number>(this.Url + '/student/DeleteStudent?Id='+StudentId);
  24. }
  25. getStudentById(StudentId: string): Observable<StudentVM> {
  26. return this.http.get<StudentVM>(this.Url + '/student/GetStudentById?Id=' + StudentId);
  27. }
  28. }
Step 13
I have created a Student Component in the Student folder using the following command.
  1. ng g c student
Step 14
I have Imported StudentVM Classs and Student Service and @angular/form and rxjs in Student Component as code as below:
  1. import { StudentVM } from '../../Class/student-vm';
  2. import { StudentService } from '../../Service/student.service';
  3. import { NgForm, FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
  4. import { Observable } from 'rxjs';
Step 15
I have declared the following field in student Component using the below code,
  1. dataSaved = false;
  2. massage:string;
  3. FromStudent: any;
  4. StudentId:string="0";
  5. allStudent:Observable<StudentVM[]>;
  6. constructor(private formbulider: FormBuilder,private StudentService:StudentService) { }
Step 16
I have created a form builder using the below code,
  1. ngOnInit(): void {
  2. this.FromStudent = this.formbulider.group({
  3. Id: ['', [Validators.required]],
  4. StudentName: ['', [Validators.required]],
  5. FName: ['', [Validators.required]],
  6. MName: ['', [Validators.required]],
  7. ContactNo: ['', [Validators.required]],
  8. });
  9. this.GetStudent();
  10. }

Step 17

I have create a method for getting student data using the below code,
  1. GetStudent( )
  2. {
  3. this.allStudent=this.StudentService.getStudent();
  4. }
Step 18
I have created a method for adding Student Data using the below code,
  1. AddStudent(StudentVM: StudentVM) {
  2. StudentVM.Id = this.StudentId;
  3. this.StudentService.CreateStudent(StudentVM).subscribe(
  4. () => {
  5. this.dataSaved = true;
  6. this.massage = 'Record saved Successfully';
  7. this.GetStudent();
  8. this.Reset();
  9. this.StudentId = "0";
  10. });

Step 19

I have created a method for editing Student Data using the below code,
  1. StudentEdit(StudentId: string) {
  2. debugger;
  3. this.StudentService.getStudentById(StudentId).subscribe(Response => {
  4. this.massage = null;
  5. this.dataSaved = false;
  6. debugger;
  7. this.StudentId = Response.Id;
  8. this.FromStudent.controls['StudentName'].setValue(Response.StudentName);
  9. this.FromStudent.controls['FName'].setValue(Response.FName);
  10. this.FromStudent.controls['MName'].setValue(Response.MName);
  11. this.FromStudent.controls['ContactNo'].setValue(Response.ContactNo);
  12. });
  13. }
Step 20
I have created a method for deleting Student Data using the below code,
  1. DeleteStudent(StudentId: string) {
  2. if (confirm("Are You Sure To Delete this Informations")) {
  3. this.StudentService.DeleteStudent(StudentId).subscribe(
  4. () => {
  5. this.dataSaved = true;
  6. this.massage = "Deleted Successfully";
  7. this.GetStudent();
  8. });
  9. }
  10. }
Step 21
I have created a method for resetting all controls using the below code,
  1. Reset()
  2. {
  3. this.FromStudent.reset();
  4. }

Complete code for student-componant.ts,

  1. import {
  2. Component,
  3. OnInit
  4. } from '@angular/core';
  5. import {
  6. StudentVM
  7. } from '../../Class/student-vm';
  8. import {
  9. StudentService
  10. } from '../../Service/student.service';
  11. import {
  12. Observable
  13. } from 'rxjs';
  14. import {
  15. NgForm,
  16. FormBuilder,
  17. FormGroup,
  18. Validators,
  19. FormControl
  20. } from '@angular/forms';
  21. @Component({
  22. selector: 'app-student',
  23. templateUrl: './student.component.html',
  24. styleUrls: ['./student.component.css']
  25. })
  26. export class StudentComponent implements OnInit {
  27. dataSaved = false;
  28. massage: string;
  29. FromStudent: any;
  30. StudentId: string = "0";
  31. allStudent: Observable < StudentVM[] > ;
  32. constructor(private formbulider: FormBuilder, private StudentService: StudentService) {}
  33. GetStudent() {
  34. debugger;
  35. this.allStudent = this.StudentService.getStudent();
  36. }
  37. Reset() {
  38. this.FromStudent.reset();
  39. }
  40. AddStudent(StudentVM: StudentVM) {
  41. debugger;
  42. StudentVM.Id = this.StudentId;
  43. this.StudentService.CreateStudent(StudentVM).subscribe(
  44. () => {
  45. this.dataSaved = true;
  46. this.massage = 'Record saved Successfully';
  47. this.GetStudent();
  48. this.Reset();
  49. this.StudentId = "0";
  50. });
  51. }
  52. DeleteStudent(StudentId: string) {
  53. if (confirm("Are You Sure To Delete this Informations")) {
  54. this.StudentService.DeleteStudent(StudentId).subscribe(
  55. () => {
  56. this.dataSaved = true;
  57. this.massage = "Deleted Successfully";
  58. this.GetStudent();
  59. }
  60. );
  61. }
  62. }
  63. StudentEdit(StudentId: string) {
  64. debugger;
  65. this.StudentService.getStudentById(StudentId).subscribe(Response => {
  66. this.massage = null;
  67. this.dataSaved = false;
  68. debugger;
  69. this.StudentId = Response.Id;
  70. this.FromStudent.controls['StudentName'].setValue(Response.StudentName);
  71. this.FromStudent.controls['FName'].setValue(Response.FName);
  72. this.FromStudent.controls['MName'].setValue(Response.MName);
  73. this.FromStudent.controls['ContactNo'].setValue(Response.ContactNo);
  74. });
  75. }
  76. ngOnInit(): void {
  77. this.FromStudent = this.formbulider.group({
  78. Id: ['', [Validators.required]],
  79. StudentName: ['', [Validators.required]],
  80. FName: ['', [Validators.required]],
  81. MName: ['', [Validators.required]],
  82. ContactNo: ['', [Validators.required]],
  83. });
  84. this.GetStudent();
  85. }
  86. }
Step 22
I have added a table displaying student data in student.componant.html using the below code,
  1. <div class="card-footer">
  2. <div class="col-lg-12 table-responsive">
  3. <table class="table table-striped">
  4. <thead>
  5. <tr>
  6. <th>Id</th>
  7. <th>Student Name</th>
  8. <th>Father Name</th>
  9. <th>Mother Name</th>
  10. <th>ContactNo</th>
  11. <th></th>
  12. </tr>
  13. </thead>
  14. <tbody>
  15. <tr *ngFor="let Student of allStudent|async">
  16. <td>{{Student.Id}}</td>
  17. <td>{{Student.StudentName}}</td>
  18. <td>{{Student.FName}}</td>
  19. <td>{{Student.MName}}</td>
  20. <td>{{Student.ContactNo}}</td>
  21. <td>
  22. <button type="button" class="btn btn-primary mr-1" (click)="StudentEdit(Student.Id)">Edit</button>
  23. <button type="button" class="btn btn-danger mr-1" (click)="DeleteStudent(Student.Id)">Delete</button>
  24. </td>
  25. </tr>
  26. </tbody>
  27. </table>
  28. </div>
  29. </div>

Step 23

I have added controls for CRUD operations in student.component.html using below code,
  1. <div class="form-group col-sm-3">
  2. <label for="company">Student Name</label>
  3. <input type="text" class="form-control" formControlName="StudentName" id="company" placeholder="Enter Student Name" >
  4. </div>
  5. <div class="form-group col-sm-3">
  6. <label for="company">ContactNo</label>
  7. <input type="text" class="form-control" formControlName="ContactNo" id="ContactNo" placeholder="Enter ContactNo" >
  8. </div>
  9. <div class="form-group col-sm-3">
  10. <label for="company">Father Name</label>
  11. <input type="text" class="form-control" formControlName="FName" id="FatherName" placeholder="Enter Father Name" >
  12. </div>
  13. <div class="form-group col-sm-3">
  14. <label for="company">Mother Name</label>
  15. <input type="text" class="form-control" formControlName="MName" id="MotherName" placeholder="Enter Mother Name" >
  16. </div>
  17. </div>
  18. <div class="row">
  19. <div class="form-group col-sm-3">
  20. <button type="submit" class="btn btn-primary" >Add Student</button>
  21. </div>
  22. </div>
  23. </form>
  24. </div>

Complete code for Student.Component.html

  1. <div class="card">
  2. <div class="card-header" style="text-align:center">
  3. <b>WEL COME TO STUDENT CURD OPERATION</b>
  4. </div>
  5. <div class="card-body">
  6. <form [formGroup]="FromStudent" (ngSubmit)="AddStudent(FromStudent.value)">
  7. <div class="row">
  8. <div class="form-group col-sm-3">
  9. <label for="company">Student Name</label>
  10. <input type="text" class="form-control" formControlName="StudentName" id="company" placeholder="Enter Student Name" >
  11. </div>
  12. <div class="form-group col-sm-3">
  13. <label for="company">ContactNo</label>
  14. <input type="text" class="form-control" formControlName="ContactNo" id="ContactNo" placeholder="Enter ContactNo" >
  15. </div>
  16. <div class="form-group col-sm-3">
  17. <label for="company">Father Name</label>
  18. <input type="text" class="form-control" formControlName="FName" id="FatherName" placeholder="Enter Father Name" >
  19. </div>
  20. <div class="form-group col-sm-3">
  21. <label for="company">Mother Name</label>
  22. <input type="text" class="form-control" formControlName="MName" id="MotherName" placeholder="Enter Mother Name" >
  23. </div>
  24. </div>
  25. <div class="row">
  26. <div class="form-group col-sm-3">
  27. <button type="submit" class="btn btn-primary" >Add Student</button>
  28. </div>
  29. </div>
  30. </form>
  31. </div>
  32. <div class="card-footer">
  33. <div class="col-lg-12 table-responsive">
  34. <table class="table table-striped">
  35. <thead>
  36. <tr>
  37. <th>Id</th>
  38. <th>Student Name</th>
  39. <th>Father Name</th>
  40. <th>Mother Name</th>
  41. <th>ContactNo</th>
  42. <th></th>
  43. </tr>
  44. </thead>
  45. <tbody>
  46. <tr *ngFor="let Student of allStudent|async">
  47. <td>{{Student.Id}}</td>
  48. <td>{{Student.StudentName}}</td>
  49. <td>{{Student.FName}}</td>
  50. <td>{{Student.MName}}</td>
  51. <td>{{Student.ContactNo}}</td>
  52. <td>
  53. <button type="button" class="btn btn-primary mr-1" (click)="StudentEdit(Student.Id)">Edit</button>
  54. <button type="button" class="btn btn-danger mr-1" (click)="DeleteStudent(Student.Id)">Delete</button>
  55. </td>
  56. </tr>
  57. </tbody>
  58. </table>
  59. </div>
  60. </div>
  61. </div>
Step 24
Let's start the project using the following command:
  1. npm start

Add Student

CRUD Operation Using Web API And Angular 7
Student List
CRUD Operation Using Web API And Angular 7

Summary

In this article I have discussed CRUD operations using Web API and Angular 7. In my next article I am going to discuss cascading dropdowns using Angular 7.