Introduction
As a beginner, I struggled a lot to implement and get a clear picture of Angular 2 life cycle. This article will explain details about how to configure your project for Angular 2 and how to write your Angular 2 application. We will go further than Hello World! and implement 2 way binding. So let's begin.
Prerequisites
Yes, there are some important installation processes you must carry out.
Note: Content in prerequisites are copied from - https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html
- Prerequisite: Install Node.js
Install Node.js® and npm if they are not already on your machine. Verify that you are running node version 4.6.x
or greater, and npm 3.x.x
or greater by running node -v
and npm -v
in a terminal/console window.
- Prerequisite: Install Visual Studio 2015 Update 3
- Prerequisite: Configure External Web tools
Configure Visual Studio to use the global external web tools instead of the tools that ship with Visual Studio:
- Open the Options dialog with
Tools
| Options
- In the tree on the left, select
Projects and Solutions
| External Web Tools
. - On the right, move the
$(PATH)
entry above the $(DevEnvDir
) entries. This tells Visual Studio to use the external tools (such as npm
) found in the global path before using its own version of the external tools. - Click OK to close the dialog.
- Restart Visual Studio for this change to take effect.
Visual Studio will now look first for external tools in the current workspace and if not found, then look in the global path and if it is not found there, Visual Studio will use its own versions of the tools.
- Prerequisite: Install Typescript 2 for Visual Studio 2015
While Visual Studio Update 3 ships with Typescript support out of the box, it currently doesn't’t ship with Typescript 2, which you need to develop Angular applications.
To install Typescript 2:
You can find out more about Typescript 2 support in Visual studio here.
At this point, Visual Studio is ready. It’s a good idea to close Visual Studio and restart it to make sure everything is clean.
Let's Begin
Note: Expecting basic knowledge of Typescript.
- Create a new ASP.NET Empty Web Application Project in VS2015 => Also, make sure you uncheck the Application Insights check box.
- Add a NPM configuration file => Right Click Solution => Add New Item => Npm Configuration File, i.e., package.json file:
- Copy paste the following code in package.json and save it, as of now as a beginner, you will get a clear picture after you are familiar with the
npm
structure and how it works and also I will explain as much as possible in this article.
{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
"start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
"e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\"
--kill-others --success first",
"lint": "tslint ./app/**/*.ts -t verbose",
"lite": "lite-server",
"pree2e": "webdriver-manager update",
"test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
"test-once": "tsc && karma start karma.conf.js --single-run",
"tsc": "tsc",
"tsc:w": "tsc -w"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@angular/common": "~2.4.0",
"@angular/compiler": "~2.4.0",
"@angular/core": "~2.4.0",
"@angular/forms": "~2.4.0",
"@angular/http": "~2.4.0",
"@angular/platform-browser": "~2.4.0",
"@angular/platform-browser-dynamic": "~2.4.0",
"@angular/router": "~3.4.0",
"angular-in-memory-web-api": "~0.2.1",
"systemjs": "0.19.40",
"core-js": "^2.4.1",
"reflect-metadata": "^0.1.8",
"rxjs": "5.0.1",
"zone.js": "^0.7.4"
},
"devDependencies": {
"concurrently": "^3.1.0",
"lite-server": "^2.2.2",
"typescript": "~2.0.10",
"canonical-path": "0.0.2",
"http-server": "^0.9.0",
"tslint": "^3.15.1",
"lodash": "^4.16.4",
"jasmine-core": "~2.4.1",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~4.0.13",
"rimraf": "^2.5.4",
"@types/node": "^6.0.46",
"@types/jasmine": "^2.5.36",
"@types/selenium-webdriver": "2.53.33"
},
"repository": {}
}
When you save this file, Visual Studio automatically tries to fetch important files through npm
command as per configuration in package.json. You will notice at message bar at the bottom, and after a few minutes, it will say this message - "Installing package Complete".
- Add a Typescript JSON configuration file => Right Click Solution => Add New Item => Typescript JSON Configuration File, i.e., tsconfig.json file and add the following code in it and save it.
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
- Now go to project location in file explorer and delete node_module folder.
- In Visual Studio, right click on package.json file and hit "Restore Packages".
In step 5, we delete node_module folder because at the time of creation, this folder they doesn't have files regarding tsconfig.json file and in step 6, we recreate folder node_module which restores all files as per package.json configuration along with files as per tsconfig.json. Now we are ready to take our first step to implement Angular application, till now, we just configure project for Angular 2.
- Add JavaScript file under project with name systemjs.config.js, and add the following code in it:
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'@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',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
It is also a configuration file. Please notice comments in the code, two important things are:
- where our code resides, i.e., folder name, here I mention "
app
" at line number 14 - and which is our starting file, run Angular 2 application, here I mention "main.js" at line number 33
- As we configure in the last step, add folder with name "app" and add "main.ts", i.e., typescript file in it.
Typescript is a strict superset of JavaScript, i.e., code will convert into JavaScript. And Angular 2 comes with Typescript compulsory. That means our main.ts file will convert into main.js file as we mention in systemjs.config.js file.
- Add the following code into main.ts file:
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"
import { AppModule } from "./app.module"
platformBrowserDynamic().bootstrapModule(AppModule);
Please notice code, here we are creating our module, here named it as "AppModule
".
platformBrowserDynamic
- is nothing but a class export from @angular/platform-browser-dynamic file.
We bootstrap our module into Angular 2 by passing Module to bootstrapModule
function at line number 3.
- In the last step, we just define our module, so create/declare our module in another file named as "app.module.ts" in app folder and add the following code in it:
import { NgModule } from "@angular/core"
import { BrowserModule } from "@angular/platform-browser"
import { FormsModule } from '@angular/forms';
import { AppComponent } from "./app.component"
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
In this file, we are declaring our AppModule
with syntactical manner of Angular 2. Please notice line number 4, we are exposing our AppModule
using AppComponent
which is also a class, which is nothing but a declaration of UI design into it.
- As mentioned in step 10, we have to create/declare
AppComponent
. So add typescript file named as "app.component.ts" and add the following code into it:
import { Component } from '@angular/core';
import { Customer } from "./Customer"
@Component({
selector: 'my-app',
moduleId: module.id,
templateUrl: './st.html'
})
export class AppComponent {
customerobj: Customer = new Customer();
}
In this file, we are mentioning that when found, my-app
attribute in HTML, then render st.html file there and st.html expecting model so we are passing that model from AppComponent
class. Here, we tried to pass Customer
Model with object name customerobj
(for two way binding).
- Add
Customer
Model in new typescript file with name Customer.tsin app folder and add the following code into it:
export class Customer {
public CustomerName: string = "asdsad";
public Code: string = "asdsa";
public Amount: string = "asdasd";
}
And add ts.html file in app folder as we mention, add the following code into it:
<div>
Customer Name :- <input [(ngModel)]="customerobj.CustomerName" /> <br />
Customer Code :- <input [(ngModel)]="customerobj.Code" /><br />
Amount :- <input [(ngModel)]="customerobj.Amount" /><br />
<br />
<br />
<br />
{{customerobj.CustomerName}} <br />
{{customerobj.Code}} <br />
{{customerobj.Amount}}
</div>
- Add one HTML page, make it as startup page and add the following code into it:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en"></script>
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
This is our first landing page, we just declare required file and starting point in Head
section, and add
<my-aap>
tag into body
section.
Save and run application.
This article is for beginners who like to learn Angular 2 and get a clear idea about how it works.