You can download the Source Code from this link Download Source Code

Introduction

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 

  •  Create our ASP.NET Core 1.0 Web Application.
  •  How to add TypeScript JSON Configuration File
  • How to add grunt package using NPM configuration file
  •  How to configure Grunt File.
  • Adding Dependencies to install Angular2 and all other files
  • How to create our Angular2 App, boot using Type Script file.
  • Creating HTML File
  • How to Run the Grunt file using Visual Studio Task Runner Explorer
  • Now It’s time to Run and view our Sample.
  • How to create multiple components in same App file.
  •  Few sample example in Angular2 which explains
  •         One Way Binding
  •         Two Way Binding
  •         NG- Click
  •         NG IF
  •         NG For
  •         NG For with Multi array.
  •   How to show the Angular2 Component result in our HTML page.

Reference website : Angular2 

Prerequisites

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

Step 1: Create our ASP.NET Core 1.0 Web Application.

After installed 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.

Step 2: How to add TypeScript JSON Configuration File

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 you Project and Click Add new Item.

Select TypeScript JSCON Configuration File and Click ok. The File will be look like below image.

Now copy the below code and replace with your config file.

"compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "target": "es5",
 "sourceMap": true


Step 3: How to add grunt package using NPM configuration file

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": true,
"devDependencies": {
    "grunt": "1.0.1",
    "grunt-contrib-copy": "1.0.0",
    "grunt-contrib-uglify": "1.0.1",
    "grunt-contrib-watch": "1.0.0",
    "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:

Step 4: Configure Grunt File.

Grunt is used to build all our client side resources like JavaScript for our project.

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 s 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.
*/
module.exports = function (grunt) {
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('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: true,
                    cwd: 'wwwroot/app',
                    src: ['**/*.js'],
                    dest: 'wwwroot/app'
                }]
            },
            options:
            {
                sourceMap: true
            }
        },
        // Copy all JS files from external libraries and required NPM packages to wwwroot/js  
        copy: {
            main: {
                files:
                     [{
                         expand: true,
                         flatten: true,
                         src: ['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'],
                         dest: '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', ['ts', 'uglify', 'copy', 'watch']);
};

Step 5: Adding Dependencies to install Angular2 and all other files

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 be look like below image.

Save the file and wait for few second to complete all decencies installed.

Step 6 How to create our Angular2 App, boot using Type Script file.

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 . 

Creating App TypeScript file:

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 has 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 in side 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 component we have selector and template. Selector is to give name for this app and in our html file we use this selector name to display our html. In template we write our code.

Next we need to add the boot.ts file to run our app.

Creating boot TypeScript file:

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);

Step 7: Creating HTML File

  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 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 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 tag like this <myapp1>My APP1 Loading ...</myapp1>

<html>
  
<head>
    <title>ASP.NET Core: AngularJS 2 Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 1. Load libraries -->
    <!-- IE required polyfills -->
    <script src="/js/es6-shim.min.js"></script>
    <script src="/js/system-polyfills.js"></script>
    <!-- Angular2 libraries -->
    <script src="/js/angular2-polyfills.js"></script>
    <script src="/js/system.src.js"></script>
    <script src="/js/Rx.js"></script>
    <script src="/js/angular2.dev.js"></script>
    <!-- Bootstrap via SystemJS -->
    <script>
  
        System.config
        ({
            packages:
            {
                "app":
                {
                    defaultExtension: 'js'
                },
                'lib': { defaultExtension: 'js' }
            }
        });
        System.import('app/boot').then(null, console.error.bind(console));
    </script>
</head>
  
<body>
    <!-- Application PlaceHolder -->
    <h1> One Way Simple Binding</h1>
    <myapp1>My APP1 Loading ...</myapp1>
    <hr />
</body>
  
</html>

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. 

Step 8: Run the Grunt file using Visual Studio Task Runner Explorer

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.

Now we can see our 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.

Step 9: How to create multiple components in same App file.

In our previous sample we have added one component in our App Type Script 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 {Component} from 'angular2/core';
import { NgIf, NgFor} from 'angular2/common';
import { students } from './students';
  
// 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 {
}
  
// 2) TWO way binding
@Component({
    selector: 'myapp2',
    template: '<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";
    }
}

In boot.ts we add one more component to be run from our app.

///<reference path="../node_modules/angular2/typings/browser.d.ts" />  
  
import {bootstrap} from 'angular2/platform/browser'
import {myAppComponent1} from './app'
import {myAppComponent2} from './app'
  
bootstrap(myAppComponent1);
bootstrap(myAppComponent2);

In HTMl add the new Component Selector to display our Two way binding result.

<!-- Application PlaceHolder -->
    <h1> One Way Simple Binding</h1>
    <myapp1>My APP1 Loading ...</myapp1>
    <hr />
  
    <h1> Two Way Binding</h1>
    <myapp2>My APP2 Loading ...</myapp2>
    <hr />

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
@Component({
    selector: 'myapp3',
    template: '<button (click)="getFruitName($event)" >' + '<h2 style="color:Red;"> Click Button to see the Fruit name : {{fruitName}} </h2> '
})
export class myAppComponent3 {
    fruitName: string;
  
    constructotr() {
        this.fruitName = "Apple";
    }
    getFruitName() {
  
        if (this.fruitName == "Apple")
            this.fruitName = "Mango";
        else
            this.fruitName = "Apple";
  
        alert("Fruit Name is : " + this.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 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
@Component({
    selector: 'myapp4',
    directives: [NgIf],
    template: '<button (click)="getFruitName($event)" >' + '<h2 style="color:#8340AF;"> <p *ngIf="isApple">Clicked Apple :) </p>  <p *ngIf="!isApple">Clicked Mango :)</p> </h2> '
})
  
export class myAppComponent4 {
    fruitName: string;
    isApple: Boolean;
  
    constructotr() {
        this.fruitName = "Apple";
        this.isApple = false;
    }
    getFruitName() {
  
        if (this.fruitName == "Apple") {
            this.fruitName = "Mango";
            this.isApple = false;
        }
        else {
            this.fruitName = "Apple";
            this.isApple = true;
        }
  
        alert("Fruit Name is : " + this.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.

The result will be displayed depend 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 template we display all the name one by one in order list using *ngFor

In the myAppComponent5 class we have created array as arrayofName to by bound in template using *ngFor.

// 5) NG-FOR
    @Component({
        selector: '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 = ["Shanu", "Afraz", "Afreen"];    
}

Note: In boot.ts file add the component and in html add the selector name finally run the GRUNT and run the application.

 Output: 

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
    ) { }
}

In our app component import the students class

import {Component} from 'angular2/core';
import { NgIf, NgFor} from 'angular2/common';
import { students } from './students';

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
    @Component({
        selector: 'myapp6',
        directives: [NgFor],
        template: `
       <h2 style="color:#D60F30;">Student Details</h2>
 <h3 style="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'),
            new students(1, 'Afraz', 'Afraz@gmail.com'),
            new students(1, 'Afreen', 'Afreen@gmail.com')
        ];
    }

Note: In boot.ts file add the component and in html add the selector name finally run the GRUNT and run the application.

 Output: 

See also


ASP.NET Core 1.0 MVC 6 using WEB API and AngularJs

Download


You can download the Source Code from this link Download Source Code