Introduction
Since Angular2 is widely used client framework for web and mobile development, in this article I will try to explain the step by step guide to create basic CRUD (create, read, update and delete) application using Angular2 and MVC Web API as backend RESTful APIs. I will create blank ASP.NET MVC application, setup the Angular2 environment and then create the web application that will have two pages, one for home page that will have only one image and second will be User Management page where data will be loaded from SQL Server Database and user would have options to Add new user, Update and Delete existing user. For all database operation, Anguar2 will call RESTful APIs that we will be developing using ASP.NET MVC Web API.
This is a beginner level article and aimed to be written for novice developers and student who have basic knowledge of programming and want to start learning Angular2, C# and RESTful APIs from scratch. If you are experienced developer and only need an overview, you can just download the attached project and go through it. You need Visual Studio and SQL Server Management Studio to develop the project along the article and compile the attached project. Download the Visual Studio 2017 Community and SQL Server Management Studio.
Let's Start
Setup Angular2 Environment
- Open Visual Studio, I am using Visual Studio 2017 Community, you can use Visual Studio 2015 Community with Update 3 installed for
Node.jsandTypeScriptpackages. (read more about Visual Studio 2015 update 3) - Go to File menu and select
File -> New -> Project:

- Enter the Project Name and select your desired .Net Framework (I am using
.Net Framework 4.6for this article). Click onOKbutton:
- Select
MVCfrom next screen and checkWeb APIin Add folders and core reference options since we will create RESTful APIs for CRUD operations. Click onOKbutton:
- The basic ASP.NET MVC project is created, the next step is to prepare it for Angular2 application. Let's do it next steps.
- Right click on Project
Angular2MVCand selectAdd -> New Item:
- Enter
package.jsonin top right search textbox,npm Configuration Filewould be filtered. Click onAddbutton to addpackage.jsonin project:
- We will use
NPM (Node Package Manager)configuration file to manage all Angular2 packages. To read more about NPM, check this link. - Next, copy the Package.json from Angular2 Quick Start GitHub link and paste it in newly added
package.jsonfile inAngular2MVCproject:
- In dependencies section of
package.jsonfile, we can see all Angular2 related packages, check here to see what is difference between^and~sign. - Right click on
package.jsonfile and select optionRestore Packages, Visual StudioNode.jstool will download all dependent packages mentioned inpackage.jsonfile, in future if you need any additional package, just add it inDevDepnedenciessection and restore it, it really makes the life easier:
- You would find new folder
node_modulesadded in project that have all the downloaded packages:
- The next step to let our project know how to get these packages, we will add
systemjs.config.jsfile. Right click onAngular2MVCproject and selectAdd -> JavaScript file:
- Enter the name
systemjs.config.jsinItem namefield and click onOKbutton:
- Copy the
systemjs.config.jsfile's content from Angular2 Quick Start GitHub and paste it in newly addedsystemjs.config.jsfile inAngular2MVCproject:
- Next let’s add the
TypeScript JSON Configuration Fileby right clicking onAngular2MVCproject andAdd -> New Item. SelectTypeScript JSON Configuration Fileand click onOKbutton:
- Copy the
tsconfig.jsfile's content from Angular2 Quick Start GitHub and replace it with newly addedtsconfig.jsfile inAngular2MVCproject:
- In case you are getting compilation error while trying to build, don’t worry. As soon we will start adding any
typescript file, these errors will go away. - Now that our Angular2 setup in ASP.NET MVC is almost completed, it’s time to develop the
User Managementapplication but first we need database with one table where we will save the user information.
create User Database & Entity Framework Model
- Right click on
App_Datafolder and selectAdd -> New item. In Data section, you can find theSQL Server Databaseoption. Select it and specify the name asUserDB.
- Once database is created, double click on
UserDB.mdfdatabase file to open theTables:
- Right click on
UserDB.mdfand selectNew Query. Paste the following SQL query to create theTblUsertable, click onExecutebutton to create the table:
Hide Copy Code
CREATE TABLE [dbo].[TblUser] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[FirstName] NVARCHAR (250) NULL,
[LastName] NVARCHAR (250) NULL,
[Gender] NVARCHAR (250) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

- Right click on
Tablesfolder and select optionRefresh:
- Next lets develop the
ASP.NET MVCside that includes setting upLayoutandIndexpages to load Angular2 main page along MVC controller to load index view and Web API 2.0 controllers for RESTful CRUD (Create,Read,UpdateandDelete) User APIs. - Let’s first go to
App_Startfolder and configure the route to accept any URL since we can define our custom routing in Angular2 (will do it in upcoming steps). Double click onRouteConfig.csfile to edit it and change the URL in default route as following:Hide Copy Codeusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Angular2MVC { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}") routes.MapRoute( name: "Default", url: "{*anything}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }

