Preparation Of ASP.NET MVC / ASP.NET Core Projects To Utilise Angular 2
With the availability of Angular 2; let’s try hands hands on this new framework. Angular 2 documentation already have many great articles available online; that could guide you to the whole process. In this article we shall discuss how you can prepare your ASP.NET MVC and ASP.NET Core projects to use Angular 2.
Let's start.
Step 1 :Install NPM
Those who already has NPM installed; this is an optional step. Many programmers prefer to work with NPM from the command prompt instead of using Visual Studio features.
Step 2 : Develop ASP.NET MVC / ASP.NET Core Project
Start by designing a new ASP.NET MVC project using Empty project template. Name it AngularAspNetMvc.
In the same solution you must add ASP.NET Core project using Empty project template. You could also prefer Web Application project template instead of empty project for MVC. Name it as AngularAspNetCore.
Then configure the ASP.NET Core project to use MVC.
Step 3 : Download Angular 2 framework and its dependencies
Before you start coding you should download and install the Angular 2 framework files in your project. This step involves more effort. Actually you need to download Angular 2 and its dependency packages using NPM.
There are two methods to do this task - using NPM command line options and using VS. Here Visual Studio 2015 is used to download the necessary packages.
Select NPM Configuration file item. Name the item as Packages.json (default) and click Ok.
The Packages.json file has all the packages and dependencies needed. 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 it 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.
All the necessary packages will get downloaded.
Repeat the same method for AngularAspNetCore project.
To mention AngularAspNetCore project also updates the Dependencies node to reflect the NPM packages.
Step 4 : Add TypeScript configuration file
Before you proceed you need to configure the TypeScript compiler. You can do this by adding tsconfig.json file in the project. You can open the Add New Item dialog and search for TypeScript.
After adding the tsconfig.json file add the below mentioned 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 identical with one difference. The exclude options specify wwwroot folder and not the scripts folder as given 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"]
}
Step 5 : Design your Angular 2 client side application using TypeScript
Now add a new folder under the project's root folder. Name it as AngularApp. Then add 3 TypeScript files to this folder : main.ts, app.component.ts and app.module.ts.
Click on No button and add 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:
Ensure to repeat the same process for AngularAspNetCore project.
Step 6 : Configure Angular 2 module loading
This is done using SystemJS. First 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).
Ensure to do this step for both the projects.
Step 7 : Add HomeController and Index view
Next add HomeController and Index view in the project. Open the Index.cshtml file and write the following codes 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>
The codes marked in bold letters are <script> references required by the application.
The <body> has one element <my-app>. This element is handled by Angular 2 component from app.component.ts file.
Step 8 : Develop the project
Build both the projects AngularAspNetMvc and AngularAspNetCore. This will help you 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.
Step 9 : Moving all JavaScript files to Scripts folder
It's time to deploy the JavaScript files. There are two types of JavaScript files you need to take into account:
Angular 2 framework files and dependencies
Your application's JavaScript files (see previous step).
You copy all the 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.
For AngularAspNetMvc project do the following from Windows Explorer and not 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 and not 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.
Step 10 : Run the application
Now time to press F5.
Make sure to run both the applications and confirm if they behave as expected.
After this you need to add more codes, configuration and functionality as required by your application.
We conclude now..... Enjoy coding!
Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.
If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRBtech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.
Stay connected to CRBtech for more technical optimization and other updates and information.