Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Learn Angular in 10 Days – Day 2

4.91/5 (18 votes)
24 Oct 2017CPOL20 min read 40.7K   462  
Steps of how to get started with Angular
This is Part 2 of a 10 day series on the latest version of Angular. In this post, we will discuss each and every step of how to get started with Angular.

So you finally completed TypeScript fundamentals and are ready for some Angular.

Today, we will learn how to get started with Angular. We will discuss each and every step in detail.

Complete Series

  1. Day 1 – Part 1
  2. Day 1 – Part 2
  3. Day 2
  4. Day 3
  5. Day 4 – Part 1
  6. Day 4 - Execution trick
  7. Day 4 – Part 2
  8. Day 4 – Part 3
  9. Day 5 (Coming soon)
  10. Day 6 (Coming soon)
  11. Day 7 (Coming soon)
  12. Day 8 (Coming soon)
  13. Day 9 (Coming soon)
  14. Day 10 (Coming soon)

Contents

What is Angular?

On Day 1, we saw the basic definition of Angular. It was as follows:

"It’s a JavaScript framework for building HTML based dynamic applications".

I will explain why it is termed as a framework at the end of the series.

Angular ArchitectUre

An Angular application consists of the following things.

Components

As I said before, Angular allows us to develop our UI application in a Component oriented style.

Component oriented style is a new UI design technique proposed in HTML5. Other than Angular, many other major technologies like React, Polymer adapted this methodology too.

According to this approach, UI should be considered as a combination of composable and reusable Web Components.

Instead of looking at UI as a one big piece of HTML, break it into multiple small logical web components. Each component represents a small part of our UI. Creating a component is like creating a new HTML element.

It will have its own independent existence and will not affect other web components.

Every component will be a combination of three things: HTML, some dynamic logic, styles.

Each component will be designed in such a way that its logic and style won’t affect any other component’s logic or style.

For instance, let’s say we want to design the following UI.

Image 1

In normal approach, it is a simple HTML file but in Component oriented style, it’s a combination of lot of components. Let’s identify those components.

Image 2

As you can see, multiple components are placed together to make up the final UI. A component called RootComponent wrapped the other components into one.

Don’t worry if you are not 100% clear about the component word, you will be more confident once we start with a demo.

Services

Services are injectable application logic in the Angular application. We will explore more about it later in the series.

Pipes

Pipes represent display-value transformation logic in the Angular application. We will explore it later in the series.

Directives

Directives will be used when we want to modify the default behavior of the DOM element. We will explore it later in the series.

Angular Modules

Components, Directives, Services and Pipes are boxed into Angular Modules (AKA NgModules). It’s a logical container for related Angular constructs.

Image 3

A single Angular application may have more than one Angular Module defined, one of which will be bootstrapped in the beginning.

Note

Overall, we spoke about three types of Modules.

TypeScript Modules, JavaScript Modules and Angular Modules. All are different concepts and different meaning. Let’s revise all of them.

  • JavaScript Module allows us to group JavaScript code into one logical unit. It will be done via Module Loaders and Module Formatters.
  • TypeScript Module is a way to do the same thing in Typescript world. When TypeScript Module is compiled, we will get JavaScript Module as final product.
  • Angular Module is an Angular concept. Angular Module is a logical parent of all other Angular constructs (components, directives, pipes and services). We can call Angular Module a logical encapsulation whereas JavaScript Module is a physical encapsulation.

Creating Angular Project

It has three steps:

  1. Setup the project.
  2. Create the Root Component.
  3. Use the component.

Image 4

Setup the Project

Image 5

Simply create a new folder "AngularProject" anywhere in your machine.

Image 6 1. Create Root folder

2. Download Angular Framework

Image 7 In order to start with our Angular Project, first we need to download the framework which is available as a collection of JavaScript libraries.
Here is the list of those libraries.
  • @angular/common
  • @angular/compiler
  • @angular/core
  • @angular/forms
  • @angular/http
  • @angular/platform-browser
  • @angular/platform-browser-dynamic
  • @angular/router

We can download this files using "npm". It involves simple two steps.

1. Create package.json

Image 8

Create a new file called "package.json" in the "AngularProject" folder with the following content:

JavaScript
{
  "name": "myfistproject",
  "version": "1.0.0"
}

If you don’t want to create the above file manually, then open Command prompt and navigate to the "AngularProject" folder and fire the below command:

JavaScript
NPM init

(Please note, its "NPM" not "npm".)

It will ask for few command line inputs.

