About this book

In the last few years, Angular has established itself as the number one choice of JavaScript Developers. What makes Angular special is performance and productivity. With Angular, developers can work on consistent coding patterns and build web applications that are powerful and scalable.

This book will you get you up and running with Angular and teach how to build modern web applications. It starts with basics of Angular 2 and then brushes you up with the new features of Angular 4. You will learn the core concepts involved in building web applications with Angular such as Data Binding, Routing, Dependency Injection, and much more. The book teaches how to build components and use them to build web apps of your choice. It will help you to handle different kinds of forms and learn the concept of reactive programming. Finally the book teaches how to build visually appealing and responsive UIs.

Publication date:
May 2017
Publisher
Packt
Pages
226
ISBN
9781785880728

 

Chapter 1. Getting Started

In this chapter, we are going to learn the Angular framework basics and new features. We will learn how to use features from future versions of JavaScript and TypeScript to develop modern web applications using Angular. After going through this chapter, the reader will understand the following concepts:

  • The Angular framework and its new features
  • Setting up the environment for development
  • The basics of TypeScript
  • Angular application basics
  • How to write your first Angular application?
 

Introduction to Angular


What is Angular? It is an open source modern JavaScript framework in order to build the Web, mobile web, native mobile, and native desktop applications. It can also be used in combination with any server-side web application framework, such as ASP.NET and Node.js. Angular is the successor of AngularJS 1, which is one of the best JavaScript frameworks for building client-slide web applications, used by millions of developers across the globe.

Even though the developer community highly appreciates AngularJS 1, it has its challenges. Many developers feel that the AngularJS 1 learning curve is high. Out-of-the-box performance in complex applications with a huge amount of data is not that great, which is essential in enterprise applications. The API to build directives is very confusing and complex, even for an experienced AngularJS 1 programmer, which is the key concept to build UI applications based component-based architecture.

Angular is the next version of AngularJS 1.x, but it is a complete rewrite from its predecessor. It is built on top of the latest web standards (web components, Observables, and decorators), the learning curve is minimal, and performance is better. This book will cover the latest version of Angular, which is version 4, at the time of writing this book. Angular 4 is an incremental update from Angular 2, unlike Angular 2.

Note

When we use the term Angular, we are referring to the latest version of the framework. Anywhere we need to discuss version 1.x, we will use the term AngularJS.

What is new in Angular?

Many concepts in version 1.x are irrelevant in Angular, such as controller, directive definition object, jqLite, $scope, and $watch. Even though lots of concepts are irrelevant, lots of goodness in AngularJS 1.x is carried forward to Angular such as services, dependency injection, and pipes. Here is a list of the new features in Angular:

  • Components
  • New templating syntax
  • Unidirectional data flow
  • Ultra-fast change detection
  • New component router
  • Observables
  • Server-side rendering
  • New languages for development
  • ES2015
  • TypeScript
  • Ahead of time compilation
 

Setting up the environment


We can start developing our Angular applications without any setup. However, we are going to use Node.js and npm (node package manager) for tooling purposes. We need them for downloading tools, libraries, and packages. We also use them for build process automation. Angular applications are as follows:

  • Node.js is a platform built on top of V8, Google's JavaScript runtime, which also powers the Chrome browser
  • Node.js is used for developing server-side JavaScript applications
  • The npm is a package manager for Node.js, which makes it quite simple to install additional tools via packages; it comes bundled with Node.js

Installing Node.js and npm

The easiest way to install Node is to follow the instructions at: https://nodejs.org. Download the latest version of Node for the respective operating system and install it. The npm is installed as part of the Node.js installation.

Once we install Node.js, run the following commands on the command line in Windows or Terminal in macOS to verify that Node.js and npm are installed and set up properly:

$ node -v
$ npm -v

The preceding commands will display currently installed Node.js and npm versions, respectively:

Note

The Angular documentation recommends installing at least Node.js v4.x.x, NPM 3.x.x, or higher versions.

 

Language choices


We can write the Angular applications in JavaScript or any language that can be compiled into JavaScript. Here, we are going to discuss the three primary language choices.