- Next let’s open our
_Layout.cshtml,clean it up a little bit and add importantJavaScriptsfiles to run the Angular2 application. openViews -> Shared -> _Layout.cshtmlfile. Remove the pre-added top menu and pages link. Add following JS files andsystem.importstatement in header section:
Hide Copy Code
<script src="/node_modules/core-js/client/shim.min.js"></script>
<script src="/node_modules/zone.js/dist/zone.js"></script>
<script src="/node_modules/systemjs/dist/system.src.js"></script>
<script src="/systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
Just a brief intro what are these JS files.
Zone.js: A Zone is an execution context that persists across async tasks. For more info click here. System.src.js & system.import(‘app’): Configurable module loader enabling dynamic ES module workflows in browsers and NodeJS. For more info click here.- Your final
_Layout.cshtmlshould look like following:
- Next let’s create the
ADO.NET Entity Data ModalforUserDBdatabase. Right Click onAngular2MVCproject and selectAdd -> New Folder, specify the nameDBContextor anything you want to:
- Right click on newly created folder
DBContextand selectAdd -> New Item:
- From left Panel under
Visual C#, selectData. On the right side selectADO.NET Entity Data Model. Enter the nameUserDBEntitiesor any of your choice. Click onAddbutton.
- From next screen, select
EF Designer for Data, click onNextbutton:
- Click on
New Connectionbutton on the next screen:
- On next screen, if Data Source is not selected as
Microsoft SQL Server Database file (SqlClient), click onChangebutton and select it:

- In
Database file name, click onBrowsebutton:
- Browse to
UserDBdatabas created in earlier steps and saved inApp_Datafolder, click onOKbutton on bothSelect SQL Server Database FileandConnection Propertieswindows:

- Check the
Save Connection Settings in Web.Config ascheckbox and click onNextbutton:
- In next screen, you can select the Entity Framework version, I am using
6.x, you can use according to your choice:
- On next screen click on
Tablescheckbox, you would see the only one tableTblUser, click onFinishbutton to end the wizard:
- It will take few seconds and finally you would see our database entity model having one table:

- Still at this point, if you would try to compile your project, you may get lot of
typescripterrors, in order to solve it, create the folder with the nameapp, right click on it and selectAdd -> TypeScript File:
- Enter the name
main.tsand clickOK(we will use this file in upcoming steps). Now rebuild the project, it should be successfully build.
Develop User Management RESTful APIs
- Next step is to create the
ASP.NET MVC Web APIsforread,add,updateanddeletethe user. - First we will create the Parent API controller that will have common methods that all API controllers would share, for now we will have only one method to serialize the class object into JSON string for Angular2 front end and also for
UserDBdatabaseDBContextobject to perform database operation in child controller. Right click onControllersfolder and selectAdd -> Controller…:
- Select the
Web API 2 Controller – Emptyand click onAddbutton:
- Enter the name
BaseAPIControllerand click onAddbutton:

- Add following code in
BaseAPIController:
Hide Copy Code
protected readonly UserDBEntities UserDB = new UserDBEntities();
protected HttpResponseMessage ToJson(dynamic obj)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
return response;
}
- Above given code is quite self-explanatory, we are creating
UserDBEntitiesclass object named asUserDBthrough which we can call methods to Load, Add, Update and Delete users.ToJsonmethod is taking any kind of class object, creating theHTTP Response objectwithOKHttpStatusCode and serializing the object to JSON string by calling theJsonConvertmethod fromNewtonsoft.jsonlibrary. Final code should looks like following:
- Next let’s create the
RESTful Web APIsfor User management i.e. load all users from database, add new user, update and delete existing user. We are creating following methods:GETmethod to read all users.POSTmethod to create new user.PUTmethod to update the existing user.DELETEmethod to delete existing user.
- To read more about
HTTP Verbsand methods, click here - Right click on
Controllersfolder and selectAdd -> Controller…
- Select
Web API 2 Controller – Emptyand click onAddbutton:
- Enter the name
UserAPIControllerand click onAddbutton:

