Angular 5 with Web API – CRUD Operations

In this article, we’ll create a CRUD application using Angular 5 with Web API. CRUD Operations Insert Update and Delete will be implemented inside an Asp.net Web API Using Entity Framework and then consumed from an Angular 5 Application.

Application Demo : 

Demo Of CRUD Operations In Angular 5 With Web API

Following tools and modules are used for this project :

– Angular CLI
– Angular 5
– ngx-Toastr (npm package)
– Bootstrap and Font-Awesome Icons
– VS Code & Visual Studio Editor

we assume that you have installed required packages and software for angular 5 application development.
Download project source code from GitHub : Angular 5 With Web API – CRUD Operations.

Create SQL Server DB

First of all, let’s create a database to work with. I use Management Studio to create and manage SQL database.

Created a Database with name ‘WebAPIDB’, In this application we’ll deals with details of employees. so an employee table is created using following SQL Script.

Here EmployeeID column is the Primary Key and IDENTITY column for the table. Because of IDENTITY specification, we don’t insert values into EmployeeID column. SQL Server will take care of that. It will start from 1 and incremented by 1 upon new record insertion.

Create Web API Application

Database is ready, Now let’s create an Asp.Net Web API project.

Open Visual Studio, Go to File > New > Project (Ctrl + Shift +N).

Create Web API Project

then select Web API template.

Select Web API Project

So here we have created a brand new Web API Project. Now let’s add Entity Model for the DB ‘WEPAPIDB’ inside Models Folder.

Right Click on Models Folder > Add > New Item.

Name your Entity Model as DBModels.edmx.

Create ADO.NET Entity Model For the DB

Select Generate From database.

Select Generate From Database

In Data Connection Window, Click On New Connection.

Configure DB Connection

Provide SQL Server Instance Details and Select the DB.

Provide SQL Server Connection Details and DB Name

As per previous window, we’ll save DB Connection string in WebConfig as DBModel. After creating this Entity Model there will be a class with this name (DBModel), we’ll create an object of this class in-order to interact with database.

After previous window, you may see an extra window as follows, if you have multiple Entity Framework Versions, then select one of them.

Select EF Version

then select tables that we want to add inside the Entity Model.

Select Tables for Entity Model

Click on Finish. Diagrammatic Representation of EF Model looks like this.

Diagrammatic Representation of EF Model

Inside this DBModels.edmx, you can see a DBModels.Context.cs file for DBModel Class. we’ll create an object of this class to work with database.

DBModels.tt > Employee.cs contains Employee Class, which contains properties corresponding to SQL Table Columns, So this is our Model Class.

Now let’s add Employee Controller, before that don’t forget to Re-build your solution. To create a Controller, right click on controllers folder then click on Add > Controller…, Then select Web API 2 Controller with actions, Using Entity Framework Scaffolding Mechanism.then following window will be shown.

Create Web API Controller

It will create Web API Controller Employee using Employee Class from Entity Model. Created controller contains web methods GET,POST,PUT and DELETE for CRUD operations READ INSERT UPDATE AND DELETE respectively. These default web methods contains model validations, we don’t do model validation in this Web API project, Form validation can be done inside angular 5 application, Employee controller without validation looks like this

All these Web API methods are written using DB First Approach in Entity Framework. Now let’s check working of this Web API project, first of all let me add a test employee record inside Employee table.

Now let’s run our Web API project. then navigate /api/Employee URL. It will call GetEmployees Method to retrieve employee collection from SQL server table Employee.

View Employee Collection from DB through Web API

Here base URL is localhost:28750, we need this base URL to consume this Web API from Angular 5 Application. Thereby our Web API Project is working fine, finally let me truncate the test record from employee table.

Create Angular 5 Application

I use Visual Studio Code Editor for Angular Project Development. In-order to create an angular 5 application you can use following Angular CLI command.

It will create the application with name AngularCRUD  and install default packages from npm. In-order to run an angular application, you can use following command.

it will open our application from default port number 4200, that means –  http://localhost:4200.

Add Required Angular 5 CRUD Components, Model and Service Class