ECMAScript 5

ECMAScript 5 (ES5) is the version of JavaScript that runs in today's browsers. The code written in ES5 does not require any additional transpilation or compilation, and there is no new learning curve. We can use this as it is to develop Angular applications.

ECMAScript 2015

ECMAScript 2015 (ES2015), previously known as ECMAScript 6 (ES6), is the next version of JavaScript. ES2015 is a significant update to the JavaScript language; the code written in ES2015 is a lot cleaner than ES5. ES2015 includes a lot of new features to increase the expressiveness of JavaScript code (for example, classes, arrows, and template strings).

However, today's browsers do not support all the features of ES2015 completely (for more information please refer to: https://caniuse.com/#search=es6). We need to use transpilers like Babel to transform ES2015 code into ES5-compatible code so that it works in today's browsers.

Note

Babel is a JavaScript transpiler, and it transpiles our code written in ES2015 to ES5 that runs in our browsers (or on your server) today. Learn more about Babel at https://babeljs.io.

TypeScript

TypeScript is a superset of JavaScript, which means all the code written in JavaScript is valid TypeScript code, and TypeScript compiles back to simple standards-based JavaScript code, which runs on any browser, for any host, on any OS. TypeScript lets us write idiomatic JavaScript. It provides optional static types that are useful for building scalable JavaScript applications and other features such as classes, modules, and decorators from future versions of the JavaScript.

It provides the following features to improve developer productivity and build scalable JavaScript applications:

  • Static checking
  • Symbol-based navigation
  • Statement completion
  • Code refactoring

These features are critical in large-scale JavaScript application developments, so in this book, we are going to use TypeScript for writing Angular applications. The Angular framework itself was developed in TypeScript.

Note

All the ECMAScript 5 code is valid in ECMAScript 2015; all ECMAScript 2015 code is valid TypeScript code.

Installing TypeScript

We can install TypeScript in multiple ways, and we are going to use npm, which we installed earlier. Go to the command line in Windows or Terminal in macOS and run the following command:

$ npm install -g typescript

The preceding command will install the TypeScript compiler and makes it available globally.

TypeScript basics – types

TypeScript uses .ts as a file extension. We can compile TypeScript code into JavaScript by invoking the TypeScript compiler using the following command:

$ tsc <filename.ts>

JavaScript is a loosely typed language, and we do not need to declare the type of a variable ahead of time. The type will be determined automatically while the program is being executed. Because of the dynamic nature of JavaScript, it does not guarantee any type safety. TypeScript provides an optional type system to ensure type safety.

In this section, we are going learn the important data types in TypeScript.

String