- Replace the UserAPIController class code with the following:
Hide Copy Code
public class UserAPIController : BaseAPIController
{
public HttpResponseMessage Get()
{
return ToJson(UserDB.TblUsers.AsEnumerable());
}
public HttpResponseMessage Post([FromBody]TblUser value)
{
UserDB.TblUsers.Add(value);
return ToJson(UserDB.SaveChanges());
}
public HttpResponseMessage Put(int id, [FromBody]TblUser value)
{
UserDB.Entry(value).State = EntityState.Modified;
return ToJson(UserDB.SaveChanges());
}
public HttpResponseMessage Delete(int id)
{
UserDB.TblUsers.Remove(UserDB.TblUsers.FirstOrDefault(x => x.Id == id));
return ToJson(UserDB.SaveChanges());
}
}
UserAPIControlleris inherited fromBaseAPIControllerto useUserDBobject andToJsonmethod to convertUserentity into JSON string and saving it in HTTP Response Message.Get(): Load all users from database and return the HTTP Response Message containing Users entity converted toJSONstring.Post([FromBody]TblUser value): Take the User information from front end and save it to database. Return 1 for successfully saved.Put(int id, [FromBody]TblUser value): Take the existing user id and updated information and update it to database. Return 1 for successfully updated.Delete(int id): Take existing user id, load the user by id and delete it. Return 1 for successfully deleted.
- Final
UserAPIControllerclass should look like following:
Develop Angular2 Application
- Now let’s start the exciting part to write the
Angular2code. Before actually writing the code, it is very important to understand theAngular2architecture, since I am not focusing on writing about Angular2 because you can find plenty of tutorials and free videos about it, let us revise the basic structure ofAngular2if you are lazy enough to go to angular.io website from here:Modules: Every Angular app has at least one Angular module class, therootmodule. The application is launched bybootstrappingits root module. During development, you're likely to bootstrap theAppModulein amain.tsfile that we will create in next steps. Root module is conventionally namedAppModule. InAppModulewe specify allcomponents,servicesor custompipefilters used by application.Components: Component controls the view on screen, you can definepropertiesandmethodsto control the views. If you ever worked with ASP.NET forms, I would say components are like code behind files aspx.cs file where you interact the aspx file through methods and properties.Templates: You define a component's view with its companion template. Atemplateis a form of HTML that tells Angular how to render the component. It is like aaspxfile in ASP.NET form according to my previous step’s example.Metadata: Metadata tells Angular how to process a class. If you would see the component, it is just a class, MetaData tells what is template (code behind or you can HTML) associated with this component, any style sheet or how would use this component specified throughSelectorproperty.Data binding: In simple words, how information or control travels betweentemplateandcomponente.g. when you would click any button in template, how would you getclickevent in component and perform your logic. Angular2 provides following types of data bindings:{{}} interpolationdisplays any variable value declared in component.[ ] property bindingis used to send value from parent component to child component. We will use it in our future chapters.( ) event bindingis used to get any event from template to component. E.g. (click).
Directives: Two kinds of directives exist:structuralandattributedirectives.Structural directivesalter layout by adding, removing, and replacing elements in DOM. E.g.*ngForand*ngIfare used to loop through html element and show/hide the element.Attribute directivesalter the appearance or behavior of an existing element. In templates, they look like regular HTML attributes, hence the name. e.g.ngStylefor style sheet,ngModelfor two-way data binding.
Services: Service is a broad category encompassing any value, function, or feature that your application needs. There is nothing specifically Angular2 about services. Angular2 has no definition of a service. There is no service base class, and no place to register a service. Services example areError,Log,HTTPetc.Componentshould only play the facilitator role between template and user. It should delegate rest of functionality e.g. fetching data from server, deleting or updating, logging, showing error etc. to service.Dependency injection: Dependency injection is a way to supply a new instance of aclasswith the fully-formed dependencies it requires. Most dependencies are services. Angular2 uses dependency injection to provide new components with the services they need. E.g. forHTTPservice we will use dependency injection to provide the service instance to component in upcoming steps.- For more detail and better understanding, please click here.
- Hopefully you have got the basic idea about Angular2 architecture, let create user management page (
Add,Update,DeleteandViewusers) using Angular 2 in ASP.NET MVC using RESTFul APIs as backend services. - In our project, we will create all Angular2 related code in
appfolder as following convention, if you didn’t createappfolder yet, go ahead and create one. If you followed previous steps, you should have one typescript filemain.tsin app folder that we will use to bootstrap theAppModule:
- Before moving further let me show how our final application would look like, it will have two page, one is home page with only large image and second will have table like view with user information, edit and delete button next to each record with one Add button on top of table to Add new user. Each button will open modal pop up where you can perform corresponding functionality, following are the screen shots for both pages and each functionality:


