Online courses in ASP.NET MVC, ASP.NET Core, and Design Patterns conducted by Bipin Joshi. Read more...
Learn ASP.NET MVC / Core, jQuery, Angular, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

Prepare ASP.NET MVC / ASP.NET Core Projects to use Angular 2 in 10 Easy Steps

Now that Angular 2 is finally available, it would be good to try your hands on this new framework. If you are an absolute beginner in Angular 2 you may find preparing your ASP.NET projects a bit confusing. That's because you need to take quite a few steps before you actually start your Angular 2 development. Angular 2 documentation already have two great articles available here and here that guide you to the whole process.

In this article I am going to discuss how you can prepare your ASP.NET MVC and ASP.NET Core projects to use Angular 2. I expect that you are already familiar with ASP.NET MVC / ASP.NET Core. Although you are not expected to have Angular 2 experience, a basic idea about what it does would be helpful. This article won't go into too much of the syntax level detailing. My aim here is to show you how ASP.NET MVC and ASP.NET Core projects can be prepared to use this new framework.

Before you begin

If you never worked with Angular before, you may find that using Angular 2 in ASP.NET applications is a cumbersome process. Remember that unlike jQuery or similar JavaScript libraries, Angular 2 is a full fledge JavaScript framework for building rich client side applications. ASP.NET MVC and ASP.NET Core are server side frameworks. Angular 2 is a client side framework. The two sides can communicate with each other using Ajax. Angular 2 application runs within a browser. As and when required it can make server side calls using Ajax.

Angular 2 makes use of other tools such as TypeScript (although optional). So, you also need to be aware of those tools and dependencies.

Let's begin.

Step 1 : Install NPM

If you have already installed Node Package Manager (npm) this is optional step for you. I still suggest that you download Windows installer for Node and npm from here and install on your machine. Many developers prefer to work with npm from the command prompt rather than using Visual Studio features. If so, you will have the latest installation at your disposal.

Step 2 : Create ASP.NET MVC / ASP.NET Core Project

Begin by creating a new ASP.NET MVC project using Empty project template. Name the project AngularAspNetMvc.

In the same solution add ASP.NET Core project using Empty project template. You can also go for Web Application project template in case you are not comfortable setting up the the empty project for MVC. Name this project as AngularAspNetCore.

Then configure the ASP.NET Core project to use MVC. Also, setup the Startup class to add MVC and Static files middleware. Since these are usual steps I won't go into the details of these steps here.

At this stage your solution explorer will resemble this:

Step 3 : Download Angular 2 framework and its dependencies

Before you code your Angular 2 application you must download and install the Angular 2 framework files in your project. This step is not as simple as adding a <script> reference. It involves some more effort. Basically you need to download Angular 2 and its dependency packages using npm. There are two ways to accomplish this task - using npm command line options and using Visual Studio. Here we will use Visual Studio 2015 to download the necessary packages.

Right click on the AngularAspNetMvc project and open the Add New Item dialog. Then search for npm. This will show an item as shown below:

Select npm Configuration file item. Name the item as Packages.json (default) and click Ok.

The Packages.json file contains all the packages and dependencies required by your application. Add the following markup into the Packages.json file.

{
  "name": "angular-aspnet",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" 
\"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.27",
    "zone.js": "^0.6.23",
    "angular2-in-memory-web-api": "0.0.20",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.2.0",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.2",
    "typings":"^1.3.2"
  }
}

Now add a JSON file to the root of the project using the Add New Item dialog. Name the file as Typings.json.

Add the following markup into the Typings.json file.

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}

Then right click on the Packages.json file and select Restore Packages from the shortcut menu.

Doing so will download all the necessary packages. The downloaded packages will be located in the node_modules under the project root. There will also be a folder named typings. These two folders might appear excluded / hidden from the project. Let them be that way.

Repeat the same process for AngularAspNetCore project.

The following figure shows how the solution explorer looks like after this step is successfully completed.

Notice that AngularAspNetCore project also updates the Dependencies node to reflect the npm packages.

NOTE: If you face any problem in this step you can install Angular 2 from command prompt. To do so open the command prompt and navigate to the project's root folder. Then type npm install command and press enter. The npm will download and install all the necessary files. The node_modules (and typings) folder will also be created for you.

Step 4 : Add TypeScript configuration file

Now that you have downloaded and installed Angular 2 framework files in your project, it's time to write some TypeScript code. However, before you go ahead and do that, you need to configure the TypeScript compiler. You do this by adding tsconfig.json file in the project root. You can again open the Add New Item dialog and search for TypeScript.

After adding the tsconfig.json file add the following markup into it:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "compileOnSave": true,
  "exclude": ["node_modules","scripts"]
}

The above markup is for AngularAspNetMvc project. The tsconfig.json for AngularAspNetCore looks almost identical with one exception. The exclude options specifies wwwroot folder rather than the scripts folder (see below).

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "compileOnSave": true,
  "exclude": ["node_modules","wwwroot"]
}

Don't worry about these folders. It simply conveys to the TypeScript compiler that these two folders should be excluded from the compilation process. This will be clear as you proceed.

Step 5 : Create your Angular 2 client side application using TypeScript

Now add a new folder immediately under the project's root folder. Name the folder as AngularApp. Then add three TypeScript files to this folder one by one - main.ts, app.component.ts and app.module.ts. You can use the Add New Item dialog as before.

While adding the first file Visual Studio may ask the following:

Click on No button and continue adding remaining files.

