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 :
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).
then select Web API template.
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.
Select Generate From database.
In Data Connection Window, Click On New Connection.
Provide SQL Server Instance Details and Select the DB.
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.
then select tables that we want to add inside the Entity Model.
Click on Finish. Diagrammatic Representation of EF Model looks like this.
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.
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.
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
- 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.
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.
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.
This form design is inspired from Bootstrap Custom Form Styles. A hidden field is added for EmployeeID property.
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
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.