- Now you have basic idea about our final application let’s start developing the Angular2 piece of application, Let’s keep the Angular2 architecture in mind and create the basic architecture of application.
- First lets’ create the Angular2
Modulethat would be the entry point of application. Right click onappfolder and selectAdd -> TypeScript File:
- If you don’t see the
TypeScript Filein second menu, right click onappfolder, selectAdd -> New Item, Search theTypeScrriptand selectTypeScript file, enter the name and selectOKbutton:
- Enter the name of new TypeScript File as
app.module.tsand click onOKbutton:
- Add following code in newly added
app.module.ts:
Hide Copy Code
import { NgModule } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule, HttpModule],
declarations: [],
providers: [{ provide: APP_BASE_HREF, useValue: '/' }],
bootstrap: []
})
export class AppModule { }
- Just to refresh your memory we are using
TypeSciptwith Angular2. If you want to learn more about TypeScript, click here. - If you quickly go through
AppModuleclass, you can see we are importing required libraries e.g.NgModulefrom angular core, similarly we will useReactive formsfor user, we are importingReactiveFormModulefrom angular Forms package. We will keep extendingapp.module.tsfile by adding user components, service, modal pop up etc.- In
NgModulemeta data section:Importscontains modules list.Declarationscontains list of components, we will add user components in next steps.Providerscontains the list of services. We will add service withHTTPoperations to perform user read, add, update and delete operations. Right now, it has basehrefpath.Bootstrapcontains the entry component, we will createapp.component.tsfile in next steps and will add it here.
- In
- The next step is to edit the
main.tsinappfolder and add following code in it:
Hide Copy Code
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

main.tscode is quite self-explanatory.AppModulereference is imported from current folder, making it as entry Module and loading other helper resources (Bootstrapping) for application by usingplateformBrowserDynamicmodule’sbootstrapModulefunction.Bootstrapfunction initialize the Angular2 application, loads the required components, services or other helping resources to run the application. Try to build the project to avoid any error in next steps.- Next, create two TypeScripts file
app.component.tsandapp.routing.tsfor main application component and routing table. We will come back to them later, right click onappfolder and selectAdd -> TypeScript File:
- Enter the name
app.component.tsand click onOKbutton:
- Again click on
appfolder and selectAdd -> TypeScript File, enter the nameapp.routing.tsand click onOKbutton: 

- Next Let’s create the
Homecomponent with only one large picture:
- We will create all user components in new folder, right click on
appfolder and selectAdd -> New Folder, enter the nameComponents: 
- Right click on newly created folder
Componentand selectAdd -> TypeScript File:
- Enter the name
home.component.tsand click onOKbutton:
- Add following code in newly created
home.component.tsfile:
Hide Copy Code
import { Component } from "@angular/core";
@Component({
template: `<img src="../../images/users.png" style="text-align:center"/>`
})
export class HomeComponent{
}

- In
HomeComponent, you can see in MetaData’s template property, we have plain HTML image element from root images folder that will showusers.pngon screen. You can get any picture, save it in images folder and load it inHomeComponent. - Right click on
Angular2MVCproject and selectAdd -> New Folder, enter the folder name asimages:
- Right click on newly added folder
imagesand selectOpen Folder in File Explorer, copy the given below image in opened location: 


- Our
HomeComponentis done, lets view it on screen. We need to do few more steps to do that. The first thing we will do is to create theRoutingTable. If you worked with ASP.NET MVC, this routing table is same as MVC Routing table. We will define custom routes for different view components. In second step, we will create our main application component where we will create the navigation menu and load all view components.- Double click on
app.routing.tsin app folder to edit it and add following code:
- Double click on
Hide Copy Code
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './components/home.component';
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

- In above code we are importing the routing libraries from angular router package and recently created
HomeComponentfrom components folder. In app Routers, thepathproperty is actual URL visible in browser address bar e.g. http://localhost:4500/home. Once we will create theUserComponent, we will add another route for it. - Next double click on
app.component.tsinappfolder to edit it and add following code:
Hide Copy Code
import { Component } from "@angular/core"
@Component({
selector: "user-app",
template: `
<div>
<nav class='navbar navbar-inverse'>
<div class='container-fluid'>
<ul class='nav navbar-nav'>
<li><a [routerLink]="['home']">Home</a></li>
</ul>
</div>
</nav>
<div class='container'>
<router-outlet></router-outlet>
</div>
</div>
`
})
export class AppComponent {
}

AppComponentis slim one having template with known bootstrap code to create navigation bar with one home link only. The routerlinkhomename for Home page is what we defined inapp.routing.ts’s routing table. You can have defined whatever is convenient for you e.g. default, index etc.router-outletacts as place holder for dynamically loaded view components. We also definedselectorproperty (user-app) inAppComponentMetaData section because we will bootstrapAppComponentinAppModuleand use thisselectorin MVC view (index.cshtml) to load it. For more information aboutrouter-outletclick here.- So we have created the Application Component (
AppComponent), let’s go toAppModuleand registerHomeComponentandAppComponentalongroutingtable. After that we will addAppComponentto bootstrap, in order to do this all, update yourapp.module.tsaccording to following:
Hide Copy Code
import { NgModule } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { HomeComponent } from './components/home.component';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing],
declarations: [AppComponent, HomeComponent],
providers: [{ provide: APP_BASE_HREF, useValue: '/' }],
bootstrap: [AppComponent]
})
export class AppModule { }

