Search in Help for developer site.

Tuesday 21 February 2017

Angular 2 - Setting up environment

I am assuming that you already have NPM(Nodejs Package Manager) Installed on your computer (because you will need it - you can find more information on the official website) It is important to double check that you have a recent version of Nodejs (executing node --version) I am using Windows to make this work.

Angular2 requires a bit of setup to get started. to avoid the headaches associated with setup,the Angular team came up with the Angular CLI. The Angular2 CLI makes it easy to create an application that just work out of the box.

Install the Angular 2 CLI globally:
    npm install -g angular-cli

Note: The Angular team has decided to drop the 2 from the name. So, it is now called Angular instead of Angular 2. For the sake of this tutorial, I’ll use Angular 2 to prevent confusion from developers just trying out the framework for the first time.
Use these commands to simply create your app and run it:
    ng new myapp // creates a new app
    ng generate // generates components, routes, services and pipes
    ng serve // serves your application in the browser

In this tutorial, we’ll avoid using the CLI and learn how to set up our development environment from scratch.

Setup your base project.

        Quiickly go ahead and create a new directory, newapp.Move into the directory and create an index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Angular 2 application</title>
</head>
<body>
  <h2>Setting up my development environment</h2>
</body>
     </html>
     Create another file, package.json by running the npm init -y command from the terminal
          Let’s install a package, lite-server, that will allow us to serve our application like so:
npm install --save-dev lite-server
Note: lite-servecomes bundled with browser-sync which automatically reloads the browser when our files change
Open up package.json to configure lite-server like so:
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "lite": "lite-server"
}
Now run npm run lite from your terminal, your browser should open up displaying your application and in your terminal, you should see something like this:

Change something within your index.html file and you’ll discover that your browser refreshes automatically and reflects that change!

Configuring the TypeScript Language

Typescript is not requried to write Angular2. but i have chosen this option because of the type system it offers and if you are coming from C# it is really easy to get used to it you can write pretty much your Angular 2 application using normail ECMAScript5(Standerd javascript where most of the apps are written). 

So let’s go ahead and install TypeScript like so:
npm install -g typescript
Create a file, tsconfig.json in your directory. tsconfig.json indicates that the directory is the root of a TypeScript project. we can compare it as a project soluation (.sln) in MVC project.
tsc --init --target es5 --sourceMap --experimentalDecorators --emitDecoratorMetadata

here.Open up your tsconfig.json and add the following:
{ "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false,
"outDir": "build", },
"exclude": ["node_modules"] }
target es5Allows Specify that we want to get our TypeScript code compiled to ECMAScript 5 and we can run our code in older browsers.
sourceMap: Allows us to generate the source maps, i.e files that contain mappings between the generated ES5 code and the original TypeScript code.
experimentalDecorators & emitDecoratorMetada: We need those flags to compile, transpile to ECMAScript 5 as we are using TypeScript with decorators (to annotate and modify classes and properties at design time, it basically says things like — ‘this is a custom property’ or ‘this class is a component (@Component, decorator)).

Setting up package.json

package.json file also be requried. in package.json we will have all the dependence and task which we will use in development. run below command it will initiate a intractive workflow.
npm init
it will ask you somthing like this. and you need to enter below information. 
Name:[ENTER YOUR APP NAME]
Version:1.0.0
Description:[ENTER ANY NICE DESCRIPTION]
main:index.js
Author:[YOUR NAME]

Setting up Concurrently

Concurrently is a nodejs package that allows us to run multiple commands concurrently. Let’s pull in the package.
npm install concurrently --save-dev
With Lite-server and Concurrently are only required for development so we have added 
--save-dev as a parameter.
Open and add the following code in your package.json which should be available at your root folder. these tags are tasks which will be used for (watch) reloading script on code change and (serve) for hosting our application locally.
"scripts": { "start": "concurrently \"npm run watch\" \"npm run serve\"", "watch": "tsc -w", "serve": "lite-server" }

Install Angular 2 

With great power, comes great responsibilities. Angular 2 depends on some libraries & tools to wield such power.
1) Zone.js simply makes our debugging much productive and supports change detection in our code
2) Core-js standard library for JavaScript that includes polyfills for ES5, ES6, ES7 features in browsers
3) rxjs hands us observables and asynchronous data streams
npm install --save @angular/common@2.4.0 @angular/compiler@2.4.0 @angular/core@2.4.0 @angular/platform-browser@2.4.0 @angular/platform-browser-dynamic@2.4.0 @angular/router@3.4.0 systemjs@0.19.40 core-js@2.4.1 reflect-metadata@0.1.8 rxjs@5.0.1 zone.js@0.7.4

