Introduction
In this article, we will see in detail about Angular2 with ASP.NET Core 1.0 RC2.
You can also view our previous article here,
In this article, we will see in detail 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 the dependencies to install Angular2 and all the other files.
- How to create our Angular2 App, and boot using Type Script file.
- Create HTML File.
- How to run the Grunt file using Visual Studio Task Runner Explorer.
- How to Run and view our Sample.
- How to create multiple components in same App file.
- A few sample examples in Angular2.
- 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.
Prerequisites
Visual Studio 2015: You can download it from here.
ASP.NET Core 1.0 RC2: download link,
Code Part
Step 1: Create our ASP.NET Core 1.0 Web Application.
After installing both Visual Studio 2015 and ASP.NET Core 1.0 RC2, click start, followed by clicking Programs and selecting Visual Studio 2015 and clicking Visual Studio 2015. Click New followed by the Project, selecting Web and subsequently selecting ASP.NET Core Web Application. Enter your project name and click OK.
Afterwards, select Web Application. If you are not hosting in the Cloud, then you can uncheck the Host in the Cloud at the bottom right corner. Click OK.
Now we have the following display on the screen:
Step 2: How to add TypeScript JSON Configuration File
Subsequently TypeScript JSON file will be the file that specifies the root files and the compiler options, required to compile the project .To know more about TypeScript JSON configuration, kindly visit these sites.
To create the TypeScript JSON file, right click the project and click Add new Item.
Select TypeScript JSCON Configuration File and Click OK. The file will look as shown below:.
Now copy the code given below 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 NPM Configuration file to add a Grunt package to run our JavaScripts. As we have created 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 it in the Solution Explorer, click “Show All Files”.
Now, open the “package.JSON” file . First, we need to change the name to our project solution name and add our Grunt package. We can see the code here, given below in 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, the npm folder will be the first restored, and then installed.
Restoring
Al 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, select Grunt Configuration file and click Add.
After creating the file, now we need to edit this file to add the loaded plugins, configure the plugins, and define the tasks.
Here in our Grunt file, we have to first load the 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 the Scripts folder results will be added in this app.js file. Next, we need to copy all the Script files from 'node_modules/ to our local js folder.
The watch plugin will be used to check for any changes on JavaScript file and update app.js with all the new changes.
This file is the main entry point for defining Grunt tasks using Grunt plugins.
Click
here to learn more.
- 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: {
- 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: {
- scripts: {
- files: ['Scripts/**/*.js'],
- tasks: ['ts', 'uglify', 'copy']
- }
- }
- });
-
- 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 dependencies, given below:
- "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 as shown below:
Save the file and wait for few seconds to complete all the dependencies to install.
Step 6: How to create our Angular2 App, and boot using Type Script file.
Now, it’s time to create our Angular2 application. First, create a folder named Scripts. Right click the project, click add new folder and name the folder “Scripts”. Now, we will create our TypeScript files inside this Scripts folder.
To work with Angular2, we need to create two important TypeScript files, which are:
- Component file is the one where we write our Angular coding.
- Boot file: To run our component app .
Creating App TypeScript file
Right click on Scripts folder and click add new item. Select TypeScript file, name the file App.ts and click Add.
In App.ts file, we have three parts, which are-
- Import part
- Component part
- We have the class to write our business logics.
Here, we can see a simple basic one-way binding example to display the welcome message in side h1 tag., shown below:
One-way Data Binding -> From Data Source to view
- import {Component} from 'angular2/core';
-
-
- @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 a template. The selector is used to give the name for this app and in our HTML file, we use this selector name to display our HTML. In the 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 add new Item. Select TypeScript file, name the file as boot.ts and click Add.
In boot.ts file, we add the code given below. First, we import bootstrap file to load and run our app file, and we need to 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);.
-
-
- 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 the result.To add HTML file, right click on wwwroot folder, click add new item, give the name as index.html and click Add.
In HTML file, replace the code given below. Here, we can see first in the header part, we add all the script reference files and in the 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, display the result and we will add a 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">
-
-
- <script src="/js/es6-shim.min.js"></script>
- <script src="/js/system-polyfills.js"></script>
-
- <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>
- <script src="https://code.angularjs.org/2.0.0-alpha.46/http.dev.js"></script>
-
- <script>
-
- System.config
- ({
- packages:
- {
- "app":
- {
- defaultExtension: 'js'
- },
- 'lib': { defaultExtension: 'js' }
- }
- });
- System.import('app/boot').then(null, console.error.bind(console));
- </script>
- </head>
-
- <body>
-
- <h1> One Way Simple Binding</h1>
- <myapp1>My APP1 Loading ...</myapp1>
- <hr />
- </body>
-
- </html>
Hence, we have successfully created our first Angular2 and ASP.NET core 1.0 Web Application -- but 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-> Task runner Explorer.
We can also open Task runner by clicking right on our Gruntfile.js in Solution Explorer and clicking on Task runner Explorer.
Now, we can see our Task runner Explorer.
Click GruntFile.js and click refresh button on the top left.
Now, we can see 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 a 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 files here, we will add multiple components 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 the file, run the Grunt file using the Task runner Explorer to view our updated data.
Here, in the example given below, we can see we will be adding two components in our app file.
- Component example for One-Way data binding.
- Component example for Two-Way data binding.
There are a few more examples in Angular2 which explain:
- Two-way Data Binding -> Used for data entry to binding and display.
Here, we can see in Two way data binding, we have declared the variable named “myName” in an export class, which binds the result in HTML, and the code is given below:
- import {Component} from 'angular2/core';
- import { NgIf, NgFor} from 'angular2/common';
- import { students } from './students';
-
-
- @Component({
- selector: 'myapp1',
- template: '<h2 style="color:blue;">Welcome to Angular2 Tutorial using ASP.NET Core RC2 by SYED SHANU</h2>'
- })
- export class myAppComponent1 {
- }
-
-
- @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 will add one more component to be run from our app.
-
-
- import {bootstrap} from 'angular2/platform/browser'
- import {myAppComponent1} from './app'
- import {myAppComponent2} from './app'
-
- bootstrap(myAppComponent1);
- bootstrap(myAppComponent2);
In HTMl add the new Componet Selector to display our Two way binding result.
-
- <h1> One Way Simple Binding</h1>
- <myapp1>My APP1 Loading ...</myapp1>
- <hr />
-
- <h1> Two Way Binding</h1>
- <myapp2>My APP2 Loading ...</myapp2>
- <hr />
Output
- 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, added the selector name as 'myapp3' and the class name as myAppComponent3.
In the template, we have created a button and in the 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”.
-
- @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 Grunt and the Application.
Output: When we click on the button first, we get the display of the fruit name in an alert box.
When we click OK on an Alert box, we can see in the button that the fruit name has been added.
- NG IF -> Now, we will see a sample for NG IF. We have used the same sample given above and created a new component to add to 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 the button click event, we call the ’getFruitName’ method.
In the ’getFruitName’, we check for the 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 NG IF to display the appropriate result.
-
- @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 the Application.
Output: When we click the button, first we display the fruit name in an Alert box.
The result will be displayed, depending on the "if" condition used.
- NG FOR -> Now we will see a sample for Ng FOR .
In our app, we have added one more component, added the selector name as 'myapp5' and the class name as myAppComponent5.
In the template, we display all the names one by one in the order list, using *NG FOR
In the myAppComponent5 class, we have created an array as arrayofName to be bound in the template using *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 Grunt and the Application.
Output
- 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 shown below:
- export class students
- {
- constructor
- (
- public StdID: number,
- public StdName: string,
- public Email: string
- ) { }
- }
In our app component, import the student 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; add the selector name as 'myapp6' and the class name as myAppComponent6.
In the myAppComponent6, we add all values for the student details in an array list and we will bind the result in the template div tag, using *ngFor="#std of stdDetails".
-
- @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', '[email protected]'),
- new students(1, 'Afraz', '[email protected]'),
- new students(1, 'Afreen', '[email protected]')
- ];
- }
Note
In boot.ts file, add the component and in HTML, add the selector name. Finally, run Grunt and the Application.
Output
Complete Code
- app.ts Code
- import {Component} from 'angular2/core';
- import { NgIf, NgFor} from 'angular2/common';
- import { students } from './students';
-
-
- @Component({
- selector: 'myapp1',
- template: '<h2 style="color:blue;">Welcome to Angular2 Tutorial using ASP.NET Core RC2 by SYED SHANU</h2>'
- })
- export class myAppComponent1 {
- }
-
-
- @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";
- }
- }
-
-
- @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);
- }
-
- }
-
-
- @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);
- }
- }
-
-
- @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"];
- }
-
-
-
- @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', '[email protected]'),
- new students(1, 'Afraz', '[email protected]'),
- new students(1, 'Afreen', '[email protected]')
- ];
- }
- boot.ts Code
-
-
- import {bootstrap} from 'angular2/platform/browser'
- import {myAppComponent1} from './app'
- import {myAppComponent2} from './app'
- import {myAppComponent3} from './app'
- import {myAppComponent4} from './app'
- import {myAppComponent5} from './app'
- import {myAppComponent6} from './app'
-
- bootstrap(myAppComponent1);
- bootstrap(myAppComponent2);
- bootstrap(myAppComponent3);
- bootstrap(myAppComponent4);
- bootstrap(myAppComponent5);
- bootstrap(myAppComponent6);
- HTML Code
- <html>
-
- <head>
- <title>ASP.NET Core: AngularJS 2 Demo</title>
- <meta name="viewport" content="width=device-width, initial-scale=1">
-
-
- <script src="/js/es6-shim.min.js"></script>
- <script src="/js/system-polyfills.js"></script>
-
- <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>
- <script src="https://code.angularjs.org/2.0.0-alpha.46/http.dev.js"></script>
-
- <script>
-
- System.config
- ({
- packages:
- {
- "app":
- {
- defaultExtension: 'js'
- },
- 'lib': { defaultExtension: 'js' }
- }
- });
- System.import('app/boot').then(null, console.error.bind(console));
- </script>
- </head>
-
- <body>
-
- <h1> One Way Simple Binding</h1>
- <myapp1>My APP1 Loading ...</myapp1>
- <hr />
-
- <h1> Two Way Binding</h1>
- <myapp2>My APP2 Loading ...</myapp2>
- <hr />
-
- <h1> NG Button CLick</h1>
- <myapp3>My APP3 Loading ...</myapp3>
- <hr />
-
- <h1> NG IF& NG CLick</h1>
- <myapp4>My APP4 Loading ...</myapp4>
- <hr />
-
- <h1> NG For</h1>
- <myapp5>My APP5 Loading ...</myapp5>
- <hr />
-
- <h1> NG For with Multi Array</h1>
- <myapp6>My APP5 Loading ...</myapp6>
- <hr />
- </body>
-
- </html>
Hope this article helps you. Soon, we will see in detail how to use Web API and Angular2 in ASP.NET Core 1.0.
Reference website