Provide package name as "myfirstangularproject" and simply skip everything else.

(Just press Enter till it says "Is this ok? (yes)").

Simply type "yes" and press Enter.

It will create a new file called "package.json". You may notice some additional entries in the file other than "name" and "version". Simply ignore them.

2. Download Files

Write the following command in Command prompt.Image 9

JavaScript
npm install @angular/common @angular/core @angular/compiler
@angular/forms @angular/http @angular/platform-browser 
@angular/platform-browser-dynamic
@angular/router --save

It will create a new folder called "node_modules" and download all the files inside it in one go.

Note

All the Angular Libraries are Modular. All of them are written in "UMD" Module format. "UMD" stands for Universal Module definition and it’s a Module formatter which is compatible with both "AMD" and "CommonJS" format. It makes both "CommonJs" and "AMD" code possible to work with Angular.

You may have noticed the additional "--save" flag passed with "npm" command.

It will create a new entry inside "package.json" called "dependencies" as follows:

JavaScript
{
  "name": "myfistproject",
  "version": "1.0.0",
  "dependencies": {
    "@angular/common": "^4.3.1",
    "@angular/compiler": "^4.3.1",
    "@angular/core": "^4.3.1",
    "@angular/forms": "^4.3.1",
    "@angular/http": "^4.3.1",
    "@angular/platform-browser": "^4.3.1",
    "@angular/platform-browser-dynamic": "^4.3.1",
    "@angular/router": "^4.3.1"
  }
}

This file makes future reinstallation very easy.

Next time, only fire the below command:

JavaScript
npm install

It will read the "package.json" file and based on dependencies section, download everything.

Why Should I Reinstall?
  • Normally, when it comes to deployment, node_modules folder will be skipped to reduce setup size. In the server machine (where the app will be installed), simply using the above command, all files will be downloaded again.
  • Also upgrading will be easier. Simply change the version in file and execute "npm install" command.

3. Download Other Angular Dependencies

Angular is dependent on some third party libraries. They are Zone.js, Core-js and rxjs.

In order to get started with Angular, you don’t need to have detailed knowledge about these libraries.

All three of these libraries are internally used by Angular files.

  • Core-js: Angular JavaScript files contain a lot of code in ES2015 standard. Including this library in our project makes ES2015 code work in ES5 compatible browsers.
  • Zone.js: is used to create an execution environment for our code.
  • RxJS: It stands for reactive extensions. Please don’t get confused between RxJS and ReactJS. ReactJS is UI designing library by Facebook whereas RxJS is a library used for reactive programming. Angular uses this library internally. We will see some of them in action later in this series.

Note

You do not need to know Reactive Programming or RxJS in order to build even the most complex applications with Angular.

To download these files, write the following command in Command Prompt.

JavaScript
npm install zone.js rxjs core-js --save

4. Install TypeScript

Image 10

We are going to write our code in TypeScript. So we need TypeScript compiler.

We have already installed TypeScript compiler in Day 1 of this series. If you missed it, you can do it using the following command:

JavaScript
npm install typescript -g

5. Configure TypeScript

Create a new folder inside the "AngularProject" folder and call it "TypeScriptFiles".

This folder is going to be our root folder for all the future TypeScript files.

Now create TypeScript configuration file, "tsconfig.json" inside this folder with the following contents:

JavaScript
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

We have already discussed each of the above CompilerOptions on Day 1.

On Day 1, we have also discussed about "Type Definition files" which is a way to teach TypeScript about external JavaScript files. Considering that, our next move will be downloading Angular "Type Definition files".

The good news is, no need to download "Type Definition files" manually. Angular files are downloaded as package using "npm" and fortunately, this package contains both JavaScript file and respective "Type Definition file".

Let’s examine one of the folders. Open the "node_modules/@angular/platform-browser-dynamic" folder.

Image 11

6. Setup Web Server

Image 12

We will also require one simple web server for testing purposes. On Day 1 of this series, we saw demonstration of "http-server". This time, let’s look at the one called "lite-server".

Install it using "npm" as follows:

JavaScript
npm install lite-server -g

7. Download Module Loader

On Day 1, we spoke about Module Formatters and Module loaders.

We have seen two demos:

  1. JavaScript Module demo with AMD + SystemJs
  2. TypeScript Module demo

(If you missed any of them, I strongly recommend you to go through it before continuing.)

If you remember about second demo, we executed generated JavaScript in the "Node" environment using the "node" command and to our surprise, the demo worked without any Module loader. The reason is very simple. "Node" has inbuilt support for "CommonJS" format which is the default Module formatter of TypeScript.

