Introduction
In my previous article "Build Your First ASP.NET MVC Core Application", I explained how to create the Application, using ASP.NET Core and in my article “Build Your First Angular 2 Application With Type Script", I have explained how to create an Angular 2 Application, using TypeScript.
In this article, I will explain how to create SPA Application using an ASP.NET Core and Angular 2 with TypeScript.
Prerequisites
The following software needs to be installed in our system before starting the work.
The following software needs to be installed in our system before starting the work.
- .NET Core 1.1.
- TypeScript 2.0.
- Node JS version 6 or later.
- Editor such as VS 2017 or VS Code.
The easiest way to create Angular SPA (Single Page Application) Application with an ASP.NET Core is to use project template. There are many project templates, which are are available on Nuget. To install SPA template, we need to run the command given below from the command prompt.
- dotnet new --install Microsoft.AspNetCore.SpaTemplates::*
After successful installation of the templates, it lists down all the installed templates. We can use any installed template to create SPA.
Here, I want to create SPA, using MVC ASP.NET Core with Angular, so we need to execute the command given below, using the command prompt at the place, where you want to create an Application.
- dotnet new angular
After successful creation of an Application, we need to download dependencies of an Angular 2 as well as an ASP.NET Core. To download the dependencies of Angular, we need to execute the command given below, using the command prompt. This command reads package.json file and download the dependencies.
- npm install
- dotnet restore
Once all the project dependencies are installed and if we have an editor such as VS 2017, then we can run the project by pressing CTRL + F5.
Alternatively, we can run the project by running the command given below from the command prompt.
- dotnet run
Output
Structure of the Project
When we look at the structure of the project, it contains the files related to configuration such as package.json, tsconfig.json and Angular project related files as well as ASP.NET Core MVC related files.
This project initially bootstraps as an ASP.NET Core MVC project by calling an index action method of Home controller. Index.cshtml file internally bootstraps an Angular component i.e. app.component.ts.
This project template puts all Angular related code in ClientApp folder. This folder also contains UI testing related configuration and the code.
Adding New Module in the project template
Adding New Module in the project template
To add new module to this project, first we need to create new folder “MyDetails” under the ClientApp>> app>> Components folder.
Next step is to create module, component and template view.
mydetails.Component.ts
- import { Component } from '@angular/core';
- @Component({
- selector: 'mydetails',
- templateUrl: './mydetails.Component.html'
- })
- export class MyDetailsComponent {
- }
- <h1>
- Welcome to my details page.
- </h1>
navmenu.component.html
- <li [routerLinkActive]="['link-active']">
- <a [routerLink]="['/my-detail']">
- <span class='glyphicon glyphicon-link'></span> My New Link
- </a>
- </li>
The next step is to import this component to app.module (root module) and also define the path to router module. The router module contains two property paths (selector) and the component. The code is given below for app.module.ts file (Application root module).
app.module.ts
- import { NgModule } from '@angular/core';
- import { RouterModule } from '@angular/router';
- import { UniversalModule } from 'angular2-universal';
- import { AppComponent } from './components/app/app.component'
- import { NavMenuComponent } from './components/navmenu/navmenu.component';
- import { HomeComponent } from './components/home/home.component';
- import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
- import { CounterComponent } from './components/counter/counter.component';
- import { MyDetailsComponent } from './components/myDetails/mydetails.Component';
- import { FormsModule } from '@angular/forms';
- @NgModule({
- bootstrap: [ AppComponent ],
- declarations: [
- AppComponent,
- NavMenuComponent,
- CounterComponent,
- FetchDataComponent,
- HomeComponent,
- MyDetailsComponent
- ],
- imports: [
- FormsModule,
- UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
- RouterModule.forRoot([
- { path: '', redirectTo: 'home', pathMatch: 'full' },
- { path: 'home', component: HomeComponent },
- { path: 'counter', component: CounterComponent },
- { path: 'fetch-data', component: FetchDataComponent },
- { path: 'my-detail', component: MyDetailsComponent },
- { path: '**', redirectTo: 'home' }
- ])
- ]
- })
- export class AppModule {
- }
Let’s extend this example and fetch observable data from the Web API (MVC) and display it on the screen. Here, I have created a model named “Personal”. I am filling all the properties of this model in an action method of controller class name “MyDetailsController”. Following is the definition of Personal and MyDetailsController class.
Personal.cs
- namespace test
- {
- public class Personal
- {
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string AdharNumber { get; set; }
- public string Email { get; set; }
- public string PhoneNumber { get; set; }
- }
- }
- using Microsoft.AspNetCore.Mvc;
- namespace test.Controllers
- {
- [Route("api/[controller]")]
- public class MyDetailsController : Controller
- {
- static Personal _personal = new Personal {
- FirstName = "Jignesh",
- LastName = "Trivedi",
- AdharNumber = "45454 4545 55",
- Email = "[email protected]",
- PhoneNumber = "988988989"
- };
- [HttpGet("[action]")]
- public Personal Mydetails()
- {
- return _personal;
- }
- }
- }
For client side, bind the data and I have created class named “Personal”. It contains same properties as Server side class.
mydetails.model.ts
- export class Personal {
- firstName: string;
- lastName: string;
- adharNumber: string;
- email: string;
- phoneNumber: string
- }
The next step is to create a Service. This Service retrieves from Web API (MVC), using http Service and the GetData method of this servicereturn observable of the Personal data. This observable stream can be published by any source. The subscription is required to specify the actions to be taken when the Web request processes the success or fail event.
mydetails.Services.ts
- import { Injectable } from '@angular/core';
- import { Http, Response, RequestOptions,Headers } from '@angular/http';
- import { Observable } from 'rxjs/Observable';
- import 'rxjs/add/operator/map';
- import { Personal } from './mydetails.model'
- @Injectable()
- export class MyDetailService {
- public personalDetail: Personal;
- public headers: Headers
- constructor(private http: Http) {
- this.headers = new Headers();
- this.headers.append('Content-Type', 'application/json');
- }
- GetData(): Observable<Personal> {
- let person$ = this.http.get('/api/MyDetails/Mydetails').map(response => response.json());
- return person$;
- }
- }
Now, I am injecting this Service into the component and calling Service‘s Getdata method. Here, I have subscribes the success event and copied Service return data to the local variable.
mydetails.Component.ts
- import { Component } from '@angular/core';
- import { MyDetailService } from './mydetails.services'
- import { Personal } from './mydetails.model';
- @Component({
- selector: 'mydetail',
- templateUrl: './mydetails.Component.html',
- providers: [MyDetailService],
- styleUrls: ['./myDetails.component.css']
- })
- export class MyDetailsComponent {
- public personalDetail: Personal = new Personal();
- constructor(private myDetailService: MyDetailService) {
- this.myDetailService.GetData().subscribe(data => {
- this.personalDetail = data;
- });
- }
- }
To display the data, I have made some changes to the template view of the component.
mydetails.Component.html
- <h1>
- Welcome to my details page.
- </h1>
- <table>
- <tr>
- <td><strong> First Name : </strong></td>
- <td><input [(ngModel)]="personalDetail.firstName"/> </td>
- </tr>
- <tr>
- <td><strong> Last Name : </strong></td>
- <td><input [(ngModel)]="personalDetail.lastName"/> </td>
- </tr>
- <tr>
- <td><strong> Adhar Number : </strong></td>
- <td><input [(ngModel)]="personalDetail.adharNumber"/> </td>
- </tr>
- <tr>
- <td><strong> Email : </strong></td>
- <td><input [(ngModel)]="personalDetail.email"/> </td>
- </tr>
- <tr>
- <td><strong> Phone Number : </strong></td>
- <td><input [(ngModel)]="personalDetail.phoneNumber"/> </td>
- </tr>
- <tr>
- <td colspan="2"><input type="button" value="Save" (click)="save()" /></td>
- </tr>
- </table>
Also, add some style to the template view of the component.
myDetails.component.css
- td{
- padding-top: 10px;
- }
Now, I am re-running the Application. Here whatever data is coming from the Server (Web API), it displays on a screen.
Output
Summary
In this article, we learnt how to create SPA Application, using an ASP.NET Core and an Angular 2. Also, we learnt how to get observable data and bind to the template.
In this article, we learnt how to create SPA Application, using an ASP.NET Core and an Angular 2. Also, we learnt how to get observable data and bind to the template.

