Lead Image © Ivan Mikhaylov, 123RF.com

Lead Image © Ivan Mikhaylov, 123RF.com

Angular 2 client-side TypeScript framework

Second Brew

Article from ADMIN 38/2017
By
Angular 2 features TypeScript instead of JavaScript, JiT and AoT compilation, and the consistent use of components.

After no fewer than six years of development, the second major release of the Angular client-side JavaScript framework [1] was released in mid-September 2016. The good news: Angular 2 also relies on data bindings to place application data in a browser HTML document using directives (i.e., specifically defined HTML tags). The bad news: Angular 2 is not downwardly compatible, although not so much because of the codebase rewrite under TypeScript [2], but rather because of design decisions made by the Angular team.

In this article, I refer to a sample application (Figure 1) to describe how developers can program apps in Angular 2 with TypeScript. The app is simple: Clicking on Add transfers the two measured values for temperature and pressure from the fields in the form to the table at the bottom of the output window. At the same time, the app calculates the average of the measured values in the line below the Weather Station label.

Figure 1: Users can access the weather station in a browser using the URL http://localhost:3000 or a local IP address.

Quick Launch

First, install version 6 of the Node.js [3] server-side JavaScript implementation on a development machine with Debian 8:

curl -sL https://deb.nodesource.com/ setup_6.x | bash
apt install nodejs git

The first command expands the collection of repositories for Debian's package manager, adding a repository for the current version 6 of Node. Then Apt with root privileges installs Node.js and Git, which you need to install Angular 2.

A quick-start variant of Angular is easily installed on your hard disk with the commands:

git clone https://github.com/angular/ quickstart station
cd station
npm install

The first line uses Git to copy the popular quickstart module into the station project directory, before changing to that directory and installing quickstart using the npm [4] node package manager. The quickstart module provides a working, but quite rudimentary, Angular 2 application out of the box. The listings in this article extend this module to include a small sample app.

Test Run

Listing 1 is an initial overview of what it looks like in the project directory of the completed sample application. The corresponding files are in the v2 folder; you need to copy them to the station folder and overwrite the existing files. For example, the package.json file stores the names and version numbers of the Node.js packages, which the npm install command has already installed.

Listing 1

The station Project Directory

 - station
 |- app
  |- app.component.html
  |- app.component.ts
  |- app.module.ts
  |- weather.ts
  |- main.ts
  |- stack.service.ts
 |- index.html
 |- package.json
 |- systemjs.config.js
 |- node_modules
 |- styles.css
 |- tsconfig.json
 |- typings
 |- typings.json

The app directory primarily contains application-specific files. The app.module.ts file binds the application to an Angular engine, and the tsconfig.json file tells the TypeScript compiler how to produce JavaScript.

Now change to the station directory and launch the development environment with:

npm start

The compiler converts any file with the extension .ts to .js. In some cases, the typings.json [5] file in the directory of the same name contains information on library-specific extensions that the TypeScript compiler cannot find in the same directory.

After the development environment has converted the files, it starts an HTTP server and displays the corresponding URLs at the command line. You can access the weather station by typing the URL localhost:3000 in the browser bar on the development machine (Figure 1). If Angular is running in a virtual machine (VM) or a container, it uses the VM's or container's IP address. The Browsersync test tool is running parallel to this on port 3001 (Figure 2); you can use this to test the web application if needed.

Figure 2: Use Browsersync to test your Angular 2 app in the browser.

Ahead of Its Time

The web browser first uses index.html (Listing 2) to access the application. The systemjs.config.js file (line 8) defines additional packages for the application. Internally, Angular uses a compiler that converts the application code into an interactive DOM tree. It generates a so-called view source just in time (JiT) in the browser (Figure 3), although in principle, you can use its ahead of time (AoT) compiler [6] to create the view source on the web server. The use of AoT is not recommended for production environments.

Listing 2

index.html

01 <html>
02   <head>
03     <title>Weather Station</title>
04     <script src="node_modules/core-js/client/shim.min.js"></script>
05     <script src="node_modules/zone.js/dist/zone.js"></script>
06     <script src="node_modules/reflect-metadata/Reflect.js"></script>
07     <script src="node_modules/systemjs/dist/system.src.js"></script>
08     <script src="systemjs.config.js"></script>
09     <script>
10       System.import('app').catch(function(err){ console.error(err); });
11     </script>
12     <link rel="stylesheet" href="styles.css">
13   </head>
14   <body>
15     <myApp>Load ...</myApp>
16   </body>
17 </html>
Figure 3: The AoT compiler (bottom) generates the view source on the server and the JiT compiler (top) only in the browser. The arrows describe the conversion steps.

This method saves computing time in production operations in which users can retrieve the application from the web server multiple times. If you believe the creators of Angular 2, an application with the JiT compiler initializes almost four times faster than when using Angular 1 [7].

The embedded CSS file styles.css stores formatting information in CSS3. A watch process keeps an eye on the project directory, and – for every change – automatically compiles the .ts files and reloads the app in the browser.

Listing 2 shows the index.html file from the weather station project. The application uses the original version of the quickstart module almost unchanged. Lines 4 to 8 embed the required JavaScript resources, line 10 launches the app by calling the app/main.js file, and line 12 includes the style sheet. A handler discussed later handles the user-defined directive myApp in line 15. It replaces myApp with an HTML fragment from the template in Listing 3. The template resides in the app/app.component.html file and uses special tags (directives, e.g., as in line 3), to pull application data from the component.

Listing 3

app/app.component.html

01 <div id="station">
02   <h1>Weather Station</h1>
03   <div id="avg">Average: {{avg('temp')}} °C and {{avg('press')}} mbar</div>
04   <form>
05     <input type="number" [(ngModel)]="model.temp" name="temp" required step="0.1" size="30" placeholder="°C">
06     <input type="number" [(ngModel)]="model.press" name="press" required size="30" placeholder="mbar">
07     <button (click)="add()" value="add">Add</button>
08   </form>
09   <table>
10   <tr>
11     <th>Date</th>
12     <th>Temperature</th>
13     <th>Pressure</th>
14   </tr>
15   <tr *ngFor="let data of datas">
16     <td>{{data.date | date:'dd.MM.yyyy HH:mm'}}</td>
17     <td>{{data.temp}}</td>
18     <td>{{data.press}}</td>
19     </tr>
20   </table>
21 </div>

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy ADMIN Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

comments powered by Disqus