Introduction
As a beginner, I struggled a lot to implement and get a clear picture of an Angular 2 life cycle. This article will explain the 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. Thus, let's begin.
Prerequisites
Yes, there is an important installation process; which 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 ships 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 an effect.
Visual Studio will now look first for the 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.
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 that everything is clean.
Let's begin
Note
Expecting the basic knowledge of TypeScript.
Step 1
Create a new ASP.NET Empty Web Application Project in VS2015 => Also, make sure that you uncheck the Application Insights check box.
Step 2
Add a NPM configuration file => Right click on Solution => Add New Item => npm configuration file, i..e package.json file
Step 3
Copy and paste the code given below in package.json and save it. As of now, as a beginner; you will get a clear picture after you are familiarized with npm structure and how it works. 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 the important files through npm command, as per the configuration in package.json, which will be noticed by you at message bar at the bottom. After a few minutes, it will say this message - "Installing package Complete".
Step 4
Add a TypeScript JSON configuration file => Right click on Solution => Add New Item => TypeScript JSON Configuration File, i..e tsconfig.json file and add the code given below 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
- }
- }
Step 5
Now, to go to project location in File Explorer and delete node_module folder.
Step 6
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 of this folder; they don't have files regarding tsconfig.json file and in step 6 we recreate folder node_module which restore 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.
Step 7
Add JavaScript file in under project with name systemjs.config.js and add the code given below in it.
-
- (function(global) {
- System.config({
- paths: {
It is also a configuration file. Please notice the comments in the code and two important things are given below.
- Where our code resides i.e folder name. Here, I need to mention app at line number 14.
- And which is our starting file, run Angular 2 Application. Here, I need to mention "main.js" at the line number 33.
Step 8
As we configure the last step, add the folder with the name app and add main.ts i.e. TypeScript file in it.
TypeScript is a strict superset of JavaScript i.e. the code will convert into JavaScript. Angular 2 comes with TypeScript compulsorily. This means that our main.ts file will be converted into main.js file, as we mention in systemjs.config.js file.
Step 9
Add the code given below into main.ts file.
- import {
- platformBrowserDynamic
- } from "@angular/platform-browser-dynamic"
- import {
- AppModule
- } from "./app.module"
- platformBrowserDynamic().bootstrapModule(AppModule);
Please notice the code that here we are creating our module and name 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.
Step 10
In the last step, we just defined our module, so create/declare our module in another file named as app.module.ts in an app folder and add the code given below 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 an Angular 2. Please notice the 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.
Step 11
As mentioned in step 10, we have to create/declare AppComponent. Thus, add TypeScript file named as app.component.ts and add the code given below 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, when the my-app attribute in HTML is found, then render st.html file there and st.html's expecting model, so we are passing that model from AppComponent class. Here, we tried to pass Customer Model with the object name customerobj. (For two way binding)
Step 12
Add Customer Model in new TypeScript file with the name Customer.tsin app folder and add the code given below into it.
- export class Customer {
- public CustomerName: string = "asdsad";
- public Code: string = "asdsa";
- public Amount: string = "asdasd";
- }
Add ts.html file in an app folder, as we mentioned add the code given below 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>
Step 13
Add one HTML page, make it as startup page and add the code given below 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 need to just declare the required file and starting point in Head section andd add <my-aap> tag into body section.
Save and run the Application.
This article is for the beginner, who wants to learn Angular 2 and get a clear idea about how it works.