Kevin DoyonPosted Oct 11, 2017, 3:01 PM
I dont quite understand the template. What is the point of the Home MVC View? It also hardcodes a title of Home Page (which is visible in your My Details page). Does that mean I am supposed to create a MVC view for every page of my application? Maybe this is for server-side rendering?
Amit KumarPosted May 20, 2017, 4:28 PM
Jignesh Trivedi: Thanks for this article. I have a question. Can I use angular-cli after following your steps . e.g I have created an application , by following your steps. Now I want to use angular-cli to speed up my development.
Former memberPosted Apr 21, 2017, 8:05 AM
Last question that angular related libs only npm only can download? we can't download manually and add in project done by VS IDE ?
kzelda linkPosted Apr 21, 2017, 6:00 AM
Thx , great article
Former memberPosted Apr 21, 2017, 5:38 AM
If we do not work with node.js then why some one will install it? why node.js is important for angular and type script ? without node.js people develop web apps with angular v1+ with asp.net then why node.js become mandatory for angular2 ? will u plzz answer. thanks
Mohammad KhalidPosted Apr 21, 2017, 1:43 AM
Very nice article .. Thank you for sharing this.
Former memberPosted Apr 20, 2017, 6:17 PM
How to check node.js has been install with my vs2017 community ed?
Former memberPosted Apr 20, 2017, 8:59 AM
Node.js does not install with VS2017 community ed setup ? where and how to install node.js......please give me some direction.
Former memberPosted Apr 20, 2017, 6:58 AM
How to work with angular 2 with typescript from VS2017 ? because i found no typescript template in VS2017. would u guide me.