- You can see, we imported the
HomeComponentandAppComponent, added it in declaration and bootstrapping theAppComponentas entry point to our application. (Bootstrapping is more than just an entry point as discussed in the previous steps, you can search on Google to fully understand it. Here for simplicity, I am only referring it as the entry point). - We are almost there to run our Angular2 application and view the Home page. Go to
Views -> Homeand double click onIndex.cshtmlto edit it:
- Delete the existing code and enter following lines of code:
Hide Copy Code
@{
ViewBag.Title = "Index";
}
<body>
<user-app>Loading…<user-app>
</body>

user-appis theselectorforAppComponent, this is how we use the Component in HTML:
- Next in
Solution Explorer, double click onsystemjs.config.jsand at the bottom addmain.jsinpackagessection:

- Run the project, you should see following web application with
Homepage and large image, you can see in address bar the page URL is ending withhomethat is same URL we defined in routing table for Home page:
- So far, we have created basic architecture for Angular2 in ASP.NET MVC application with one static page. Next step is to create the
User Managementpage that includes loading all users, adding new user, updating and deleting existing user:

- In User Management page, we will use
TypeScript Interface(for User Model),Reactive formsand one third party component Ng2-Bs3-Modal for modal pop up.Interface: Aninterfaceis an abstract type, it does not contain any code as a class does. It only defines thesignatureor shape of an API that’s why we will use interface to define our User Model.Reactive Forms: Angular2 provides two kind of forms,Templatedriven andReactiveForms (Model Driven Forms). There is a great article available for both forms here & here. if you are ASP.NET MVC developer,ReactiveForms is like MVC strongly typedRazorview.
- Next lets create the user
interface. Right click onappfolder and selectAdd -> New Folder. Enter the name of folder asModels:


- Right click on newly created
Modelsfolder and selectAdd -> TypeScript File, enter the file name asuser.ts:


- Enter the following variables in newly created user interface:
Hide Copy Code
export interface IUser {
Id: number,
FirstName: string,
LastName: string,
Gender: string
}

- These
interfaceproperties are same asUsertable in database. The awesome thing about Angular2 is, user object will automatically be mapped to array ofIUserinterface when we will load data from database throughRESTful API, in next steps, we will see how this is being done. - Before moving to
UserComponent, lets create some helping files i.e.Globalvariables andEnumeration. I prefer to save all endpoints, error message and other shared variables inGlobalfile and I am going to create Enumeration for CRUD operation. Right click onappfolder and selectAdd ->New Folder, name the folder asshared:


- Right click on newly created
sharedfolder and selectAdd -> TyepScript File, enter the name asglobal.ts:

- Copy the following code in
global.ts:
Hide Copy Code
export class Global {
public static BASE_USER_ENDPOINT = 'api/userapi/';
}

- This is simple
exportableclass with single static propertyBASE_USER_ENDPOINThaving the base endpoint for user management RESTful APIs. - Again, right click on
sharedfolder and selectAdd -> TypeScript File, enter the name asenum.ts:

- Enter following code in
enum.tsfile:
Hide Copy Code
export enum DBOperation {
create = 1,
update = 2,
delete =3
}

- Enumeration is quite self-explanatory, instead of hard coded string for CRUD operations (“create”, “update”,”delete”), we would use
DBOperationenumeration. - Next, let’s create the important functions to call ASP.NET RESTful Web API for user management using Angular2
HTTPservice. As discussed in previous steps, we will create GET, POST, PUT and DELETE requests for RESTful users APIs that we already have created using ASP.NET MVC Web API in earlier steps. Right click onappfolder and selectAdd -> New Folder, enter the name asService.

- Right click on newly created
Servicefolder and selectAdd -> TypeScript File, enter the name asuser.service.ts:



