You can download the Source Code from this link Download Source Code
In this article, we will see in detail of using Angular2 with ASP.NET Core 1.0 RC2.
You can also view our previous article http://www.c-sharpcorner.com/article/Asp-Net-core-1-0-mvc-6-using-web-api-and-angularjs/
In this article, we will see in detail of how to
Reference website: Angular2
Visual Studio 2015: You can download it from here.
ASP.NET Core 1.0 RC2: download link https://www.microsoft.com/net , https://www.microsoft.com/net/core#windows
Code Part
After installing both Visual Studio 2015 and ASP.NET Core 1.0 RC2. Click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and select ASP.NET Core Web Application. Enter your Project Name and click OK.
Next select Web Application. If you are not hosting in Cloud then you can uncheck the Host in the Cloud at the bottom right corner. Click OK
Now we have created our project.
The TypeScript JSON file will file specifies the root files and the compiler options required to compile the project. To know more about TypeScript JSON Configuration kindly visit this sites
http://www.typescriptlang.org/docs/handbook/tsconfig-json.html ,To create the TypeScript JSON file right click on your Project and Click Add New Item.
Select TypeScript JSON Configuration File and Click ok. The File will look like below image.
Now copy the below code and replace with your config file.
"compilerOptions"
: {
"emitDecoratorMetadata"
:
true
,
"experimentalDecorators"
"module"
"commonjs"
"moduleResolution"
"node"
"noImplicitAny"
false
"noEmitOnError"
"removeComments"
"target"
"es5"
"sourceMap"
Now we need to add a NPM Configuration File for adding a grunt package to run our java scripts.
As we have created as a Web Application the NPM Configuration File will be located in our project.
By default we can’t view our NPM Configuration File. The NPM Configuration File will be in the name of “package.JSON” . TO view that from the Solution Explorer click on “Show All Files”
Now open the “package.JSON” file. Now first we need to change the name to our project Solution name and add our grunt package .we can see the code here below the image.
Here we have changed the name as our Solution name and also added the grunt package.
{
"name"
"test"
"version"
"0.0.0"
"private"
"devDependencies"
"grunt"
"1.0.1"
"grunt-contrib-copy"
"1.0.0"
"grunt-contrib-uglify"
"grunt-contrib-watch"
"grunt-ts"
"5.5.1"
"gulp"
"3.8.11"
"gulp-concat"
"2.5.2"
"gulp-cssmin"
"0.1.7"
"gulp-uglify"
"1.2.0"
"rimraf"
"2.2.8"
}
Now save the package.json file and you should be able to see a grunt package under Dependencies/ npm Folder will be first Resorted and then installed.
Restoring :
All Installed:
Grunt is used to build all our client-side resources like JavaScript for our project.
The first step is to add a Grunt file to our project. Right click our project and Select Grunt Configuration File and click Add.
After creating the file, now we need to edit this file to add load plugins, configure plugins and define tasks
Here in our Grunt file we have first load plugins which we have added in our npm. Using loadNpmTask here we load 'grunt-contrib-copy ,'grunt-contrib-uglify' , 'grunt-contrib-watch'
Next, we configure the grunt add the app.js file in our wwwroot folder. All our Script files from Scripts folder result will be added in this app.js file. Next, we need to copy all the Script file from 'node_modules/ to our local js Folder.
The watch plugin will be used to check for any changes on JavaScript file and update it app.js with all new changes.
/*
This file in the main entry point for defining grunt tasks and using grunt plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409
*/
module.exports =
function
(grunt) {
grunt.loadNpmTasks(
'grunt-contrib-copy'
);
'grunt-contrib-uglify'
'grunt-contrib-watch'
'grunt-ts'
grunt.initConfig({
ts:
base:
src: [
'Scripts/app/boot.ts'
'Scripts/app/**/*.ts'
],
outDir:
'wwwroot/app'
tsconfig:
'./tsconfig.json'
},
uglify:
my_target:
files: [{
expand:
cwd:
'**/*.js'
dest:
}]
options:
sourceMap:
// Copy all JS files from external libraries and required NPM packages to wwwroot/js
copy: {
main: {
files:
[{
flatten:
'Scripts/js/**/*.js'
'node_modules/es6-shim/es6-shim.min.js'
'node_modules/systemjs/dist/system-polyfills.js'
'node_modules/angular2/bundles/angular2-polyfills.js'
'node_modules/systemjs/dist/system.src.js'
'node_modules/rxjs/bundles/Rx.js'
'node_modules/angular2/bundles/angular2.dev.js'
'wwwroot/js/'
filter:
'isFile'
// Watch specified files and define what to do upon file changes
watch: {
scripts: {
files: [
'Scripts/**/*.js'
tasks: [
'ts'
'uglify'
'copy'
]
});
// Define the default task so it will launch all other tasks
grunt.registerTask(
'default'
, [
'watch'
]);
};
We are using NPM to install our Angular2 in our web application. Open our Package.JSON file and the below dependencies.
"dependencies"
"@angular/http"
"2.0.0-rc.1"
"angular2"
"^2.0.0-beta.8"
"angular2-jwt"
"0.1.16"
"angular2-meteor"
"0.5.5"
"cors"
"2.7.1"
"systemjs"
"0.19.22"
"es6-promise"
"^3.0.2"
"es6-shim"
"^0.33.3"
"reflect-metadata"
"0.1.2"
"rxjs"
"5.0.0-beta.2"
"tsd"
"^0.6.5"
"zone.js"
"0.5.15"
The edited Package.json file will look like below image.
Save the file and wait for few seconds to complete all decencies installed.
Now it’s time to create our Angular2 application. First, create a Folder named Scripts. Right click our project and click add new Folder and name the folder name as “Scripts”. Now we will create our TypeScript files inside this Scripts folder.
To work with Angular2 we need to create 2 important TypeScript file.
1) Component File where we write our Angular coding.
2) Boot file: To run our component app.
Right Click on Scripts folder and click on add new Item. Select TypeScript File and name the file as App.ts and click Add.
In App.ts file we have three parts first is the
1) import part
2) Next is component part
3) Next, we have is the class for writing our business logics.
Here we can see a simple basic one-way binding example to display the welcome message inside h1 tag. Here.
One-way Data Binding -> From Data Source to view
import {Component} from
'angular2/core'
;
// 1) One Way
@Component({
selector:
'myapp1'
template:
'<h2 style="color:blue;">Welcome to Angular2 Tutorial using ASP.NET Core RC2 by SYED SHANU</h2>'
})
export class myAppComponent1 {
In the component, we have a selector and template. The selector is to give a name for this app and in our HTML file we use this selector name to display our HTML. In ttemplate we write our code.
Next we need to add the boot.ts file to run our app.
Right Click on Scripts folder and click on add new Item. Select TypeScript File and name the file as boot.ts and click Add.
In boot.ts file we add the below code. Here first we import bootsrap file to load and run our app file and also we import our app component. Note to import our app we need to give the same class name which was given in our app typescript file and give our app path in from as ’./app’ .Next we run our app by adding the app name in bootstrap as bootstrap(myAppComponent1);.
///<reference path="../node_modules/angular2/typings/browser.d.ts" />
import {bootstrap} from
'angular2/platform/browser'
import {myAppComponent1} from
'./app'
bootstrap(myAppComponent1);
Next we need to create our html page to view result.To add the HTML file right click on wwwroot folder and click add new item , give the name as index.html and click Add.
In the HTMl file, replace the below code. Here we can see first in header part we add all the script reference file and in script we load our boot file to run our app. In the body part, we display the result using the component selector name. In our app component, we have given the selector name as “myapp1”.In this HTML to display the result we add a tag like this <myapp1>My APP1 Loading ...</myapp1>
<
html
>
head
title
>ASP.NET Core: AngularJS 2 Demo</
meta
name
=
"viewport"
content
"width=device-width, initial-scale=1"
<!-- 1. Load libraries -->
<!-- IE required polyfills -->
script
src
"/js/es6-shim.min.js"
></
"/js/system-polyfills.js"
<!-- Angular2 libraries -->
"/js/angular2-polyfills.js"
"/js/system.src.js"
"/js/Rx.js"
"/js/angular2.dev.js"
"https://code.angularjs.org/2.0.0-alpha.46/http.dev.js"
<!-- Bootstrap via SystemJS -->
System.config
({
packages:
"app":
defaultExtension: 'js'
'lib': { defaultExtension: 'js' }
System.import('app/boot').then(null, console.error.bind(console));
</
body
<!-- Application PlaceHolder -->
h1
> One Way Simple Binding</
myapp1
>My APP1 Loading ...</
hr
/>
So what is next we have successfully created our first Angular2 and Asp.Net core 1.0 web application and wait we have to do one more pending work to run our application? Yes we need to run our Grunt file to create our entire script file in our wwwroot scripts folder.
Now we need to run the Grunt file using Visual Studio Task Runner.
To view the Task Runner Click the menu View-> Other Windows,-> and click on Task Runner
We can also open Task Runner by right click on our Gruntfile.js in Solution Explorer and click on Task Runner Explorer.
Click on GruntFile.js and click on refresh button at top left.
Now we can see all the GruntFile has been added.
Right-click the default under Alias Task and click Run.
Now our Grunt file has been successfully run in our project. When we add a script file we can see new app.js file will be created in our wwwroot folder.
Now we have completed our first sample application using Angular2 in Asp.Net Core.
Run the program to see our sample One Way binding.
In our previous sample, we have added one component in our App TypeScript file. Instead of creating multiple App file here we will add multiple Component in our App file, add the bootstrap for each app in our boot file and finally in our html file we add the app component selector name to view our result.
Note: Each time when you change the app or boot file run the GRUNT file using the Task Runner Explorer to view our updated data.
Here in below example, we can see we will be adding 2 components in our app file.
1) Component example for One-Way data binding
2) Component Example for Two-Way data binding.
Few more example in Angular2 which explains
1) Two-way Data Binding -> Used for Data Entry for binding and display.
Here we can see in Two way data binding we have declared the variable named “myName” in export class and bind the result in html and in input tag.
import { NgIf, NgFor} from
'angular2/common'
import { students } from
'./students'
// 2) TWO way binding
'myapp2'
'<h3> Enter Your Name : <input [(ngModel)]="myName" > <br />'
+
'<h2 style="color:green;"> Your Name is : {{myName}} </h2> '
export class myAppComponent2 {
myName: string;
constructotr() {
this
.myName =
"Shanu"
import {myAppComponent2} from
bootstrap(myAppComponent2);
<h1> One Way Simple Binding</h1>
<myapp1>My APP1 Loading ...</myapp1>
<hr />
<h1> Two Way Binding</h1>
<myapp2>My APP2 Loading ...</myapp2>
Output:
2) NG Click -> Now we will see a sample to create our button click from our component.
In our app, we have added one more Component and added the selector name as 'myapp3' and the class name as myAppComponent3.
In template, we have created a Button and in Button Click event we call the ’getFruitName’ method
In the ’getFruitName’ we check for fruit name and change the name in each click as “Apple’ or “Mango”.
// 3) Button Click
'myapp3'
'<button (click)="getFruitName($event)" >'
'<h2 style="color:Red;"> Click Button to see the Fruit name : {{fruitName}} </h2> '
export class myAppComponent3 {
fruitName: string;
.fruitName =
"Apple"
getFruitName() {
if
(
.fruitName ==
)
"Mango"
else
alert(
"Fruit Name is : "
.fruitName);
Note: In boot.ts file add the component and in html add the selector name finally run the GRUNT and run the application.
Output: When we click on the button first we display the fruit name in alert box.
When we click Ok on Alert box we can see in button the fruit name has been added.
3) NG IF -> Now we will see a sample for NgIf .We have used the same above sample and created new component to add our If condition check.
In our app, we have added one more Component and added the selector name as 'myapp4' and the class name as myAppComponent4.
In the template, we have created a Button and in Button Click event we call the ’getFruitName’ method
In the ’getFruitName’ we check for fruit name and change the name in each click as “Apple’ or “Mango”. In this method, we set the isApple Boolean variable as true if the fruitname is Apple and in our template, we have used the ngIf to display the appropriate result.
// 4) NG-IF
'myapp4'
directives: [NgIf],
'<h2 style="color:#8340AF;"> <p *ngIf="isApple">Clicked Apple :) </p> <p *ngIf="!isApple">Clicked Mango :)</p> </h2> '
export class myAppComponent4 {
isApple: Boolean;
.isApple =
) {
Note: In boot.ts file add the component and in HTML add the selector name finally run the GRUNT and run the application.
Output: When we click on the button first we display the fruit name in the alert box.
The result will be displayed ddepending on the if condition used.
4) NG FOR -> Now we will see a sample for Ng FOR .
In our app, we have added one more Component and added the selector name as 'myapp5' and the class name as myAppComponent5.
In the template, we display all the name one by one in order list using *ngFor
In the myAppComponent5 class we have created an array as arrayofName to by bound in the template using *ngFor.
// 5) NG-FOR
'myapp5'
directives: [NgFor],
template: `
<h2 style=
"color:#C70039;"
>Name List using For NG For</h2>
<h3 style=
"color:#3D693D;"
<ul>
<li *ngFor=
"#ourname of arrayofName"
>{{ourname}}</li>
</ul> </h3>
`
export class myAppComponent5{
arrayofName = [
"Afraz"
"Afreen"
];
5) NG FOR using Multi array ->
First, we will create a new Type Script file to create a class file to create all multi array variables. Right Click Scripts folder and click add new Item-> Select Type Script and name the file as “Students”
Here we add Studentid, name and email in this class as below.
export class students {
constructor(
public StdID: number,
public StdName: string,
public Email: string
) { }
Now we will see a sample for Ng FOR .
In our app we have added one more Component and added the selector name as 'myapp6' and the class name as myAppComponent6.
In the myAppComponent6 we add all values for student details in array list and we will bind the result in template div tag using *ngFor="#std of stdDetails"
/ 6) NG-FOR
with
Multi array using class
'myapp6'
"color:#D60F30;"
>Student Details</h2>
"color:#FF5733;"
<div *ngFor=
"#std of stdDetails"
{{std.StdID}}
{{std.StdName}}
{{std.Email}}
</div>
<h3>
export class myAppComponent6 {
stdDetails = [
new
students(1,
'SHANU'
'syedshanumcain@gmail.com'
),
'Afraz'
'Afraz@gmail.com'
'Afreen'
'Afreen@gmail.com'