Our Angular project is going to follow "CommonJS" format but the execution environment is going to be browser. Hence, we need Module loader this time.

Fire the following command in command prompt:

npm install systemjs --save

Here, we complete the setup process:

Image 13

Just to conclude, you should have the following things with you:

  • AngularProject” folder
  • TypeScriptFiles” folder inside “AngularProject” Folder.
  • tsconfig.json” file inside “TypeScriptFiles” folder with the following contents:
    JavaScript
    {
      "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [ "es2015", "dom" ],
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true
      }
    }
  • package.json” inside “AngularProject” folder with the following contents:
    JavaScript
    {
      "name": "myfistproject",
      "version": "1.0.0",
      "dependencies": {
        "@angular/common": "^4.3.1",
        "@angular/compiler": "^4.3.1",
        "@angular/core": "^4.3.1",
        "@angular/forms": "^4.3.1",
        "@angular/http": "^4.3.1",
        "@angular/platform-browser": "^4.3.1",
        "@angular/platform-browser-dynamic": "^4.3.1",
        "@angular/router": "^4.3.1",
        "core-js": "^2.4.1",
        "rxjs": "^5.4.2",
        "systemjs": "^0.20.17",
        "zone.js": "^0.8.14"
      }
    }

Create Root Component

If you remember the Angular Architecture, UI is composed as tree of Angular components – one component will be placed besides another component, both of which may be wrapped up by one outer component and so on. This component hierarchy starts with one Root Component.

Here are the steps for creating such a Root Component.

  • Create Angular Module
  • Create Angular Component
  • Add Component to Module
  • Bootstrap Module
  • Bootstrap Component

1. Create Angular Module

As I said before, everything in Angular belongs to some Angular Module. The same rule is applied for the Root Component. So it’s time to create our very first Angular Module.

It can be done by creating a TypeScript class decorated with the "NgModule" decorator.

What is NgModule?

"NgModule" is a decorator defined inside the "@angular/core" library. In order to use it, first we need to import it as follows:

JavaScript
import {NgModule} from
"../../node_modules/@angular/core/core"

Do you remember "moduleResolution" option we discussed on Day 1?

(I strongly recommend you to go through it again, if you missed it or are unable to recollect it.)

According to the explanation we had on Day 1, when "moduleResolution" is set to "node", we can rewrite the above statement as follows:

JavaScript
import {NgModule} from "@angular/core"

Creating Module

First, create a new folder inside the "TypeScriptFiles" folder called "AppModule".

Then create a new TypeScript file called "app.module.ts" with the following content:

JavaScript
import {NgModule} from "@angular/core"
@NgModule()
class AppModule{

}

2. Create Angular Component

Finally, we reach the point where we will create our very first Angular component. It can be done by creating a class decorated with "Component" decorator defined inside "@angular/core" library.

Create a new TypeScript file called "app.component.ts" with the following code snippet:

JavaScript
import {Component} from "@angular/core"

@Component({
selector:'app-component',
template:`<h1>Welcome to Learn Angular in 10 days series</h1>
<i>Here is the Day 2</i>`
}
)
class AppComponent{

}

You can see two parameters passed to the "Component" decorator.

  1. selector – a simple text representing the tag name of component
  2. template – UI part of the component

No need to worry about these two attributes right now. You will see both of them in action very soon.

3. Add Component to Module

It can be done using "declarations" option in "NgModule" decorator.

Check the below code:

JavaScript
import {NgModule} from "@angular/core"
@NgModule({
    declarations:[AppComponent] //New statement
})
class AppModule{

}

(Check line number 4 in the above code, a new "declarations" section is added.)

Are We Missing Something?

Image 14

Have we forgotten about something? Try to think for a minute before you continue reading the next line.

We forgot about TypeScript Modules. AppComponent and AppModule both are written in separate TypeScript files, hence both of them will be considered as independent TypeScript Modules. We have to export AppComponent in app.component.ts and import in "app.module.ts".

So here is the final code.

app.module.ts
JavaScript
import {NgModule} from "@angular/core"
import {AppComponent} from "./app.component"
@NgModule({
    declarations:[AppComponent]
})
class AppModule{

}
app.component.ts
JavaScript
import {Component} from "@angular/core"
@Component({
selector:'app-component',
template:`<h1>Welcome to Learn Angular in 10 days series</h1>
<i>Here is the Day 2</i>`
}
)
export class AppComponent{

}

4. Bootstrap the Module