Now we need to add 3 components. To add an angular component you can do this

Here we creates employees component,remaining two components will be child components for this employees component. following command creates child components employee and employee-list componets.

Open appmodule.ts file, Make sure that newly added components are added to declarations array.

Let’s Start the Design

We’ll use Bootstrap and Font-Awesome Icons For Application Design. So first of all add CDN reference for these style sheets inside index.html .

Update app.component.html as follows

Add Following to employees.component.html file.

We need Model and Services to design remaining child components.

Create Service and Model Classes

To create these classes let’s add a new folder shared, inside employees folder (/src/app/employees/ ).

Now create employee model class

in this application we deals with employee details like

  • First Name
  • Last Name
  • Emp Code
  • Position
  • Office Location

So we have to add properties corresponding to these employee’s details inside employee.model.ts file.

EmployeeID property is used to identify each employee record individually inside the application.

Inside Employee service class,we defined functions for each CRUD operation in Angular 5 with Web API.That means we consume Web API methods from this service class.

In this service class we have imported http and rxjs related classes. http class is used to consume the Web API methods for Insert Update and Delete operations.

But there is a Problem – CORS

CORS (Cross-Origin Resource Sharing) : it is a mechanism to let a user agent (browser) gain permission to access selected resources from a server on a different origin (domain) than the site currently in use. cross-origin HTTP request occurs when it requests a resource from a different domain, protocol, or port than the one from which the current document originated.

In this application, our web API project will block request from angular 5 application, since they are cross-origin HTTP request(from different port numbers – 4200 and 28750). In-order to allow cross-origin HTTP request, we have to configure Web API project for this localhost:4200 request. so let’s look how we can do that.

First of we have to install NuGet Package : WebApi.Cors. Back to Visual Studio, Select your Web API project from solution explorer, then go to Tools > Library Package Manager > Package Manager Console. use following NuGet command to install WebApi.Cors.

NuGet Command for Web API Cors

Now let’s look how we can use this package. In-order allow cross-origin request in Web API controller Employee we can do this.

Here we have given permission for http request from ‘http://localhost:4200’, it’s not a good idea to add this EnableCors attribute for all Web API controlls if your project is big in size. In that case you do this.

Go to App_Start >WebApiConfig.cs file. add following lines of code

now web API project is ready for cross-origin request from our angular 5 application.

try to navigate this URL /api/Employee from your web API project some of you may get this problem.

Could not load file or assembly System.Web.Http

It is due to different version of WebApi.Cors (5.2.3) and System.Web.Http (5.0.0), so lets install same version of WebApi.Core (Not Cors it is Core). it will resolve this assembly problem. for that you can run following NuGet Command from Package Manager Console.

So here we have completed with Web APi Project. Back to angular 5 project.

Angular 5 Project Structure

This our application structure, component employees will be the parent component for employee and employee-list component.

We are going to inject EmployeeService inside the Parent Component Employees. and there by we can access the same injected service instance from child components Employee and Employee-List. so whenever we make make changes in one child component same change can seen from other child component also.

Inject Employee Service in Components :

first of all inject the service class inside parent component Employees

To inject a class inside a component , mention the class inside component providers array and then create private parameter inside component constructor.

Now we can use this injected instance in child components, Inside employee.component.ts file

And inside employee-list.component.ts file

Angular 5 CRUD Operations Form

we’ll create an employee form to implement Insert and Update Operation with employee Component. So we are going to create a Template Driven Form(TDF) using selectedEmployee property from injected EmployeeService Class.

So first of all we have to import FormsModule and HttpModule  in appmodule.ts file.

So you can use following html in employee.component.html file.

and this employee form will look like this.

Screen shot Employee Form

This form design is inspired from Bootstrap Custom Form Styles. A hidden field is added for EmployeeID property.

Form Validation

required attribute is added to First Name and Last Name text boxes, so these two fields are mandatory to submit this form.When these text-boxes are invalid,  ng-invalid and ng-dirty class will automatically added to it. so based on these classes we have implemented form validation.