- Copy the following code in user.service.ts file:
Hide Shrink
Copy Code
Copy Codeimport { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
@Injectable()
export class UserService {
constructor(private _http: Http) { }
get(url: string): Observable<any> {
return this._http.get(url)
.map((response: Response) => <any>response.json())
// .do(data => console.log("All: " + JSON.stringify(data)))
.catch(this.handleError);
}
post(url: string, model: any): Observable<any> {
let body = JSON.stringify(model);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post(url, body, options)
.map((response: Response) => <any>response.json())
.catch(this.handleError);
}
put(url: string, id: number, model: any): Observable<any> {
let body = JSON.stringify(model);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.put(url+id, body, options)
.map((response: Response) => <any>response.json())
.catch(this.handleError);
}
delete(url: string, id: number): Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.delete(url+id,options)
.map((response: Response) => <any>response.json())
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
In order to understand above code, we need to learn about
Observable, you can easily get information about it just by searching it on Google but I would prefer to quickly go through following link:- In just few line,
Observableis more like data stream, opposite topromisemethod (in Angular 1.x),Observabledoesn’t return the response at once but in stream, it provides very helpful methods e.g.map(for mapping result to interface),filter(filter any particular record from array of data) etc.Observablealso providesHTTPrequest handling.Rxjsis an eternal library providing us allObservablemethods. - The first method is
get, that is taking the RESTful API URL as a parameter and returning theObservable<any>, you can also specify the particular type ofinterfaceto return e.g.Observable<IUser[]>but I try to keep it generic. In next lines, http get method is being called by providing the input RESTful API user, calling themapmethod to map the JSON response toanytype, you can specify the particular type too like<IUser[]>response.json(). The typeanyis like adynamicin C#, it does the compile type check.
- One awesome thing about RESTful API is the HTTP verbs like functions names i.e. if function name is starting from GET, PUT, POST or DELETE, we only need base URL (endpoint), by the HTTP call, it automatically determines the corresponding function. It’s obvious, one Web API controller should have one HTTP verb method.
- The other methods POST, PUT and DELETE have almost same function body, creating the http header and sending the
IUserinterface in body where it is being received in Web API controller functions and automatically get converted touserentity because column name does match. - Now that we created the
userservice, let’s add it toAppModule. Double click onapp.module.tsfile inappfolder to edit it. Import theUserServiceby adding following line:
Hide Copy Code
import { UserService} from './Service/user.service'
- Add the
UserServiceinAppModuleproviders section.

- After this, let create the
UserComponent. Right click onComponentsfolder and selectAdd -> TypeScript File:

- Enter the name as
user.component.ts:

- We will create the
templatein separate html file so right click onComponentsfolder again selectAdd-> HTML Page:

- Enter the name as
user.component.html:

- Before going to
UserComponent, let configure one third party component for modal pop ng2-bs3-modal. It’s very simple to use. - Double click on
Package.jsonfile inAngular2MVCproject and add following package indevDependenciessection:
"ng2-bs3-modal": "0.10.4"

- Now let’s download this package from NPM, right click on
package.jsonand selectRestore Packages:

- Double click on
systemjs.config.jsinAngular2MVCproject: - Add the following text in
mapsection:
'ng2-bs3-modal': 'npm:/ng2-bs3-modal'
- Add the following text in packages section:
'ng2-bs3-modal':
{ main: '/bundles/ng2-bs3-modal.js', defaultExtension: 'js' }
- Final update should look like following:

- Now since we got our modal pop up, let’s create the
UserComponentthat will have view all users, add new user, edit and delete existing users. Double click onuser.component.tsfile inapp -> componentsfolder to edit:

- First add following
importstatements:
Hide Copy Code
import { Component, OnInit, ViewChild } from '@angular/core';
import { UserService } from '../Service/user.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { IUser } from '../Model/user';
import { DBOperation } from '../Shared/enum';
import { Observable } from 'rxjs/Rx';
import { Global } from '../Shared/global';
- We are importing Components,
OnInit(to use OnInit event),ViewChild(to access Modal pop up properties). - Then we are importing the
UserSerivcethat executes the HTTP calls to server. - In
UserComponentwe are going to useReactive(Model-driven) forms that I found way more organized and easy to use than template driven forms. To me, it looks like a strongly type ASP.NET MVC razor view, it is also good forunit testing. The form fields, validations and validation errors can be managed on TypeScript side and HTML view has minimum form logic that is good practice to keep the code at one place. To read more about Reactive form, click here. ModalComponentis third party modal pop up that we downloaded in previous steps.IUseris the interface we will use as a Model, to store the user information.DBOperationandGlobalare enumeration and global variables.Observable, we briefly discussed in previous steps. We will usesubscribeandfilterfunction from Rxjs library.- Next copy following Component meta data information under the import statements:
Hide Copy Code
@Component({
templateUrl: 'app/Components/user.component.html'
})
- Since
Useris a parent component and we will not use it in any other component, we are not specifying theSelectorproperty. HTML for User component would be inuser.component.htmlfile. - Next let’s start the
UserComponentclass body and declare the required variable:
Hide Copy Code
export class UserComponent implements OnInit
{
@ViewChild('modal') modal: ModalComponent;
users: IUser[];
user: IUser;
msg: string;
indLoading: boolean = false;
userFrm: FormGroup;
dbops: DBOperation;
modalTitle: string;
modalBtnTitle: string;
}
- We are starting our class with
exportand then with ourUserComponentname, since we will useonInitevent, our class should must implement this. - The next line is starting with
@ViewChild(‘modal’), themodalis placeholder for Modal pop up component that we will create in HTML template. This is the syntax if you want to access any HTML element in TypeScript.:ModalComponentspecify the type of element. - Next we are creating the array of
IUserinterface to hold the list of users and singe IUser to hold one user information for add, edit and delete. Others are few string and Boolean variables that we will use in next steps to show some messages. - As we discussed in previous steps, we will use
Reactive(Model-driven) form, so we create theuserformof Formgroup type. - Next is to add the
constructorfor UserComponent class:
Hide Copy Code
constructor(private fb: FormBuilder, private _userService: UserService) { }
- On great thing about Angular2 is dependency injection, in constructor you can see, we are getting the
FormBuilderandUserServiceinstances though DI. To read more about DI, click here. - So far, our
UserComponentshould look like following:

- At this point, you might be getting an error because still
ngOnInitevent is not implemented, let’s go ahead and addngOnInitevent, we will create and initialize our Reactive User form:
Hide Copy Code
ngOnInit(): void {
this.userFrm = this.fb.group({
Id: [''],
FirstName: ['', Validators.required],
LastName: [''],
Gender: ['']
});
this.LoadUsers();
}
- We are initializing the User form, specifying the form elements and validation rules. Right now form is initialized with empty string ‘’.
- Next let create the
LoadUsersmethod, as name says, this method will call the get method fromUserServiceto load all users from database through RESTful API:
Hide Copy Code
LoadUsers(): void {
this.indLoading = true;
this._userService.get(Global.BASE_USER_ENDPOINT)
.subscribe(users => { this.users = users; this.indLoading = false; },
error => this.msg = <any>error);
}
Subscribeis the part ofObservablethat we discussed in previous steps. Once the user loads would be complete, it will save it inusersvariable. In case of any error, error message would be saved inmsgvariable.indLoadingis the Boolean variable we are using here to show loading message until full response would be loaded.- Next, let’s add three methods to show modal pop up for Add, Update and Delete user. Add following code for these functions:
Hide Copy Code
addUser() {
this.dbops = DBOperation.create;
this.SetControlsState(true);
this.modalTitle = "Add New User";
this.modalBtnTitle = "Add";
this.userFrm.reset();
this.modal.open();
}
editUser(id: number) {
this.dbops = DBOperation.update;
this.SetControlsState(true);
this.modalTitle = "Edit User";
this.modalBtnTitle = "Update";
this.user = this.users.filter(x => x.Id == id)[0];
this.userFrm.setValue(this.user);
this.modal.open();
}
deleteUser(id: number) {
this.dbops = DBOperation.delete;
this.SetControlsState(false);
this.modalTitle = "Confirm to Delete?";
this.modalBtnTitle = "Delete";
this.user = this.users.filter(x => x.Id == id)[0];
this.userFrm.setValue(this.user);
this.modal.open();
}
- These all methods are resembling so let’s take AddUser method and understand it. First, we are storing current DB operation in
dpopsvariable that is ofDBOperationenumeration type. Next, we are callingSetControlsStatemethod that will enable or disable form controls. Next variables are setting the modal pop up heading and button title. In only AddUser function, we are resetting form to clearing the form. Next, we are callingmodal.open()function to view the modal pop up. In edit and delete user method, we are gettingUserIDas parameter, calling the Observable’s filter method to get single user from users list. The filter syntax is like anonymous method in C#. the next line is to assign the single user to user form that will set the value to the front end, piece of cake. - Let’s create the
SetControlsStatethat will enable or disable the form.Reactiveform has enable and disable methods that make the control read-only and editable.
Hide Copy Code
SetControlsState(isEnable: boolean)
{
isEnable ? this.userFrm.enable() : this.userFrm.disable();
}
- The next method is
onSubmitthat actually get the form values and based onDBOperationenumeration value, it performs add, update and delete operation, we are using simple switch statement, paste following code:
Hide Shrink
Copy Code
Copy CodeonSubmit(formData: any) {
this.msg = "";
switch (this.dbops) {
case DBOperation.create:
this._userService.post(Global.BASE_USER_ENDPOINT, formData._value).subscribe(
data => {
if (data == 1) //Success
{
this.msg = "Data successfully added.";
this.LoadUsers();
}
else
{
this.msg = "There is some issue in saving records, please contact to system administrator!"
}
this.modal.dismiss();
},
error => {
this.msg = error;
}
);
break;
case DBOperation.update:
this._userService.put(Global.BASE_USER_ENDPOINT, formData._value.Id, formData._value).subscribe(
data => {
if (data == 1) //Success
{
this.msg = "Data successfully updated.";
this.LoadUsers();
}
else {
this.msg = "There is some issue in saving records, please contact to system administrator!"
}
this.modal.dismiss();
},
error => {
this.msg = error;
}
);
break;
case DBOperation.delete:
this._userService.delete(Global.BASE_USER_ENDPOINT, formData._value.Id).subscribe(
data => {
if (data == 1) //Success
{
this.msg = "Data successfully deleted.";
this.LoadUsers();
}
else {
this.msg = "There is some issue in saving records, please contact to system administrator!"
}
this.modal.dismiss();
},
error => {
this.msg = error;
}
);
break;
}
}
- The code is quite simple and self-explanatory, once we submit the form, it sends all the values that we can get through
.valueproperty. That’s pretty much it on TypeScript side. - Let’s write the HTML template for
UserComponent. Double click onuser.component.htmlto edit it:

- Copy the following code in
user.component.html:
Hide Shrink
Copy Code
Copy Code<div class='panel panel-primary'>
<div class='panel-heading'>
User Management
</div>
<div class='panel-body'>
<div class='table-responsive'>
<div style="padding-bottom:10px"><button class="btn btn-primary" (click)="addUser()">Add</button></div>
<div class="alert alert-info" role="alert" *ngIf="indLoading"><img src="../../images/loading.gif" width="32" height="32" /> Loading...</div>
<div *ngIf='users && users.length==0' class="alert alert-info" role="alert">No record found!</div>
<table class='table table-striped' *ngIf='users && users.length'>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of users">
<td>{{user.FirstName}}</td>
<td>{{user.LastName}}</td>
<td>{{user.Gender}}</td>
<td>
<button title="Edit" class="btn btn-primary" (click)="editUser(user.Id)">Edit</button>
<button title="Delete" class="btn btn-danger" (click)="deleteUser(user.Id)">Delete</button>
</td>
</tr>
</tbody>
</table>
<div>
</div>
</div>
<div *ngIf="msg" role="alert" class="alert alert-info alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
{{msg}}
</div>
</div>
</div>
<modal #modal>
<form novalidate (ngSubmit)="onSubmit(userFrm)" [formGroup]="userFrm">
<modal-header [show-close]="true">
<h4 class="modal-title">{{modalTitle}}</h4>
</modal-header>
<modal-body>
<div class="form-group">
<div>
<span>Full name*</span>
<input type="text" class="form-control" placeholder="First Name" formControlName="FirstName">
</div>
<div>
<span>Full name</span>
<input type="text" class="form-control" placeholder="Last Name" formControlName="LastName">
</div>
<div>
<span>Gender*</span>
<select formControlName="Gender" class="form-control">
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
</modal-body>
<modal-footer>
<div>
<a class="btn btn-default" (click)="modal.dismiss()">Cancel</a>
<button type="submit" [disabled]="userFrm.invalid" class="btn btn-primary">{{modalBtnTitle}}</button>
</div>
</modal-footer>
</form>
</modal>
- If you look at the Add button, we are calling the
AddUserfunction by using(click)function that is the example ofeventbinding we discussed in previous steps. - Next, we are using
*ngIf, thestructural directivesto show the loading message based onindLoadingBoolean variable. - Next, we are using
*ngForstructural directive to loop through theusersarray and showing the user information. - Next code is for modal pop up, you can see
#modalplaceholder that we are using to access it on TypeScript side through@ViewChildto access open and dismiss functions. - Next we are creating the form,
(ngSumbit)event will send the form data to TypeScriptonSumitfunction. - Through
[formgorup]property binding we are assigning theuserformthat we created on TypeScript side. We are telling our template the corresponding form control throughformControlNameproperty. - Add and Edit buttons will be disabled until form gets valid. This is being handled by
[disabled]property binding untiluserform.invalidproperty get enabled. - That’s it with
UserComponent, now let’s add the routing for UserComponent and add the itAppModule. - Double click on
app.routing.tsinappfolder to edit it:

- Import the
UserComponentby following code:
Hide Copy Code
import { UserComponent } from './components/user.component';
- Add the
UserComponentroute as following:
Hide Copy Code
{ path: 'user', component: UserComponent }
- The final
app.routing.tsshould look like following:

- Edit the
app.component.tsby double clicking on it:

- Add User Component in App Module:
Hide Copy Code
import { UserComponent } from './components/user.component';
- Add the
UserComponentin declaration section, the finalAppModuleshould look like following:

- Add menu item for User Management, double click on
app.component.tsand add following line:
Hide Copy Code
<li><a [routerLink]="['user']">Users Management</a></li>
- Final
app.component.tsshould be following:

- Compile and run the application.