As I said in the beginning, a single Angular application may have more than one Angular Module defined, but only one of them will be bootstrapped in the beginning. Unlike in AngularJS, this bootstrapping process has to be done manually with the help of "platformBrowserDynamic" function defined inside the "@angular/platform-browser-dynamic" library.

First, attach export keyword to AppModule class. It allows us to import it in another file.

JavaScript
...
export class AppModule{
...

Then create a new file called "Main.ts" in the "TypeScriptFiles" folder with the following content:

JavaScript
import {platformBrowserDynamic} from "@angular/platform-browser-dynamic"
import {AppModule} from "./AppModule/app.module"
platformBrowserDynamic().bootstrapModule(AppModule);

Angular is not limited to only working in the browser. It can be used to write code which can execute in mobile devices using Ionic or some similar framework. This is why we need to tell Angular exactly how we want it to bootstrap itself, in our case, we are running in the browser so we use the platformBrowserDynamic function to bootstrap our application.

5. Bootstrap the Component

Later in the series, you will see lot of new Modules coming into the picture with more than one Component. For this initial demo, we will stick to one Module and one Component.

Now the question is, if one Angular Module is going to have more than one component, how Angular identifies the root component.

It can be done by using the "bootstrap" option in "NgModule" decorator.

Check the below code:

JavaScript
...
import {AppComponent} from "./app.component"
@NgModule({
    declarations:[AppComponent],
    bootstrap:[AppComponent]
})
export class AppModule{
...

6. Compile

Open command prompt, navigate to "TypeScriptFiles" folder and fire "tsc" command.

It should compile successfully.

[If you are facing any error during compilation, I strongly recommend you to go through the above steps once again, read each and every statement and only continue after you get success.]

Use the Component

Now it’s finally time to use the component created above in a real web application.

1. Create HTML File

Our very first step will be creating startup HTML file. Create a simple HTML file "Index.html" in the "AngularProject" folder.

2. Include Non Modular Script Files

Include the following three JS files in the "index.html".

  • zone.js
  • shim.min.js (which is core-js library)
  • system.src.js

The final HTML looks like the following:

HTML
<!DOCTYPE html>
<html>
  <head>
    <title>Angular QuickStart</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/systemjs/dist/system.src.js"></script>
  </head>
  <body>
  </body>
</html>

3. Load Main.js File

Load Main.js file using SystemJs loader in "index.html". Check out the below code:

HTML
...    
    <script>  
      SystemJS.import("/TypeScriptFiles/Main.js");
    </script>
</head>
<body>
...

No need to include any other JS files. All the necessary files will be loaded automatically at runtime by our Module Loader (SystemJs) based on need.

  1. Zone.js, shim.min.js and system.src.js are manually included because they don’t contain Modular code (they are not following any Module formatter). Hence Module loader won’t be able to load any of them at runtime.
  2. Main.js is our startup file. It’s an entry point. Hence, it needs to be included manually.

4. Use the Root Component

Use the root component’s selector ("app-component") as a tag in "index.html" as follows:

HTML
    </script>
  </head>
  <body>
      <app-component>Component is Loading.....</app-component>
  </body>
</html>

5. Execute

Open Command prompt. Navigate to folder "AngularProject". Now fire "lite-server" as follows:

Image 15