when these text boxes are not valid, employee form as whole is not valid, so we added conditional disable attribute to Submit Button.

to show validation error, we’ll show red border around these text box using CSS. complete css rules for this application to global css file styles.css.

Insert,Update  and Reset Operation

Inside employee.component.ts file we’ll write code for Insert, Update and Delete Operation. Before that I’m going to install ngx-toastr from npm package. this package helps us to show notification message inside angular applications.

 ngx-toastr package installation

In-order to install the package, you can use following npm command.

then add ToastrModule inside appmodule.ts file.

Then add toastr.css style-sheet reference in .angular-cli.json file.

Now you can add following code inside employee component typescript file.

restForm function is used reset form controls value to initial stage, we called this function from reset button click event and from ngOnint  Lifecycle Hook to initialise the form.

Inside the form submit event function OnSubmit, we implement both insert and update operation based on EmployeeID value. To show the success message,  we use ToastrService class object toastr.

List Inserted Records and Delete Operation

Using employee-list component we’ll list all inserted employees and implement Delete operation.

you can add following inside employee-list component.

Inside this we have injected EmployeeService and ToastrService Class. Inside the ngOnint  Lifecycle Hook, we called getEmployeeList from EmployeeService class. It will store employee collection from Employee table inside employeeList array. Now we can use this array to list employee collection. You can add following html code inside employee-list.component.html file.

Component design looks like this

employee-list component design

 

when we click on pencil button it will call showForEdit function to populate corresponding record inside the employee form.Using trash icon we implemented delete operation with onDelete  function.

Download project source code from GitHub : Angular 5 With Web API – CRUD Operations.

In my previous article we discussed on implementing Angular 5 CRUD Operations With Firebase. Please read the article if you have not read before.

Step by Step Video Tutorial

Thanks for the visit, hope you liked it, let me know your comments.

92
Leave a Reply

avatar
53 Comment threads
39 Thread replies
2 Followers
 
Most reacted comment
Hottest comment thread
57 Comment authors
ShamseerGirija Sahusneha dasJaison JoySTEVEN Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
vivek GC
Guest
vivek GC

Good Example thank you so much for this articles

Chris K
Guest
Chris K

Very well written for me. Simple, clean, and informative. Thank you.

Facundo D
Guest
Facundo D

Excellent example… very cute things are behind Angular v5 branch.
Keep in mind that Http component – https://angular.io/api/http/Http – is deprecated in favor of HttpClient – https://angular.io/api/common/http/HttpClient – that has also some json magic build it.

Cheers!

Aravind
Guest
Aravind

it is not deprecated. New HttpClient has some new features. Old http component will work fine.

Ahmad Zeb
Guest
Ahmad Zeb

Hello sir please add angular5 user registration and Angular 5 : Login – Logout with Web API articles

riyaz
Guest
riyaz

hi sir..please add one example of how to use chartjs to our angular5 application…plz make sure multiple graphs should b loaded on the same view when we select dropdown

pandu wijaya
Guest
pandu wijaya

hi sir, why my form not reset after submit the data?
i have download your project and get same problem.

thanks

Rocky
Guest
Rocky

Thanks.. Really nice topic

daniel
Guest
daniel

I get this error in console

ERROR TypeError: Cannot read property ‘selectedEmployee ‘ of undefined

Adward
Guest
Adward

Hi Sir,
I have get an error when I try to Insert Employee.
{\”Message\”:\”The request is invalid.\”,\”ModelState\”:{\”employee.EmployeeID\”:[\”Error converting value {null} to type ‘System.Int32’. Path ‘EmployeeID’, line 1, position 18.\”]}}

Mayur
Guest
Mayur

It does not submit on click!!!!!!!!!!!

Tami
Guest
Tami

