Step-By-Step Solution To Set Up Angular With Your Visual Studio 2017

Motive

In this blog, we will understand the concepts of Angular 2, Web API, and SQL Server. 

Introduction - Angular 2
  • Angular (commonly referred to as "Angular 2+" or "Angular v2 and above") is a TypeScript-based product of Google and created by a community of individuals and corporations.
  • This is not an MVC framework.
  • It is an open-source front-end web application platform.
WebAPI
  • A server-side web API is a programmatic interface consisting of one or more publicly exposed endpoints to a defined request–response message system, typically expressed in JSON or XML, which is exposed via the web—most commonly by means of an HTTP-based web server
OverView

This is a step-by-step solution to set up Angular 2 with your Visual Studio 2017. In this project, I will create a simple web application for beginners. This application is used to bind the drop-down. We are just five steps away from Angular 2 application.
  • Step 1 - Create a database (SQL Server).
  • Step 2 - Create an API (web API)
  • Step 3 - Create a connection with SQL and get data from SQL using Web API.
  • Step 4 - Setup angular2 with Web API.
  • Step 5 - Bind  drop-down using Angular 2.
Needs
  • Node JS (node version is 4.6.x or greater)
  • NPM (Node Package Manager)( version 3.x.x or greater)
  • Visual Studio 2017.
  • TypeScript (2.2 or greater).

Now, set up Angular 2 files with Visual Studio.

Step 1

  1. Create table Country(CountryId int Identity (1,1),CountryName varchar(50))  
  2.   
  3. insert intoCityvalues(India);  
  4. insert intoCityvalues('Canada');  
  5. insert intoCityvalues(Australia); 
Angular
Step 2 - CREATE WEB API
  • Open Visual Studio 2017 and create a new project. 
  • Go to File=>New=> Project=>Select Web from Right Side =>Select ASP .Net Web Application (.NET FrameWork).
  • Give a name to the project and select the directory where you want to create the project.

Angular
  • Now, you will see a new window. Please select MVC project. 

    Angular
Angular 

Step 3 - Create a connection with SQL and get data from SQL using Web API.

You can do it with only three steps.
  • SqlConnetion
  • Model
  • Buisnesslogic

The following code is used to GET the data from database.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. namespace WebApplication1.api {  
  10.     [RoutePrefix("api/DropDownBind")]  
  11.     publicclassDropDownBindController: ApiController {  

  12.         /// Method for calling getcountrylist and return list of country to service of angular  
  13.         [HttpGet]  
  14.         public IHttpActionResult GetCountry() {  
  15.             var objlist = GetCountryList();  
  16.             return Ok(objlist.ToList());  
  17.         }  

  18.         /// Method to get from Database  
  19.         public List < CountryModel > GetCountryList() {  
  20.             SqlConnection con = new SqlConnection("Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=sa;Password=123");  
  21.             con.Open();  
  22.             string sql = null;  
  23.             SqlCommand cmd = new SqlCommand(sql, con);  
  24.             SqlDataAdapter sd = new SqlDataAdapter(cmd);  
  25.             List < CountryModel > listdetail = new List < CountryModel > ();  
  26.             try {  
  27.                 cmd.CommandText = "Select * from Country";  
  28.                 sd.SelectCommand = cmd;  
  29.                 DataTable dt = new DataTable();  
  30.                 sd.Fill(dt);  
  31.                 for (int i = 0; i < dt.Rows.Count; i++) {  
  32.                     CountryModel md1 = new CountryModel();  
  33.                     md1.CountryName = dt.Rows[i]["CountryName"].ToString();  
  34.                     md1.CountryId = Convert.ToInt16(dt.Rows[i]["CountryId"].ToString());  
  35.                     listdetail.Add(md1);  
  36.                 }  
  37.             } catch (Exception ex) {  
  38.                 Console.WriteLine(ex);  
  39.             }  
  40.             return listdetail;  
  41.         }  

  42.         // Model or Properties for Country  
  43.         publicclassCountryModel {  
  44.             publicint CountryId {  
  45.                 get;  
  46.                 set;  
  47.             }  
  48.             publicstring CountryName {  
  49.                 get;  
  50.                 set;  
  51.             }  
  52.         }  
  53.     }  
  54. }  
