-->

Learn Angular 2 step by step



Introduction

Before we have learned about AngularJS, Now it's time to learn Angular2.

Why we will learn Angular 2?

This question just comes in your mind, Right?
Angular 2 is easier to learn than Angular 1.x. Here again, a question can come in your mind if you don't know angular 1.x and the question is, can we learn Angular 2 without having hands on experience in angular 1.x?


Yes, we can very well skip Angular 1.x and start with Angular 2. But you might be thinking that is it really easier to learn? Yes, my friend Angular 2 is easier to learn than Angular 1.x. When I started before few month, I also though that it's very complex because of lots of configuration (.json) files. Believe me, it's really easy to learn and that is the purpose of this article to make the angular 2 learning easy for you with step by step process.

There are many more features in Angular 2 over Angular 1.x like Performance improvements, Mobile Support and more will we learn later part of this article.

Pre-requisite for Angular 2

Before start developing Angular 2 application, I will download & install this following...


1. Node.js 
Technically, Node.js and NPM are not needed to do Angular2 work. Here we will use Node.js as a package manager. It gives us the tool npm that allows us to download libraries and packages we will use in Angular 2. That's it what we need to know about it, for now. Later we will learn more about Node.js in the next steps.

Download Node.js from here: https://nodejs.org/en/download/

2. TypeScript 
TypeScript is an extension (a “superset”) of the JavaScript language. It allows us to write code in Object Oriented Design approach which makes possible writing JavaScript code faster. In the end, TypeScript code is compiled to Javascript code.

Angular 2 is written in TypeScript, a strict superset of Javascript and ES6. We can install typescript by using npm (node package manager tool) command >  npm install –g typescript 

You don't know TypeScript? Read this article Learn TypeScript Step by step,

3. VS (Visual studio) Code editor
We can write Angular 2 application using a simple notepad But here in this article, I have used VS (Visual studio) code editor. I personally love VS Code Editor. You can download VS Code editor from here https://code.visualstudio.com/download

Setup Angular 2 development environment.

First, we will download and install Node.js from https://nodejs.org/en/download/ if you have already not installed.

Now we will install TypeScript using npm tool
Open your Node.js command prompt then write command > npm install –g typescript  and then click enter.



After that, we will download and install VS Code editor from https://code.visualstudio.com/download

Download/clone Angular 2 quick start configuration files from here https://github.com/dotnetawesome/AngularJS2Seed before start angular 2 coding. Here I have created an angular template for quick start with the minimal configuration files those are required at that moment, you can also download from here https://github.com/angular/quickstart which is provided by angular.io official site but there are lots of files those are not required at this moment as we are going to begin and I would like to make it as simple as possible for better understanding.



These all the files you can see here what we have downloaded from the https://github.com/dotnetawesome/AngularJS2Seed is only for setup development environment So we can quick start angular 2 development. And most important things, this is just for 1-time setup and we don't need to know much about this configuration files right now as most of the time it will be identical and this files will not go to production.

package.json: files contain all the dependencies/node packages meta-data that our application will depend on and defines some useful scripts.
People always confused with this 2 types of packages.
"dependencies": these packages are required by your application in production
"devDependencies": these packages are only needed for development and testing

typings.json: In the typescript compiling process d.ts (typescript definition file) file used for getting typescript type information. When the compiler doesn't recognize something, it throws an error.
we need do nothing to get typings files for library packages that include d.ts files. Angular packages include them already. But many libraries—jQuery, Jasmine, and Lodash among them—do not include d.ts files in their npm packages.
So, we have to write typings.json file to get the correct type definition files to run the project smoothly.

tsconfig.json: This is TypeScript configuration file. It contains TypeScript compiler options used in typescript compiling process into javascript.