In TypeScript, we can use either double quotes (") or single quotes (') to surround strings similar to JavaScript.

var bookName: string = "Angular"; 
bookName = 'Angular UI Development'; 

Number

As in JavaScript, all numbers in TypeScript are floating point values:

var version: number = 4; 

Boolean

The boolean data type represents the true/false value:

var isCompleted: boolean = false; 

Array

We have two different syntaxes to describe arrays, and the first syntax uses the element type followed by []:

var fw: string[] = ['Angular', 'React', 'Ember']; 

The second syntax uses a generic array type, Array<elementType>:

var fw: Array<string> = ['Angular', 'React', 'Ember']; 

Enum

TypeScript includes the enum data type along with the standard set of data types from JavaScript. In languages such as C# and JAVA, an enum is a way of giving more friendly names to sets of numeric values, as shown in the following code snippet:

enum Frameworks { Angular, React, Ember }; 
var f: Frameworks = Frameworks.Angular; 

The numbering of members in the enum type starts with 0 by default. We can change this by manually setting the value of one of its members. As illustrated earlier, in code snippet, the Frameworks.Angular value is 0, the Frameworks.React value is 1, and the Frameworks.Ember value is 2.

We can change the starting value of enum type to 5 instead of 0, and remaining members follow the starting value:

enum Frameworks { Angular = 5, React, Ember }; 
var f: Frameworks = Frameworks.Angular; 
var r: Frameworks = Frameworks.React; 

In the preceding code snippet, the Frameworks.Angular value is 5, the Frameworks.React value is 6, and the Frameworks.Ember value is 7.

Any

If we need to opt out type-checking in TypeScript to store any value in a variable whose type is not known right away, we can use any keyword to declare that variable:

var eventId: any = 7890; 
eventId = 'event1'; 

In the preceding code snippet while declaring a variable, we are initializing it with the number value, but later we are assigning the string value to the same variable. TypeScript compiler will not report any errors because of any keyword. Here is one more example of an array storing different data type values:

var myCollection:any[] = ["value1", 100, 'test', true]; 
myCollection[2] = false; 

Void

The void keyword represents not having any data type. Functions without return keyword do not return any value, and we use void to represent it.

function simpleMessage(): void { 
    alert("Hey! I return void"); 
} 

Let's write our first TypeScript example and save it into the example1.ts file:

var bookName: string = 'Angular UI Development'; 
var version: number = 2; 
var isCompleted: boolean = false; 
var frameworks1: string[] = ['Angular', 'React', 'Ember']; 
var frameworks2: Array<string> = ['Angular', 'React', 'Ember']; 
enum Framework { Angular, React, Ember }; 
var f: Framework = Framework.Angular; 
var eventId: any = 7890; 
eventId = 'event1'; 
var myCollection:any[] = ['value1', 100, 'test', true]; 
myCollection[2] = false; 

Let's compile the example1.ts file using the TypeScript command-line compiler:

$ tsc example1.ts

The preceding command will compile TypeScript code into plain JavaScript code into the example1.js file; this is how it will look, and it is plain JavaScript:

var bookName = 'Angular UI Development'; 
var version = 2; 
var isCompleted = false; 
var frameworks1 = ['Angular', 'React', 'Ember']; 
var frameworks2 = ['Angular', 'React', 'Ember']; 
var Framework; 
(function (Framework) { 
    Framework[Framework["Angular"] = 0] = "Angular"; 
    Framework[Framework["React"] = 1] = "React"; 
    Framework[Framework["Ember"] = 2] = "Ember"; 
})(Framework || (Framework = {})); 
; 
var f = Framework.Angular; 
var eventId = 7890; 
eventId = 'event1'; 
var myCollection = ['value1', 100, 'test', true]; 
myCollection[2] = false; 

Functions

Functions are the fundamental building blocks of any JavaScript application. In JavaScript, we declare functions in two ways.

 

 

Function declaration – named function

The following is an example of function declaration:

function sum(a, b) { 
return a + b; 
} 
Function expression – anonymous function

The following is an example of function expression:

var result = function(a, b) {  
      return a + b; 
} 

In JavaScript, unlike any other concept, there is no type safety for functions also. We do not have any assurance on data types of parameters, return type, the number of parameters passed to function, TypeScript guarantees all this. It supports both the syntaxes.

Here are the same functions written in TypeScript:

function sum(a: number, b: number): number { 
      return a + b; 
} 

var result = function(a: number, b: number): number {  
return a + b;  
} 

The preceding TypeScript functions are very similar to the JavaScript syntax except parameters, and return type has type on them, which ensures type safety while invoking them.

Classes

The ES5 does not have the concept of classes. However, we can mimic the class structure using different JavaScript patterns. The ES2015 does support classes. However, today, we can already write them in TypeScript. In fact, the ECMAScript 2015 class syntax is inspired by TypeScript.

The following example shows a person class written in TypeScript:

class Person { 
    name: string; 
    constructor(name: string) { 
        this.name = name; 
    } 
    sayHello() { 
        return 'Hello ' + this.name; 
    } 
} 

var person = new Person('Shravan'); 
console.log(person.name); 
console.log(person.sayHello()); 

The preceding Person class has three members - a property named name, a constructor, and a method sayHello. We should use this keyword to refer to the properties of the class. We created an instance of the Person class using the new operator. In the next step, we invoke the sayHello() method of the Person class using its instance created in the previous step.

Save the preceding code into the person.ts file and compile it using the TypeScript command-line compiler. It will compile TypeScript code into plain JavaScript code into the person.js file:

$ tsc person.ts

Here is the plain JavaScript code, which was compiled from the TypeScript class:

var Person = (function () { 
    function Person(name) { 
        this.name = name; 
    } 
    Person.prototype.sayHello = function () { 
        return 'Hello ' + this.name; 
    }; 
    return Person; 
}()); 

var person = new Person('Shravan'); 
console.log(person.name); 
console.log(person.sayHello()); 

 

 

Note

To learn more about functions, classes, and other concepts in TypeScript, check out http://typescriptlang.org.

 

Writing your first Angular application


Angular follows a component-based approach to building an application. An application written in AngularJS 1 is a set of individual controllers and views, but in Angular, we need to treat our application as a component tree.

The Angular application component tree will have one root component; it will act as the entry point of the application. All the other components that are part of the application will load inside the root component, and they can be nested in any way that we need inside the root component.

Angular also has the concept of modules, which are used for grouping components with similar functionality. An Angular application should have minimum one module and minimum one component that should be part of that module. Component acts as root component, and module acts as root module.

Set up the Angular application

Let' us begin writing our first Angular application by creating the following folder structure and files:

hello-world
├─ index.html
├─ package.json
├─ tsconfig.json
└─ src
└─ app.ts

Step 1

As we are going to write our application in TypeScript, let us begin with the tsconfig.json file first. It is the TypeScript configuration file that contains instructions for its compiler on how to compile TypeScript code into JavaScript. If we do not use the tsconfig.json file, the TypeScript compiler uses the default flags during compilation, or we can pass our flags manually every time while compiling.

The tsconfig.json file is the best way to pass the flags to the TypeScript compiler, so we do not need to type them every time. Some of the flags here are mandatory for the Angular application written in TypeScript; we are going to use this file throughout the book. Add the following code to the tsconfig.json file:

{ 
  "compilerOptions": { 
    "target": "es5", 
    "module": "commonjs", 
    "moduleResolution": "node", 
    "sourceMap": true, 
    "emitDecoratorMetadata": true, 
    "experimentalDecorators": true, 
    "lib": ["es2015", "dom"], 
    "noImplicitAny": true, 
    "suppressImplicitAnyIndexErrors": true, 
    "typeRoots": ["node_modules/@types/"] 
  }, 
  "compileOnSave": true, 
  "exclude": ["node_modules/*"] 
} 

Note

Downloading the example codeDetailed steps to download the code bundle are mentioned in the Preface of this book. The code bundle for the book is also hosted on GitHub at: https://github.com/PacktPublishing/Building-Modern-Web-Application-using-Angular. We also have other code bundles from our rich catalog of books and videos available at: https://github.com/PacktPublishing/. Check them out!

The explanation for flags specified in the tsconfig.json file are as follows:

  • target: Specifies ECMAScript target version: es3 (default), es5, or es2015
  • module: Specifies module code generation: commonjs, amd, system, umd or es2015
  • moduleResolution: Specifies module resolution strategy: node (Node.js) or classic (TypeScript pre-1.6)
  • sourceMap: If true, generates corresponding .map file for .js file
  • emitDecoratorMetadata: If true, enables the output JavaScript to create the metadata for the decorators
  • experimentalDecorators: If true, enables experimental support for ES7 decorators
  • lib: Specifies library files to be included in the compilation
  • noImplicitAny: If true, raise error if we use any type on expressions and declarations

Step 2

Let us add the following code to the package.json file, which holds metadata for npm and contains all the Angular packages and third-party libraries required for Angular application development:

{ 
  "name": "hello-world", 
  "version": "1.0.0", 
  "scripts": { 
    "prestart": "npm run build", 
    "start": "concurrently \"tsc -w\"  \"lite-server\"", 
    "build": "tsc" 
  }, 
  "license": "ISC", 
  "dependencies": { 
    "@angular/common": "^4.0.0", 
    "@angular/compiler": "^4.0.0", 
    "@angular/core": "^4.0.0", 
    "@angular/platform-browser": "^4.0.0", 
    "@angular/platform-browser-dynamic": "^4.0.0", 
    "core-js": "^2.4.1", 
    "rxjs": "^5.1.0", 
    "systemjs": "0.20.12", 
    "zone.js": "^0.8.4" 
  }, 
  "devDependencies": { 
    "@types/node": "^6.0.45", 
    "concurrently": "^3.4.0", 
    "lite-server": "^2.3.0", 
    "typescript": "~2.2.0" 
  } 
} 

In the preceding code snippet, there are two important sections:

  • dependencies: This holds all packages required for application to run
  • devDependencies: This holds all packages required only for development

Once we add the preceding code to the package.json file in our project, we should run the following command at the root of our application:

$ npm install

The preceding command will create the node_modules folder in the root of project, and it downloads all the packages mentioned in the dependencies and devDependencies sections into the node_modules folder.

There is one more section in the package.json file, that is, scripts. We will discuss the scripts section when we are ready to run our application.

Step 4

We have the basic setup ready for our application; now let's write some code by beginning with a module. An Angular module in TypeScript is simply a class annotated it with the @NgModule() decorator.

Add the following code to the app.ts file under the src folder:

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 

@NgModule({ 
  imports: [BrowserModule], 
  declarations: [], 
  bootstrap: [] 
}) 
class HelloWorldAppModule {} 

We imported the NgModule decorator from the @angular/core module and BrowserModule from the @angular/platform-browser module using ES2015 module imports syntax; we will discuss these modules later.

We declared a class and annotated it with the @NgModule() decorator. The @NgModule() decorator takes a configuration object as the parameter with a couple of properties; here is what they mean.

imports

We need to specify the other modules on which our module is dependent. We are going to run our application in a browser, so our module depends on BrowserModule; we imported it and added it to this array.

declarations

We need to specify that the components, directives, and pipes belong to this module.

bootstrap

We need to specify the components that must be bootstrapped when this module is bootstrapped. The components added here will automatically be added to the entryComponents property. The components specified in the entryComponents will be compiled when the module is defined.

 

The @NgModule() is a decorator; the decorator is a function that adds the metadata to class declaratively without modifying its original behavior.

Step 5

In the previous step, we created a module, but the module does not do anything. It is just a container for components; actual logic needs to be written inside a component. Let's write our first component in Angular. An Angular component in TypeScript is simply a class annotated with the @Component() decorator:

@Component({}) 
class HelloWorldAppComponent {} 

The @Component() decorator tells Angular that this class is an Angular component, and we can pass a configuration object to the @Component() function that has two properties - a selector and a template:

@Component({ 
  selector: 'hello-world-app', 
  template: '<h1>Say Hello to Angular</h1>' 
}) 

The selector property specifies a CSS selector (custom tag name) for the component that can be used in HTML.

The template property specifies the HTML template for the component that tells Angular how to render a view. Our template is a single line of HTML Say Hello to Angular surrounded with the h1 tag. We can also specify a multiline template string. Instead of using the inline template, we can use the external template stored in a different file using the templateUrl property.

Let us also add this code to the app.ts file under the src folder:

import { Component } from '@angular/core'; 

@Component({ 
  selector: 'hello-world-app', 
  template: '<h1>Say Hello to Angular</h1>' 
}) 
class HelloWorldAppComponent {} 

Step 6

We have our component ready, and we need to associate this component to a module. Let's add the component to the declarations array of the app module created in Step 4, and we also need this component bootstrapped as soon as a module is bootstrapped, so add this to the bootstrap array also. Let us add all this code to the app.ts file under the src folder:

import { NgModule, Component } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 

@Component({ 
  selector: 'hello-world-app', 
  template: '<h1>Say Hello to Angular</h1>' 
}) 
class HelloWorldAppComponent {} 

@NgModule({ 
  imports: [BrowserModule], 
  declarations: [HelloWorldAppComponent], 
  bootstrap: [HelloWorldAppComponent] 
}) 
class HelloWorldAppModule {} 

 

Step 7

The next step is to bootstrap our module. This can be done using the bootstrapModule() method; it is available in the PlatformRef class. We can get the instance of the PlatformRef class using the platformBrowserDynamic() function available in the @angular/platform-browser-dynamic module:

import { platformBrowserDynamic } from  
                        '@angular/platform-browser-dynamic'; 

platformBrowserDynamic().bootstrapModule(HelloWorldAppModule); 

The app.ts file finally looks as follows after adding the module bootstrapping logic:

import { NgModule, Component } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { platformBrowserDynamic } from  
                        '@angular/platform-browser-dynamic'; 

@Component({ 
  selector: 'hello-world-app', 
  template: '<h1>Say Hello to Angular</h1>' 
}) 
class HelloWorldAppComponent { } 

@NgModule({ 
  imports: [BrowserModule], 
  declarations: [HelloWorldAppComponent], 
  bootstrap: [HelloWorldAppComponent] 
}) 
class HelloWorldAppModule { } 

platformBrowserDynamic().bootstrapModule(HelloWorldAppModule); 

 

Step 8

Let us use the component we created in the earlier step, add following code in index.html:

<html> 
<head> 
  <title>Angular Hello World</title> 
  <meta charset="UTF-8"> 
  <meta name="viewport" content="width=device-width,  
                                        initial-scale=1"> 

  <script src="node_modules/core-js/client/shim.js"></script> 
  <script src="node_modules/zone.js/dist/zone.js"></script> 
  <script src="node_modules/systemjs/dist/system.src.js"></script> 

  <script> 
    System.config({ 
      paths: { 
        'ng:': 'node_modules/@angular/' 
      }, 
      map: { 
        '@angular/core': 'ng:core/bundles/core.umd.js', 
        '@angular/common': 'ng:common/bundles/common.umd.js', 
        '@angular/compiler': 'ng:compiler/bundles/compiler.umd.js', 
        '@angular/platform-browser': 'ng:platform- 
                           browser/bundles/platform-browser.umd.js', 
        '@angular/platform-browser-dynamic': 'ng:platform-browser- 
                    dynamic/bundles/platform-browser-dynamic.umd.js', 
        'rxjs': 'node_modules/rxjs' 
      }, 
      packages: { 
        src: { 
          main: 'app', 
          defaultExtension: 'js' 
        }, 
        rxjs: { defaultExtension: 'js' } 
      } 
    }); 

    System.import('src').catch(function (err) { 
      console.error(err); 
    }); 
  </script> 
</head> 
<body> 
<hello-world-app>Loading...</hello-world-app> 
</body> 
</html> 

There is a lot going on in the index.html; let us understand it step by step.

SystemJS

We included SystemJS and its configuration, so what is SystemJS? SystemJS is a universal dynamic module loader. It can load ES2015, AMD, CommonJS modules, and global scripts in the browser and Node.js.

<script src="node_modules/systemjs/dist/system.src.js"></script> 

<script> 
System.config({}); 
System.import('src'); 
</script> 

Why do we need SystemJS? If we refer back to our previous steps, we imported NgModule, Component from the @angular/core module, BrowserModule from the @angular/platform-browser module, the platformBrowserDynamic function from the @angular/platform-browser-dynamic module. The @angular/core module is a physical JavaScript file available in our application root at the node_modules/@angular/core/bundles/core.umd.js path.

Normally, in order to use anything (variables, functions, objects, and so on) in an external JavaScript file, we need to add it to our HTML using the <script> tag. Instead of using the traditional <script> tag to load our JavaScript files, which is slow and synchronous, we can use the ES2015 modules feature to load our JavaScript files dynamically, asynchronously, and on demand. Module loading can be done using SystemJS, and instead of SystemJS, we can also use other alternatives such as webpack and rollup.

We need to tell the SystemJS how to load modules using its configuration. In SystemJS configuration, map object tells where to look for JavaScript files, packages object tells how to load when no filename is specified and no file extension is specified.

After the configuration, we need inform one more thing to SystemJS that is our main file, which system loads it first and start the execution. This is done using the System.import() method.

In our code, we specified System.import('src'). SystemJS looks for the src folder in configuration; we specified the app.js file is the main file for it. SystemJS will load the app.js file under src and start the execution. Currently, we have only one JavaScript file with all the logic in our application, app.js.

Using the Angular component

In the body tag section, we are using the <hello-world-app> tag, which we declared in our HelloWorldAppComponent, and it will render its view:

<body> 
  <hello-world-app>Loading...</hello-world-app> 
</body> 

 

 

Understanding npm packages

Let us refer to Step 3; in the package.json file dependencies section, we have a lot of packages. We downloaded them, and some of them are loaded using the <script> tag, while some of them are loaded using SystemJS. Some of these packages are part of the Angular framework; some are third-party libraries.

The following are the Angular packages:

  • @angular/core: This package contains critical runtime parts of the angular framework required by every application. It includes all metadata decorators, dependency injection, NgModule, Component, directive, the component life cycle hooks, core providers, links to change detection and Observables.
  • @angular/common: This package contains common directives (ngClass, ngFor, ngIf, ngPlural, ngPluralCase, ngStyle, ngSwitch, ngSwitchCase, ngSwitchDefault, and ngTemplateOutlet), pipes (AsyncPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, JsonPipe, LowerCasePipe, CurrencyPipe, DecimalPipe, PercentPipe, SlicePipe, and UpperCasePipe), and services.
  • @angular/compiler: This package contains logic for the Angular template compiler.
  • @angular/platform-browser: This package contains everything related to DOM and browser.
  • @angular/platform-browser-dynamic: This package contains everything related to bootstrapping our applications during development.

The following are the dependencies:

  • rxjs: This is a reactive extensions library for JavaScript based on Observables, which are used by Angular. JavaScript native does not support them, and there is a proposal for adding them as core language in future versions. However, we need to include RxJS and its mandatory dependency. We are loading it using the SystemJS configuration.
  • zone.js: This library contains all the logic for change detection; there is a proposal for adding them as core language. However, we need to include zone.js and its mandatory dependency. We load it using the <script> tag.

Note

@angular/core package is dependent on rxjs, zone.js.

  • core-js: It is a polyfill for ECMAScript 2015 and the upcoming JavaScript language features. We need this for Angular to work in older IE browsers where ever it is supported, we load it using the <script> tag.

Step 9

Our application is ready, but we wrote our code in TypeScript; it has to be compiled into JavaScript. Once this is done, we need the web server to run our application.

Once again, if we refer to package.json in Step 3 in the devDependencies section, we specified the typescript, lite-server, and concurrently packages. These are downloaded during the npm install execution.

The typescript package contains its compiler; lite-server package is lightweight node-based web server and concurrently package let us run multiple commands concurrently. Now if we check out scripts section, there are three commands:

  "scripts": { 
    "prestart": "npm run build", 
    "start": "concurrently \"tsc -w\"  \"lite-server\"", 
    "build": "tsc" 
  } 

The build command is invoking the TypeScript compiler using the tsc command. The start command is invoking the TypeScript compiler in watch mode, also simultaneously it's running the lite-sever command, which will launch web server. The prestart command is invoked automatically before the start command, and we are simply invoking the build command in it.

We can invoke these commands in the scripts section using npm run <command>; npm predefined commands can run using npm <command>.

Step 10

Finally let's run our first Angular application, run the following command at the root folder of our application:

$ npm start

The preceding command will compile our TypeScript code and launch the web server. The web server will start our application and launch the default browser and will display the Say Hello to Angular message in the browser.

So, what happened? Here are the following steps happened in between once web server launched, we saw the output in the browser.

As soon as a web server loads the index.html page, the browser loads the files specified in scripts tags. Once browser loads the SystemJS, it read its configuration and loads the app.js file (which is compiled from app.ts file). In the app.js file, @angular/core, @angular/platform-browser, @angular/platform-browser-dynamic modules are loaded; they will load their dependent modules.

The platformBrowserDynamic() function bootstraps our HelloWorldAppModule, while bootstrapping HelloWorldAppModule, it will add the HelloWorldAppComponent in the bootstrap property to its entryComponents.

Once the HelloWorldAppComponent is added to entryComponents, Angular will compile it and create a ComponentFactory instance and store it in the ComponentFactoryResolver instance.

Finally, the <hello-world-app> tag in index.html will render the template of HelloWorldAppComponent output.

Note

ES2015 features will be explained whenever they are used in the code.

 

 

 

Using Angular CLI


In the previous section Writing your first Angular application, we learned how to write a hello world application from scratch. To write a simple hello world application, we initially had to create a lot of files with boilerplate code and project configuration. This process is common for both small and large applications.

For large applications, we create a lot of modules, components, services, directives, and pipes with boilerplate code and project configuration. This is a very time-consuming process. Since we want to save time and be productive by focusing on solving business problems instead of spending time on tedious tasks, tooling comes in handy.

The Angular team created a command-line tool know as Angular CLI. The Angular CLI helps us in generating Angular projects with required configurations, boilerplate code, and also downloads the required node packages with one simple command. It also provides commands for generating components, directives, pipes, services, classes, guards, interfaces, enums, modules, modules with routing and building, running and testing the applications locally.

Getting started with Angular CLI

The Angular CLI is available as a node package. First, we need to download and install it with the following command:

$ npm install -g @angular/cli

The preceding command will install Angular CLI, we can then access it anywhere via command line or Terminal. To generate the Angular project using CLI we can use the ng new project-name command.

$ ng new first-ng-cli-project

This command creates a folder named first-ng-cli-project, generates Angular project under it with all the required files and downloads all the node packages. To run the application, we need to navigate to the project folder and run the ng serve command:

$ cd first-ng-cli-project
$ ng serve

The ng serve command compiles and builds the project, and starts the local web server at http://localhost:4200 URL. When we navigate to http://localhost:4200 URL in the browser, we see the following output:

The output is very simple but we generated the entire project, and got it up and running with two simple commands. Here are some more commands to generate different types of files using Angular CLI.

Component

ng g component my-new-component

Directive

ng g directive my-new-directive

Pipe

ng g pipe my-new-pipe

Service

ng g service my-new-service

Module

ng g module my-module

Module with routing

ng g module my-module --routing

 

 

Note

To learn more about Angular CLI visit https://cli.angular.io.

 

Summary


We started this chapter with an introduction to Angular, and some of its new features. Then, we discussed few tools that will help us during our application development. Next, we looked at different language choices available to build Angular applications and also learned TypeScript and its importance. We learned how to set up Angular for development and wrote our first Angular application. Finally we looked at Angular CLI and how it accelerates the project development.

In the next chapter, we will learn how to write components, new directives and new templating syntax in Angular.

About the Author

  • Shravan Kumar Kasagoni

    Shravan Kumar Kasagoni is a developer, gadget freak, technology evangelist, mentor, blogger, and speaker living in Hyderabad. He has been passionate about computers and technology right from childhood. He holds a bachelors degree in computer science and engineering, and he is a Microsoft Certified Professional.

    His expertise includes modern web technologies (HTML5, JavaScript, and Node.js) and frameworks (Angular, React.js, Knockout.js, and so on). He has also worked on many Microsoft technologies, such as ASP.NET MVC, ASP.NET WEB API, WCF, C#, SSRS, and the Microsoft cloud platform Azure.

    He is a core member of Microsoft User Group Hyderabad, where he helps thousands of developers on modern web technologies and Microsoft technologies. He also actively contributes to open source community. He is a regular speaker at local user groups and conferences. Shravan has been awarded Microsoft's prestigious Most Valuable Professional award for past 6 years in a row for his expertise and community contributions in modern web technologies using ASP.NET and open source technologies.

    He is currently working with Novartis India, where he is responsible for the design and development of high-performance modern enterprise web applications and RESTful APIs. Previously, he was associated with Thomson Reuters and Pramati Technologies.

    Browse publications by this author