Now, open app.component.ts file and add the following TypeScript code to it.

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: '<h1>Angular 2 meets ASP.NET!</h1>'
})

export class AppComponent { }

Similarly, open the app.module.ts file and add the following code:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }   from './app.component';

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }

Finally, open the main.ts file and write the following code:

import { platformBrowserDynamic } from 
    '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

After this step your AngularApp folder should look like this:

Make sure to repeat the same process for AngularAspNetCore project.

You just created Angular 2 client side application that will simply display "Angular 2 meets ASP.NET!" in the browser.

Step 6 : Configure Angular 2 module loading

Now it's time to configure how Angular 2 modules are loaded. This is done using SystemJS. To configure SystemJS, add a JavaScript file named systemjs.config.js in the project's root folder.

Write the following code inside the systemjs.config.js file.

(function (global) {
    System.config({
        paths: {
            'npm:': '/scripts/angularframework/'
        },
        map: {
            app: '/scripts/angularapp',
            '@angular/core': 'npm:@angular/core/bundles
/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/
common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/
compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/
platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/
platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/
http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/
router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/
forms.umd.js',
            'rxjs': 'npm:rxjs',
            'angular2-in-memory-web-api': 
'npm:angular2-in-memory-web-api',
        },
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            },
            'angular2-in-memory-web-api': {
                main: './index.js',
                defaultExtension: 'js'
            }
        }
    });
})(this);

Notice the code marked in bold letters. The first bold line sets the path where Angular 2 framework files are located. On the same lines the second bold line sets the path where your Angular 2 application files will be located. In our example we will store these files under Scripts folder (more on that later).

Make sure to do this step for both the projects.

Step 7 : Add HomeController and Index view

Now add HomeController and Index view in the project as you normally do. Open the Index.cshtml file and write the following markup into it.

<html>
<head>
<title>Angular 2 meets ASP.NET</title>
<script src="/scripts/angularframework/core-js/client/shim.min.js">
</script>
<script src="/scripts/angularframework/zone.js/dist/zone.js">
</script>
<script src="/scripts/angularframework/reflect-metadata/Reflect.js">
</script>
<script src="/scripts/angularframework/systemjs/dist/system.src.js">
</script>
<script src="/scripts/systemjs.config.js"></script>
<script>
 System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
    <my-app>Loading...</my-app>
</body>
</html>
</html>

Notice the code marked in bold letters. They are <script> references needed by your application. Notice that the script file paths point to the Scripts folder (more on this later).

The <body> has only one element <my-app>. This element is handled by our Angular 2 component from app.component.ts file. Just to indicate that some processing is going on "Loading..." status indicator is displayed by default.

Step 8 : Build the project

You have come a long way. Just two more steps and you will have your first Angular 2 application running. So, take a deep breath and build both the projects AngularAspNetMvc and AngularAspNetCore. Doing so will not only compile the C# code but also the TypeScript code. If the compilation is successful you will find that the TypeScript code has been converted to JavaScript code under the AngularApp folder.

The following figure how the AngularApp folder looks like for AngularAspNetCore and AngularAspNetMvc projects respectively.

Step 9 : Moving all JavaScript files to Scripts folder

Now that you have developed and build your Angular 2 application, it's time to deploy the JavaScript files. There are two kinds of JavaScript files you need to take into account:

  • Angular 2 framework files and dependencies
  • Your application's JavaScript files (see previous step).

So, far all the Angular 2 framework files are inside node_modules folder and your application files are inside AngularApp folder. There is one more - systemjs.config.js - at the project root.

You need to copy all these files under your "Scripts" folder. For an ASP.NET MVC application there is no specific name or location for the scripts folder. For ASP.NET Core applications all scripts must be placed under wwwroot folder. So, do the following:

  • For AngularAspNetMvc project create Scripts folder under the project root.
  • For AngularAspNetCore project create Scripts folder under the wwwroot folder.

There are two ways to copy the files from node_modules and AngularApp folders to the Scripts folder - manual and automated.

The automated way involves Gulp or Grunt tasks that copy the required files to their destination. This is the recommended option in most of the real-world applications. In this article, however, I will go for manual approach just for the sake of simplicity.

For AngularAspNetMvc project do the following from Windows Explorer (don't do these steps from VS):

  • Copy node_modules folder from project root to the Scripts folder.
  • Rename the newly copied folder to AngularFramework.
  • Copy AngularApp folder from project root to the Scripts folder.
  • Copy Systemjs.config.js file from project root to the Scripts folder.

For AngularAspNetCore project do the following from Windows Explorer (don't do these steps from VS):

  • Copy node_modules folder from project root to the /wwwroot/Scripts folder.
  • Rename the newly copied folder to AngularFramework.
  • Copy AngularApp folder from project root to the /wwwroot/Scripts folder.
  • Copy Systemjs.config.js file from project root to the /wwwroot/Scripts folder.

The following figure shows how the Scripts folder look like for both the projects.

Step 10 : Run the application

Finally, you are ready to witness the magic. Another deep breath and press F5. You will be greeted with the progress indicator as shown below:

After a while the progress message will be replaced by your component's template.

Make sure to run both the applications and confirm whether they behave as expected.

This was just a beginning. Now you can add more code, configuration and functionality as needed by your application. See Angular 2 documentation here.

That's it! Keep coding!!

 




Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 26 Sep 2016



Tags : ASP.NET ASP.NET Core MVC AngularJS JavaScript