I’m getting a browser console error…The request is invalid.”,”ModelState”:{“tRtest.EmployeeID”: “Error converting value {null} to type ‘System.Int32’ for the EmployeeID. Any help would be great, I really want to get this working. (I modified DB name to TRtest). No errors in the code for Visual Studio (and Visual Studio Code).

ben2code
Guest
ben2code

same problem here at work , trying to fix that

ben2code
Guest
ben2code

Fixed on my own project by removing checking the model is empty or not

Alo
Guest
Alo

Hi, I am getting the following message “message: “_co.employeeService.selectedEmployee is undefined” I have downloaded your code and still is having the same problem. Once I click the Reset button, I have got the above message in the console window. Could you please tell me how I can fix the problem?… Read more »

NamHT
Guest
NamHT

Thank Sir, Very good example thank you so much.

Adam
Guest
Adam

Hey 🙂 You forgot to add that TOASTR require additional CSS styling. Without that it will appear as plain text.

Anonymous
Guest
Anonymous

on edit button click i am not getting record in form

ali
Guest
ali

i have same problem
what should I do?

Midhun P
Guest
Midhun P

Can I run this project in Visual Studio 2015

Gurnam
Guest
Gurnam

Hi, I’m currently following your tutorial, everything seems to be working fine up to this point. The issue I’ve got is when I add the following html to employee.component.html: Employee Register This working and shows in my browser however when I added the second element: My localhost crashes and nothing… Read more »

Gurnam
Guest
Gurnam

this works

Employee Register
</
this secord element not working..

Gurnam
Guest
Gurnam

Hi, I’m currently following your tutorial, everything seems to be working fine up to this point. The issue I’ve got is when I add the following html to employee.component.html: Employee Register This working and shows in my browser however when I added the second element: My localhost crashes and nothing… Read more »

Acrobat
Guest
Acrobat

Hi everyone. When I click on edit, textbox are filled but with extra blank spaces. First name is John in database, but on edit textbox is filled with John_______ (underscore is example. the are space in my case). Can anyone suggest solution?

ali
Guest
ali

hi dear
thank u for this example
i have one problem
when i click on edit button in the table ,row not send to the from

Suvro
Guest
Suvro

Hi..very good article,need some source code of check boxes ,drop downs in these forms for edit/update through web api..Can you integrate various form components inside this source and send it to me

padmaja
Guest
padmaja

ERROR Error: Uncaught (in promise): Response with status: 0 for URL: null
Getting the above exception for me, not able to submit the form

karnik
Guest
karnik

awesome. very very useful. please provide in same manner with image/file upload in angular 5.

S kumar
Guest
S kumar

Hi,
I am getting below error, please help me to resolve.
[ts] Module ‘”c:/AngularProject/AngularCRUD/node_modules/rxjs/Observable”‘ has no exported member ‘Observable’.

Gualter
Guest
Gualter

Cannot read property ‘FirstName’ of undefined
The Course is awesome… Please help me!

Jen
Guest
Jen

I am getting this error
src/app/employees/employee/employee.component.ts(2,27): error TS2300: Duplicate identifier ‘EmployeeService’.

Shafqat Jan Siddiqui
Guest
Shafqat Jan Siddiqui

ERROR in ./src/app/employees/shared/employee.service.ts
Module not found: Error: Can’t resolve ‘rxjs/add/operator/map’ in ‘E:\nodejs\demo\Angular4\AngularCRUD2\src\app\employees\shared’
ERROR in ./src/app/employees/shared/employee.service.ts
Module not found: Error: Can’t resolve ‘rxjs/add/operator/toPromise’ in ‘E:\nodejs\demo\Angular4\AngularCRUD2\src\app\employees\shared’

Shafqat Jan Siddiqui
Guest
Shafqat Jan Siddiqui

im facing this issue
ERROR in ./src/app/employees/shared/employee.service.ts
Module not found: Error: Can’t resolve ‘rxjs/add/operator/map’ in ‘E:\nodejs\demo\Angular4\AngularCRUD2\src\app\employees\shared’
ERROR in ./src/app/employees/shared/employee.service.ts
Module not found: Error: Can’t resolve ‘rxjs/add/operator/toPromise’ in ‘E:\nodejs\demo\Angular4\AngularCRUD2\src\app\employees\shared’

MD Hameed
Guest
MD Hameed

Add this import and try: import { Observable, of } from ‘rxjs’

MD Hameed
Guest
MD Hameed

The below solution I took from user vermouthyr from this link https://github.com/angular/angular/issues/15548 and it worked in my case also. “I met the same problem with the angular cli 6.0.0 and rxjs 6.1.0. And I solved the problem by replacing the former code with latter code below. import ‘rxjs/add/operator/map’; this.myObservable().map(data =>… Read more »

Deepak
Guest
Deepak

Thanq So much

Nakul
Guest
Nakul

Thanks. Nice article for newbies !!!

MD Hameed
Guest
MD Hameed

I have rewritten this app using the latest Angular 6. You can download it from the github here: https://github.com/mdhameed/ng6withWebAPI_Part2 and also find the Web api app from here https://github.com/mdhameed/ng6withWebAPI. Please let me know if you get any queries.

Rush
Guest
Rush

Best tutorial for Angular 5, Good explanation as well..!!

venkat
Guest
venkat

Very nice tutorial. Explained almost features. Thank you very much

sandeep
Guest
sandeep

Awesome demo project , i have facing issues after click edit event not generated no error but nothing happen .
how to check the event call?

Puneet Goel
Guest
Puneet Goel

this.myObservable().map(data => {})
becomes this:

this.myObservable().pipe(map(data => {}))
And with your operators you need to switch to using lettable operators by switching from an import like this:

import ‘rxjs/add/operator/map’;
to this:

import { map } from “rxjs/operators”;

FE - SoT
Guest
FE - SoT

Only 1 thing – why you use “var”? Is it necessary to use it as in example? I don’t think so. Even linter yelling for “let”.

hadd8
Guest
hadd8

very clean, you save my day, bro! thanks so much

Guzzyman
Guest
Guzzyman

Hi Shamsheer, The tutorial is very great. I actually used your tutorial to come up with something different. Instead of using employees I used family. But the challenge I’m having is with the CORS. I’m using Visual Studio Ultimate edition. How can I get the second component to display data?… Read more »

gayatri
Guest
gayatri

hi ,Nice tutorial but my data is not getting populated after click on showedit icon. there are no error in console aswett

vino b
Guest
vino b

Can’t get customer list //error shown here Cannot find a differ supporting object ‘[object Object]’ of type ‘object’. NgFor only supports binding to Iterables such as Arrays. {{customer.firstname}} – {{customer.lastname}}

Vinay pratap singh
Guest
Vinay pratap singh

Thanks for the tutorial sir. I am getting an error on compiling– ERROR in src/app/employees/employee/employee.component.ts(31,26): error TS2339: Property ‘postEmployee’ does not exist on type ‘EmployeeService’. please do let me know how to resolve it I am stuck

harish
Guest
harish

Angular is running in the development mode. Call enableProdMode() to enable the production mode.

harish
Guest
harish

hello everyone I am getting error Angular is running in the development mode. Call enableProdMode() to enable the production mode. in angular 4 when i click on edit button not get value into textbox and I am getting error Angular is running in the development mode. Call enableProdMode() to enable… Read more »

harish
Guest
harish

on edit button click i am not getting record in form

harish
Guest
harish

hello everyone
on edit button click i am not getting record in form. i see console in browser then i see this error
I am getting error Angular is running in the development mode. Call enableProdMode() to enable the production mode. in angular 4

gayatri
Guest
gayatri

what is the solution for that. to get data in form on button click

mahesh
Guest
mahesh

how to publish
angular 5 and web api

Hoàng Quốc Duy
Guest
Hoàng Quốc Duy

could you show me the way read data from json api?

Djo
Guest
Djo

Thank you very much Master

Mahboob
Guest
Mahboob

I want to run this program in angular6 but i get .map error [Property ‘map’ does not exist on type ‘Observable<Response] in emplolyee.service.ts file. what can i do..?? please reply as fast as u can.
Thankyou.

test
Guest
test

just write this command in vs code terminal of your project and restart the project.

npm install rxjs-compat
You need to import the map operator by write this:

import ‘rxjs/add/operator/map’;

https://stackoverflow.com/questions/37208801/property-map-does-not-exist-on-type-observableresponse