NOTE
Please change your connection string.

Please check it in the following images.

Angular 

Angular
 
Now build your project. While running your project, if you get an error in your output like "multiple actions were found", then please check:

appStart =>webApiConfig.cs=> Replace routetemplate: (api/{controller}/{id}), with routetemplate: (api/{controller}/{action}/{id}),

Angular
 
Step 4 - Set up Angular 2 with Web API project 
  • Go to the following link and download from this link.
  • Download Angular project configuration from QuickStart.
    • · src folder and it’s all contents
    • · bs-config.json file
    • · package.json file
    • · tslint.json file

  • Copy these above files and paste into your web application root directory. Now click on show all files in the solution explorer and right click on all those folder and files which you just pasted to your web app project and include these files in the solution.

    Angular

  • Restore package on right -- click on "package.json" file and select "Restore Packages" from the context menu.

    Angular

  • After restoration completion, you will see the message "Installing Packages Complete".

Note the following things carefully. Don’t include node_module in your solution.

Build the Angular 2 application using the folllowing steps,
  • First => make your index.html file as your start up page. Right-click on src/index.html file in the solution explorer and select option “Set As Start Page”.
  • To run your Angular project using Visual Studio via F5, you need to make the following changes,

    • Change (in Index.html) the base path from <base href=”/”> to <base href=”/src/”> in the HTML file under src/app folder.
    • Change the scripts also to use /node_modules with a slash instead of node_modules without the slash in the html file.
    • Change(in systemjs.config.js file ),the NPM path from node_modules/ to /node_modules/ in the src/systemjs.config.js file.
    • Run Aplication.
If you get this following error while running, please "set as startup page" to index.html.

And again run this,

Angular 
 
Final OutPut

Angular 

Step 5 - Bind dropdown using angular 2

First define an interface which will be the class definition to store the information from our ‘api’ file. Create a file called County.ts

Right click on app inside src (src=>app)

Add=>typescript file=>Country.ts

Insert the following code,

  1. exportinterface ICountry {  
  2.     CountryId: number;  
  3.     CountryName: string;  
  4. }  
Angular

Now add CountryService.ts file,

Angular

Now change "app.component.ts".
Angular

Code of app.component.ts
  1. import { Component } from '@angular/core';  
  2. import { ICountry } from './Country';  
  3. import { CountryService } from './CountryService';  
  4. import { Http, Response } from '@angular/http';  
  5. import { Observable } from 'rxjs/Observable';  
  6. import 'rxjs/add/operator/map';  
  7. @Component({  
  8. selector: 'my-app',  
  9. template: `<h2>{{name}},<h2><br>  
  10. Country:  
  11. <select >  
  12.    <option value="0">Select</option>  
  13.       <option *ngFor="let obj of Country" value="{{obj.CountryId}}">  
  14.       {{obj.CountryName}}  
  15.    </option>  
  16. </select>`,  
  17. providers: [CountryService]  
  18. })  
  19. export class AppComponent {  
  20.    name = 'Hello Nav';  
  21.    Country: ICountry[];  
  22.    constructor(private componentName: CountryService) {  
  23. }  
  24. ngOnInit(): void {  
  25.    this.componentName.getCountry()  
  26.    .subscribe(response => (this.Country) = response);  
  27. }  
  28. }  
Now change your app.module.ts file.

Code => app.module.ts 
  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { HttpModule } from '@angular/http';  
  4. import { AppComponent } from './app.component';  
  5. import { CountryService } from './CountryService';  
  6. @NgModule({  
  7. imports: [BrowserModule, HttpModule ],  
  8.    declarations: [ AppComponent ],  
  9.    bootstrap: [ AppComponent ]  
  10. })  
  11. export class AppModule { }  
Angular
 
Finally build your project,

Angular
 
Thanks for reading.