  • It will start a server in local machine (in port number 3000 by default) pointing to "AngularProject" folder.
  • Launch the browser (Internet Explorer) with hosting URL (http://localhost:3000).
    (I recommend you to open Chrome with the same URL. Chrome will make our life easy when it comes to JavaScript to debugging.)
  • By default, lite-server executes the "index.html" in root folder, so we need to put the filename in address bar.

Note

I recommend you to use two different command prompts. One pointing to "TypeScriptFiles" folder. It will be used for compiling typescript files. Second for "lite-server". It will keep your life easy and won’t let you concentrate on learning.

6. Check the Output

Unfortunately in the first go, we won’t get the expected output. We get something like below:

Image 16

Bugs and Solutions

1. Identify the Bug

In order to identify the reason for not getting expected output, open developer tools in browser and check if there is any JavaScript error. (In Chrome, you can get the developer tools by pressing F12 and then check the console tab for JavaScript error.)

Image 17

As you can see, there are four errors. Let’s concentrate on the first error.

Error is related to loading "@angular/platform-browser-dynamic".

Understand the Problem

In our case, SystemJs (Module Loader) is responsible for loading other files at runtime. It means SystemJs is unable to find "@angular/platform-browser-dynamic".

There are two very strange things happening.

  1. "@angular" is a folder inside "node_modules" folder which has a sub folder called "platform-browser-dynamic". It means SystemJs is trying to load folder. Module Loaders are meant for loading JS file dynamically and in our case, it is trying to load folder.
  2. Secondly, @angular folder is present inside the "node_modules" folder but SystemJs is searching for it inside root folder. (Examine the error carefully, it says, "Failed to load ‘:3000/@angular/platform-browser-dynamic’_").

Open "main.js" file. It contains the following code:

JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var platform_browser_dynamic_1 = require("@angular/platform-browser-dynamic");
var app_module_1 = require("./AppModule/app.module");
platform_browser_dynamic_1.platformBrowserDynamic().bootstrapModule(app_module_1.AppModule);

If you remember, we have written the following statement in our TypeScript file.

JavaScript
import {NgModule} from ("@angular/platform-browser-dynamic"

Hence, generate JS file contains the following statement:

JavaScript
var platform_browser_dynamic_1 = require("@angular/platform-browser-dynamic");

It is supposed to be the following:

JavaScript
var platform_browser_dynamic_1 = 
require("/node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js");
Solution for the Problem

Solution is "teaching". You have to teach SystemJs that, loading "@angular/platform-browser-dynamic" means loading "/node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js". In fact, we have to do it for every Angular library. It can be done by creating SystemJs Configuration file.

2. Configure System JS

Create a new JS file inside "AngularProject" folder and name it "system.config.js".

Now put the following content inside it.

JavaScript
(function (global) {
  System.config({
    map: {
      '@angular/core': '/node_modules/@angular/core/bundles/core.umd.js',
      '@angular/common': '/node_modules/@angular/common/bundles/common.umd.js',
      '@angular/compiler': '/node_modules/@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 
      '/node_modules/@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 
      '/node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': '/node_modules/@angular/http/bundles/http.umd.js',
      '@angular/router': '/node_modules/@angular/router/bundles/router.umd.js',
      '@angular/forms': '/node_modules/@angular/forms/bundles/forms.umd.js',
    }
  });
})(this);

Include the above file in "index.html" after system.src.js and before main.js as follows:

HTML
<script src="/node_modules/systemjs/dist/system.src.js"></script>
<script src="system.config.js"></script>
<script>
  SystemJs.import("/TypeScriptFiles/Main.js");
</script>

3. Recheck the Output

lite-server is very smart. It keep a watch on all the files on your "TypeScriptFiles" folder and automatically refreshes the browser if any of the files get changed.

Check the output after including "system.config.js" file.

This time, you will get the following error:

Image 18

Understand the Problem

Take a while and try to see if you can think about the reason for this error.

Check the error carefully. Path is correct, file name is wrong. It is looking for a file called "app.module" which we don’t have. We have "app.module.js".

Solution for This Problem

Solution is again teaching. We have to teach SystemJs to add default extension to all the requests.

4. Reconfigure System JS

Add some more settings to "system.config.js" as follows:

JavaScript
(function (global) {
  System.config({
    map: {
      '@angular/core': '/node_modules/@angular/core/bundles/core.umd.js',
      '@angular/common': '/node_modules/@angular/common/bundles/common.umd.js',
      '@angular/compiler': '/node_modules/@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 
      '/node_modules/@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 
      '/node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': '/node_modules/@angular/http/bundles/http.umd.js',
      '@angular/router': '/node_modules/@angular/router/bundles/router.umd.js',
      '@angular/forms': '/node_modules/@angular/forms/bundles/forms.umd.js',
    },
     packages: {
      'TypeScriptFiles': {
        defaultExtension: 'js'
      }
    }
  });
})(this);

Check the new packages section above.

It contains an entry which teaches SystemJs to add "js" extension to all requests made for files inside "TypeScriptFiles" folder.

5. Recheck the Output

This time, the error will be as follows:

Image 19

Again, just like before, instead of "node_modules", the root folder is considered.

But this time. adding one entry in the map section of SystemJs will not solve the issue because "rxjs" is a big library. It has lot of JavaScript files inside it. Two of them are "Observable.js" and "Subject.js".

We have to add one entry for one such JavaScript file. For example, for the above error, we have the following entry in map section:

JavaScript
"rxjs/Observable": "/node_modules/rxjs/Observable.js"

Note: Don’t add the above entry in "system.config.js".

6. Reconfigure System JS

Adding one entry for one file will be too much of work, so let’s do it in a shortcut way. We will use of both "map" and "packages" to achieve it.

JavaScript
(function (global) {
  System.config({
    map: {
      '@angular/core': '/node_modules/@angular/core/bundles/core.umd.js',
      '@angular/common': '/node_modules/@angular/common/bundles/common.umd.js',
      '@angular/compiler': '/node_modules/@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 
      '/node_modules/@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 
      '/node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': '/node_modules/@angular/http/bundles/http.umd.js',
      '@angular/router': '/node_modules/@angular/router/bundles/router.umd.js',
      '@angular/forms': '/node_modules/@angular/forms/bundles/forms.umd.js',

      'rxjs':'/node_modules/rxjs',
    },
     packages: {
      'TypeScriptFiles': {
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

As you can see, there is a new entry in both "map" and "packages" section now.

7. Recheck the Output

This time, error will be very different.

Image 20

This time error is about something called "BrowserModule".

"BrowserModule"is an Angular Module defined inside "@angular/platform-browser" library which contains services which will be required to launch application in browser.

8. Load BrowserModule

We can make "BrowserModule" load when "AppModule" is bootstrapped by using "import" option in the "NgModule" decorator. Here is the complete revamped code AppModule.

9. Recheck the Output

This time, we have made a change in the TypeScript file which needs recompilation.

Recompile it and check the output.

Image 21

Finally, our very first Angular output is here.

I request you to try all of the above steps one after the other. Implement the solution only after error is properly understood. Proceed further with the series only after you feel confident about Day 1 and Day 2.

Restructured Steps

The above steps are very important from a learning point of view. It will give you a nice idea about the internals of Angular project and make it easy to customize project structure as per the need.

Follow the below steps in case you are interested to get in one go. (Preferred way in real time project)

Image 22

Complete Execution Process

Step 1

Browser renders contents in "index.html" file. In this situation, "app-component" tag will be a simple HTML tag and get displayed as it. In our case, it will show "Component is Loading....." message.

Step 2

"zone.js", "shim.min.js", "system.src.js" and "system.config.js" get downloaded.

Step 3

"main.js" file will be loaded by SystemJs loader. It in turn loads other necessary Angular and non-Angular JavaScript files dynamically.

Step 4

"main.js" contains an executable statement which will bootstrap the AppModule.

Step 5

Bootstrapping AppModule leads to bootstrap of AppComponent. Angular will create a new instance AppComponent class and search for AppComponent’s selector (that is "app-component") in "index.html" file.

In case "index.html" won't contain AppComponent selector, the following error will be raised.

Image 23

If our case, we have it. So simply Component’s template will be displayed in place of "app-component".

Other Ways of Developing Angular Application

There are two more ways to develop Angular application.

  1. Download Quick start project from the following link:

    https://github.com/Angular/quickstart/archive/master.zip

    It contains almost everything configured for you.

  2. Use Angular CLI – Angular CLI is a command line interface using which we can create Angular Projects quickly and easily.

    We will have a detailed demo in one of the future articles about Angular CLI.

When it comes to learning, I personally prefer the manual way. I follow a simple philosophy, "More errors we get during learning, less we get in production".

Important Points to Consider

  1. Typescript compiler can be started in watch mode. Simply fire "tsc –w" command in command prompt. It will compile all existing TypeScript files plus keep a watch on folder and all sub folders. Any time, any TypeScript file gets changed, it will immediately recompile it.
  2. For our demo, we have used "lite-server" for creating web server. You can choose any other too. It’s your choice.
  3. Now the most important point – Use your editor and environment efficiently. Try to take full advantage of your development environment.
    1. Many modern editors like Visual Studio and Visual Studio Code, WebStorm are aware about TypeScript, hence they provide rich intellisense support for syntaxes. So choose your editor wisely. For this series, I am using Visual Studio Code which can be downloaded from https://code.visualstudio.com/.
    2. Check if your editor has inbuilt support for TypeScript compilation. For instance, Visual Studio has it. In such case, you can skip the entire TypeScript installation and TypeScript configuration step.
    3. Check if your editor has inbuilt support for light weight web server for testing purposes. For example, Visual Studio provides IIS web express. In such case, you can just ignore about "lite-server" or other node servers.

Note

As of now, just to be in sync, I recommend you follow the same editor and tools I am using. Once you are done with the entire series, you can try it in your editor and environment.

Summary

So finally, we are done with our Day 2.

Practice it multiple times, don’t rush to jump to the next day. Once you get comfortable and have confidence in it, move on to Day 3.

Stay tuned!

History

  • 3rd August, 2017: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)