Your package.json should looks like this..
{ "name": "setup", "version": "1.0.0", "description": "Angular2 project setup", "main": "index.js", "scripts": { "start": "concurrently \"npm run watch\" \"npm run serve\"", "watch": "tsc -w", "serve": "lite-server" }, "author": "Omi Amarwal", "license": "ISC", "dependencies": { "@angular/common": "^2.4.0", "@angular/compiler": "^2.4.0", "@angular/core": "^2.4.0", "@angular/platform-browser": "^2.4.0", "@angular/platform-browser-dynamic": "^2.4.0", "@angular/router": "^3.4.0", "core-js": "^2.4.1", "reflect-metadata": "^0.1.8", "rxjs": "^5.0.1", "systemjs": "^0.19.40", "zone.js": "^0.7.4" }, "devDependencies": { "concurrently": "^3.3.0", "lite-server": "^2.2.2" } } 

Setting systemjs.config.js

 We need a loader to help load all the angular packages that we use in the app. Angular needs a tool to point it to where each and every package is whenever it invokes the package functionalities. SystemJS is a universal dynamic loader. It loads ES6 modules, CommonJS, AMD and global scripts in the browser and NodeJS.
Create a new file, systemjs.config.js, the SystemJS configuration file in the root directory.
https://github.com/OmprakashAmarwal/StartAngular2/blob/master/systemjs.config.js


It looks for the application files to run in the app directory, you can change it to whatever directory you want. You can also see that it has specified what directory to look for angular packages, node_modules/@angular.
Take another good look at this section too:
This config lets SystemJS know how and what to load in the app.
Now head over to your index.html and reference the polyfills we installed earlier. Then load SystemJS like so:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Angular 2 app</title>

  <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>
  <!-- Load our angular app with Systemjs -->
  <script src="node_modules/systemjs/dist/system.src.js"></script>
  <script src="systemjs.config.js"></script>
  <script>
    System.import('MyApp').catch(function(err) { console.error(err); });
  </script>
</head>
<body>
  <h2>Setting up my development environment</h2>
</body>
</html>
Run npm start
That’s all really, no more steps needed! You are ready to create your first Angular 2 app using TypeScript. 
Create app folder at root and create a new file inside it with name app.component.ts and add our first component. In this tutorial, all our .ts files will be maintained in this app folder.

app.component.ts

