Angular 5 with Web API - CRUD Operations - CodAffection

Angular 5 with Web API – CRUD Operations

Angular with ASP.NET Web API CRUD

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.

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.


ng new AngularCRUD

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.


ng serve --open

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


# from root component
ng g c employees

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.


# switch to parent component directory
cd src\app\employees
# create child components
ng g c employee
ng g c employee-list

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


# switch to shared folder
cd src\app\employees\shared
# create employee model class
ng g class employee --type=model
# create employee service class
ng g s employee

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.


Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.2.3
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.


Install-Package Microsoft.AspNet.WebApi.Core -Version 5.2.3

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

Angular 5 Project Structure


● src
+---● app
|   +--● employees
|   |  |--employees.component.ts|.html|.css
|   |  +--● employee (employee form)
|   |  |  |--employee.component.ts|.html|.css
|   |  |
|   |  +--● employee-list (list inserted employees)
|   |  |  |--employee-list.component.ts|.html|.css
|   |  |
|   |  +--● shared
|   |     |--employee.service.ts
|   |     |--employee.model.ts
|   |
|   |--app.module.ts (configured firebase connection)
|
+---● environments  
|   |--environment.ts 
|
|--index.html (cdn path for bootstrap and font awesome icon)

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.


form.emp-form{
    background-color: #dbdbdb;
    border-radius: 4px;
    padding: 10px;
}
div.validation-error{
    color: red;
    text-align: center;
}
button:hover,a.btn:hover{
    cursor: pointer;
}

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 fromnpm 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.


npm install ngx-toastr --save

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

Video tutorial for the same topic from our YouTube.

101 thoughts on “Angular 5 with Web API – CRUD Operations”

  1. Rama Krishna

    Recently started learning Angular. Your articles are very good to improve angular skills. I watched your video of angular crud operations and tried with adding extra field of Date of Birth. Everything goes well except edit. Edit is not populating date field.
    Could you please suggest how resolve. I am using ngx bootstrap date picker.

  2. Hello,
    I am using visual studio 2019 .i was copying procedure but i dont know why Empolyee.cs is not coming in the model.cs part. can u please help me out…?

  3. I’m using your code in an angular 8 and tried to convert your code in angular 8 but data is not inserting. Will you please guide me?
    employee.service.ts(code)
    import { Injectable } from ‘@angular/core’;
    import {Employee} from ‘./employee.model’;
    import {HttpClient, HttpResponse, HttpHeaders, HttpRequest, HttpClientModule} from ‘@angular/common/http’;
    import {Observable} from ‘rxjs’;
    import { map } from ‘rxjs/operators’;

    @Injectable({
    providedIn: ‘root’
    })
    export class EmployeeService {

    selectedEmployee : Employee;
    constructor(private http: HttpClient) {}

    postEmployee(emp : Employee){
    var body = JSON.stringify(emp);
    var headerOptions = new Headers({‘Content-Type’:’application/json’});
    var requestOptions = new requestOptions({method: HttpClient, headers : headerOptions});
    return this.http.post(‘http://localhost:51054/api/Employees’,body, requestOptions).pipe(map(x => x));
    }

    }

  4. Do you have a tutorial for how to filter/search employee table with SQL Server Database similar to the one created to firebase but for Angular 4 CRUD With Web API?

  5. Parvinder.bardhen@gmail.com

    It is really one of the best article on an internet and I really thanks to Shamseer Sir to share knowledgeable content.

  6. 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.

      1. I’m using your code in an angular 8 and tried to convert your code in angular 8 but data is not inserting. Will you please guide me?

        employee.service.ts(code)
        import { Injectable } from ‘@angular/core’;
        import {Employee} from ‘./employee.model’;
        import {HttpClient, HttpResponse, HttpHeaders, HttpRequest, HttpClientModule} from ‘@angular/common/http’;
        import {Observable} from ‘rxjs’;
        import { map } from ‘rxjs/operators’;

        @Injectable({
        providedIn: ‘root’
        })
        export class EmployeeService {

        selectedEmployee : Employee;
        constructor(private http: HttpClient) {}

        postEmployee(emp : Employee){
        var body = JSON.stringify(emp);
        var headerOptions = new Headers({‘Content-Type’:’application/json’});
        var requestOptions = new requestOptions({method: HttpClient, headers : headerOptions});
        return this.http.post(‘http://localhost:51054/api/Employees’,body, requestOptions).pipe(map(x => x));
        }

        }

  7. 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

  8. 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 the production mode.

  9. 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

  10. 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}}






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

  12. 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?

    Secondly I intend using the project to construct a FAQ list using nested *ngFor. Is this possible?

      1. Hi Shamseer,

        I still get the CORs error even after following the steps in the video. I wonder why the list couldn’t display. CORs is a critical part of the application for me. Before I can continue, I have to get it just right.

  13. 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”.

  14. 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”;

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

  16. 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’

    1. 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 => {})

      import { map } from “rxjs/operators”;
      this.myObservable().pipe(map(data => {}))”

  17. 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’

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

  19. 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’.

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

  21. 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

  22. 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

  23. 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?

  24. 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 appears. I know my employee name spelled incorrectly this should course any issue.

    Please help..?
    Gurnam.

  25. 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 appears. I know my employee name spelled incorrectly this should course any issue.

    Please help..?

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

  27. 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? I have compared your code with mine, but couldn’t see any difference yet.

    Looking forward to hearing from you soon.

      1. Hi Shamseer, S

        Sorry for late update. Thanks for the tutorial.

        I have tried again from the scratch and started working as expected. The tutorial is very good and you provided very good explanation about the project . I like that you have used EF to display the project.

        Do you have another tutorial where you have used some kind of grid structure instead of HTML table?

        The project would be like a. List of customers b.Each customer has multiple orders c. Once you click the order, you display the details of the order.

        Looking forward to hearing from you soon.

        1. Well thanks for the comment.

          I have no tutorial on grid in Angular Application.(I have some in Asp.Net Web Form and MVC). Hopefully I’ll do one in Angular Application too with Angular Material.

  28. 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).

      1. same issue. error like this
        ‘Found the synthetic property @flyInOut. Please include either “BrowserAnimationsModule” or “NoopAnimationsModule” in your application.’ what package i must be install?

        1. No need to install any package,just update app.module.ts file as folows

          import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations’;

          imports :[
          …,
          BrowserAnimationsModule]

  29. 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.\”]}}

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

    thanks

  31. 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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
21 Shares
21 Shares
Share via
Copy link