systemjs.config.js: This is contain systemjs configuration options. Now the question is what is SystemJS?
It's a universal dynamic module loader. It's loads js files on demand basic. I want to give you 1 example here...
We know that angular 2 application is a component based module and we will write each angular 2 component in separate files for making it well-structured & manageable.
So now suppose we have 100 javascript files for 100 components in our angular 2 application, definitely, we will not load all the files at one go in the browser right? It will be a performance issue.

What systemjs do is it's dynamically load required components/javascript files on demand basic.

Again I am saying don't fell that it's too complex because of these configuration files. These are only used in the development environment and we can use these files on our every angular 2 application with some minimum changes if required.

"Hello World" in Angular 2

Now let's start creating "Hello World" application in Angular 2.

Before start writing code we will install all the dependencies defined in the package.json file.
Open "Node.js command prompt" > write command for change directory to your application folder > and then write command > npm install for install all the dependencies defined in the package.json file.



When we will run this command, what it does actually its looks for package.json file and will download all the dependencies added here in the package.json file into the "node_modules" folder in our application root path. It will take a little time. You must have to connect with the internet otherwise it will fail.

Create our first angular 2 component

Angular 2 applications are made up of components. A component is the combination of an HTML template and a component class that controls a portion of the screen.

Here first I will create a folder "App" inside this src folder first.
Right-click on the src folder > Create folder > name it "App".

Now I will create 1 ts file "app.component.ts"  file inside this app folder which is our first angular 2 component.
Right-click on the App folder > add file > name it "app.component.ts" 

.ts is TypeScript file extension. As I have told you before that TypeScript is an extension (a “superset”) of the JavaScript language. It allows us to write code in Object Oriented Design approach.

Here I have created a class AppComponent with a @Component decorator for making it angular 2 component. you can see here I have added a selector "app", that's mean we can load the template with the title "Hello World" using this HTML tag now.

The export specifies that the component will be available outside the file.

app.component.ts
import {Component} from '@angular/core';
@Component({
    selector:'app',
    template: `
        <h1>{{title}}</h1>
    `
})
export class AppComponent{
    title:string = '';
    constructor(){
        this.title = 'Hello World';
    }
} 

Create an angular 2 module

We have created our first angular 2 component, Now we will create an angular 2 module.

What is Angular Module?

Angular apps are modular and Angular has its own modularity system called Angular modules or NgModules.
Every Angular app should have at least one module class, the root module. We bootstrap that module to launch the application.

Angular 2 NgModules contains imports, declarations, and bootstrap.

imports - other modules whose exported classes are needed by component templates declared in this module.
declarations - the view classes that belong to this module. Angular has three kinds of view classes: components, directives, and pipes.
bootstrap - the main application view, called the root component, that hosts all other app views. Only the root module should set this bootstrap property.
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{
    
}

Bootstrap our application

Now we will create 1 more file inside this "App" folder which is main.ts where we will write code for bootstrap our created angular module.
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);


Update index.html file

<!DOCTYPE html>
<html>
    <head>
        <title>This is my frist angular 2 app</title>
        <meta charset="utf-8"/>
        <!-- 1. Load libraries -->
        <!-- Polyfill(s) for older browsers -->
        <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>
        <!-- System.JS configuration -->
        <script src="./Systemjs.config.js"></script>
        <script>
            System.config({
                "defaultJSExtensions" : true
            })
            System.import('app').catch(function(err){
                console.log(err);
            })
        </script>
    </head>
    <body>
        <app>Please Wait...</app>
    </body>
</html>

You can see in the line 1-10, Here I have done system import with 'app' which is defined in the systemjs.config.js map section. This will load "main.js" file from App folder. "main.js" file will be generated when we will run npm start command, where we have bootstrapped our angular 2 module.

Run Application

Now we will run our application. To run the application > open command terminal from View > Integrated Terminal
and write command npm start.
what it will do, it will run this start command from package.json. The start command compiles all the ts file and create javascript file for each ts file and start the lite-server.Now you can see in the browser app application is running.

Must read next part:  Learn about Angular 2 components
Live Demo Download

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.