import { Component } from '@angular/core';
@Component({ selector: 'my-app', template: <h1>Setting up my development environment</h1>' }) export class AppComponent { }

To bundle our app modules, add a new file with name app.module.ts.
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
Add directive in Index.html
<body> <my-app>Loading...</my-app>
</body>
Ok, now let's bootstrap our code by adding a new file main.ts
main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule);

This is how our folder structure should look like:

In command prompt / terminal window, execute the below command.
npm start
npm will read your package.json file and execute start command which we added in scripts section. Once npm start has been executed successfully, you should be able to see application page at http://localhost:3000.

Since npm start is also configured for auto load any changes made to code file, this will automatically reload your page on code change save. For testing the same, make changes to app.component.ts  and save. You should be able to see that the application page is now automatically updated to newer text.

You can download the code from here. 

Thursday 16 February 2017

TypeScript core concepts

TypeScript and Angular 2


One of the very common surprises that people have when learning about Angular 2 is its close ties with TypeScript. This relationship seemingly came out of nowhere, and many people have been asking questions about this. Additionally, developers may feel a little trepidation when faced with learning yet again something new. So let’s get a quick look at not only the rationale, but the absolute basics and how much of an additional learning curve TypeScript might add when learning Angular 2.

History

It’s easier to understand the present by understanding the past. When the Angular team started on Angular 2, they realized that with such a large undertaking, that having types would eliminate a large segment of possible bugs as they wrote the code for the framework. So internally they were interested in adding types to JavaScript. Furthermore, the dependency injection system of Angular 2 works better with types. So there was a good reason to use types not only within the source code of Angular 2, but also for developers using Angular 2. Additionally, one of the design goals for Angular 2 has always been for it to be forward looking. Using the latest version of JavaScript, ECMAScript 6, was a big part of that goal. So for now, some kind of transpiler is necessary.

When analyzing the existing tools, nothing quite matched the requirements they had. That gave birth to an internal language called AtScript. The team used this language for quite a while, but eventually ended up in a meeting with the TypeScript team where they looked at the few things they needed that were missing from TypeScript. This resulted in an agreement to have those items added to TypeScript. AtScript was dropped and the project was converted to TypeScript.

What’s the Difference?

Now TypeScript is by no means required to work with Angular 2. It just simplifies the code. Let’s take a quick look at what the same code looks like using TypeScript vs just regular old JavaScript.

Here’s a simple component written in JavaScript:

And here’s the same thing in TypeScript:
Right off the bat, you can see that the TypeScript code is more succinct. Only 13 lines instead of 20. Additionally, once you understand the various ES6 and TypeScript constructs used, TypeScript is just more expressive. It takes less ceremony to express the same thing.

What About ES6?

There’s actually another piece involved in this whole thing that we haven’t really discussed. And that is ES6 (and ES7 and maybe even ES8). Much of the syntax that we’re seeing in the above TypeScript example is actually current and future versions of ECMAScript (JavaScript). So learning these features is important for working with Angular 2. Although there’s a clear difference between ECMAScript and TypeScript, we’re going to make it simple and just bundle it all up together, and look at the absolute minimum you need to know to work with Angular 2.

1. Import & Export

The import and export keywords you see in the above example is part of ECMAScript modules, introduced in ECMAScript 6. There’s a lot you CAN learn about them, but the absolutely necessary knowledge is pretty straightforward when dealing with Angular 2.

The import statements we see at the top lets us bring in pieces of the Angular 2 framework for us to use, and also lets us bring in other pieces of our own code for us to use. The syntax is very simple. The import keyword, followed by curly braces that contain whatever pieces we want to use, then the from keyword, and finally a string that indicates what file we’re pulling them from. In the above example code, line 1 imports the Component from the core of Angular. Line 2 refers to a file that was written by the developer named hero.ts (the extension is implied) and that file exists in the same directory. The way we know this is that it starts with a period. That means it’s a local file, not some library we’re accessing.

Finally, we will need to export what we’re creating in this file. In the case above, it’s the HeroFormComponent, which is represented by a class. So that class is exported. That lets another file use this component with its own import statement which might look something like this:
That’s it. If you can put together your imports and exports following the above pattern, you’re set.

2. Decorators

Probably the strangest looking syntax from our TypeScript example is the @Component on line 3. This is simply metadata that describes the HeroFormComponent class that is created on line 7. This is an ECMAScript feature called a decorator. Decorators are put before the code construct that they are decorating. In this case, it’s right before the class. So when the compiler sees this decorator, it will look for the very next thing, our HeroFormComponent class, and apply this decorator to that class.

Under the hood there’s a lot of interesting stuff going on, but for our purposes we only need to understand that each of the properties we specify in that decorator, the selector and the template URL will end up getting attached to the HeroFormComponent for the Angular 2 framework to use as it runs your application. Simple right?

3. Classes

Classes are the next feature we need to understand. Thankfully most languages support classes, so this will feel familiar to anyone who programs in just about any other language. If they look strange to you, no worries. They will soon feel very familiar. There’s only a couple things about classes you need to learn. First is how to specify properties of a class. We see this on lines 8, 10, and 11 of the above code. A property is created by specifying an identifier, and equals sign, and then a value. If you don’t have an initial value, you can just specify the identifier and skip the equals sign and the initial value.

The other feature that is important is the constructor, which is just a method named “constructor”.We don’t see an example of that in the above code, but here’s a quick example.



Here we have a constructor that takes in a name, and sets that name to an internal property which is also called “name”.

Here’s a tip: this pattern of taking in values in the constructor and setting them to internal properties is so common, there’s a shorthand syntax for that shown here:


This does the same thing as the above code but removes 2 lines of code just by adding the public keyword in front of the property name of the constructor. This creates a property “name” on the class that is visible to other objects. We can also use the “private” keyword instead if we don’t want external code to be able to see the property.

Taking advantage of this is easy. If this was the constructor for a class named Hero, then we can create a new hero like this:


This would create a hero with a name property set to “Mr. Imposter”.

Again, once we learn the pattern, then the code becomes very readable and easy to deal with.

4. Types

The final feature we need to understand is Types. Types are the only one of the four features we’re discussing that are specific to TypeScript. The rest are technically ECMAScript constructs.

Types are really rather simple. Just look for the colon. That separates an object from its type. There are three basic types: number, string, and boolean. Creating a variable of a specific type just involves creating the identifier, then a colon, then the type as shown here:


This creates a variable “name” that is of type string. Naturally if we try to assign 3 to it, then our TypeScript compiler will complain. It’s far more common to use this when creating properties of classes, in which case we simply omit the “var” from the above code, which would create a name property of type string.

We can use types in functions (even constructors) as we see here:


Here we have changed our constructor to note that the name must be a string. So if someone tries to send in a number or a boolean as the name when constructing a Hero, TypeScript will prevent it at compile time.

There’s a fourth type that is very important to know: the any type.


This type indicates that the variable can be assigned any value, which is the situation we’re used to in JavaScript. So the something variable can be assigned the value of 3, or true, or the string “Mr. Impostor”. It can even be assigned all three values at given points of time during the execution of your application.

The final commonly encountered type is the array type. Often we need an array, but we want to constrain the values of the array to be of a specific type. For example in line 8 of our sample code, we create an array of powers which are all of type string. We can create an empty array that can only contain strings with the following code:


This will mean that we can only add strings to the powers array. If we try to add a number or boolean, TypeScript will stop us.



There’s obviously more to TypeScript’s types than what little I’ve shown here, but really, this is the 20% that’ll get you 80% of the result. For further reading I recommend you check out the TypeScript documentation at http://www.typescriptlang.org/docs/tutorial.html.
Thanks for reading.
Please write your comments in comment section.