JavaScript Articles

Angular 2 Programming Languages

Programming Languages for Angular Development

Angular 2 differs from Angular JS in regards to programming language support. With Angular JS you generally program in JavaScript. With Angular 2 the official site provides example code in several languages; JavaScript, TypeScript and Dart.

JavaScript is an implementation of the ECMAScript standard. Several versions exist including ES5 and ES6. Most current browsers fully support JavaScript ES5. This means that code compliant with ES5 will run on most most browsers without modification. ES6 on the other hand may not be supported and is typically converted to ES5 before it gets to the browser. The more recent version of JavaScript (ES6) adds features and makes certain tasks easier. It is not clear when browsers will be fully ES6 compliant.

TypeScript and Dart are language super sets of JavaScript. This means they include all the features of JavaScript but add many helpful features as well. But just like the ES6 version of JavaScript they don’t work on current browsers. To work around this limitation there are utilities to convert code written in their non-browser-compliant syntax back to JavaScript ES5. In this way they provide the developer with advanced features and still allow code to be run on existing browsers. The process of converting code from one language to another is referred to as ‘transpilation’. Technically this conversion is performed by a language pre-processor that, although it does not compile anything, is commonly referred to as a compiler.

TypeScript is an open source language that is developed and maintained by Microsoft. It provides type safety, advanced object oriented features, and simplified module loading. Angular 2 itself is built using TypeScript. The documentation support is better on the Angular 2 site for TypeScript than it is for the other options. So although you could write your Angular 2 apps in pure ES5 JavaScript you may find it more difficult and find less support if you get into trouble than if you bite the bullet and spends some time learning TypeScript.

Dart is another alternative for programming Angular 2 applications. It is similar in features to TypeScript and has its own loyal following. If your team is already versed in Dart and is looking to start developing in Angular 2 it could be a good choice. That being said,  in the rest of this post, we will be concentrating on TypeScript.

Code Example

A basic Angular 2 component coded in TypeScript:

import { Component } from '@angular/core';
@Component({
selector: 'hello-app',
template: '<h1>Hello Angular 2</h1>'
})
export class AppComponent { }

 

The same component coded in JavaScript ES5:

(function(app) {
app.AppComponent = ng.core.Component({
selector: 'hello-app',
template: '<h1>Hello Angular 2</h1>'
})
.Class({
constructor: function() {}
});
})(window.app || (window.app = {}));

 As you can see the TypeScript version is more concise and easy to read.

 

TypeScript Usage Basics

TypeScript support is provided by the Node.js ‘typescript’ package. To use typescript you first need to load Node.js and the Node Package Manager (npm). Once Node.js is installed on you system you would use the following command to install TypeScript support:

npm install -g typescript

This will install the TypeScript compiler and allow you to run it from the command line using the following command:

tsc

There are generally three methods to execute tsc. The first method involves passing the name of the TypeScript code file you want compiled on the command line:

tsc filename.ts

Here’s a simple TypeScript code file:

// app.ts
var msg:string = "Hello Typescript!";
function getMessage(message: string){
return message;
}
console.log(getMessage(msg));

Compiling this file produces a JavaScript file with the same name as the TypeScript file but with an extension of “.js”.

tsc app.ts
(produces app.js)

You can test the file by running it using Node.js like this:

node app.js

As your application gets more complex and you have multiple *.ts files in one or more directories you may want to take advantage of the second method of running tsc. To do this you will first need to set up a tsconfig.json config file. Among other things this file tells tsc which directories contain the files you wish to compile. After placing this file in the root of your project tsc will compile any *.ts files it finds whenever they are modified and saved. To use this method you launch tsc in a terminal window and then edit your *.ts files in any text editor. As you save your files they will automatically be converted to JavaScript.

The third method involves using a text editor plugin to determine when you have saved a *.ts file. When that happens the editor itself will call tsc to perform the conversion. This kind of plugin is available for the Atom text editor. Microsoft Visual Studio also includes this type of support. For those who don’t want to load the complete Visual Studio development system Microsoft’s Visual Studio Core text editor also includes TypeScript support.

Conclusion

Using TypeScript significantly simplifies the code you need to write when creating Angular 2 applications. Although TypeScript can’t be executed by browsers directly there are several ways to convert TypeScript into code that browsers can work with.

No Comments

New Support for ECMAScript 2015

Although it is a huge part of the modern web, the syntax of JavaScript hasn’t really changed significantly in quite a long time. That all changed though last June, when ‘ECMAScript 2015’ was released.  This major update contained some significant changes and new features.  Now that more JavaScript engines and environments support the new specification it is a good time to get familiar with these changes.

Besides browsers adding more support for ECMAScript 2015, also call ECMAScript 6 or just “ES 6”, several of the popular JavaScript platforms are adding support as well.  Node.js 4 & 5 support a majority of ES 6, as does AngularJS 2.0.  Of course, like any major version upgrade of such a fundamental web technology, there will be a gradual migration.  We will see a lot of the same things happen with JavaScript that happened with HTML5 and CSS 3, both of which are now “mainstream” and enjoy much broader support.

One thing we’ve learned at Web Age is you can’t wait for “100% support in 100% of environments” to learn about or even begin to adopt a new technology.  It is important to learn about such major upgrades now so that you are aware what is different and look for places where a new version of a technology might be leveraged.

For those looking to keep up with these major changes to JavaScript introduced in ECMAScript 2015, we have a few resources.  The primary one is a new one-day course that focuses on the changes introduced with ECMAScript 2015.  We chose to release a class focused only on the changes since there are lots of people that have JavaScript skills and just need to learn about the changes.  You can find that course here:

WA2488 JavaScript Changes with ECMAScript 2015

We also are going to have a webinar this week that will provide a very quick overview of the changes.  This webinar will cover the main differences with the new ECMAScript 2015 specification and the impact on how JavaScript code can be written.  In particular, focus will be paid on how various ways to leverage the new version while also considering backwards compatibility.  You can register for that webinar here:

WEBINAR: Changes in ECMAScript 2015

As with all new and emerging technologies, we at Web Age look forward to keeping you up to date on what is happening and helping you learn about these technologies to expand the scope of your development skills!

No Comments

Netflix in Flames

Recently I came across this blog post. The title sounded quite intriguing and when reading it, I found some points of interest that I will summarize and present at the end of my blog post.
Read the rest of this entry »

No Comments

A Simple jQuery Image Rotater

Recently I was looking to add a collection of rotating images to my website, so I searched for an image rotater using jQuery. I found a number of very sophisticated libraries designed to rotate images, create slideshows and display fancy transitions. Any one of these would have met my needs. What I did not find was a simple bare-bonesjQuery example that I could use on my web site and enhance as I saw fit. So, I decided to build one form scratch. This example is simple enough that anyone with any jQuery experience at all can understand it. Hopefully, the explanation is clear enough that anyone can incorporate it into their own web site or use it as a starting point to learn jQuery.

Because this this blog is built on a framework that already uses jQuery, the image rotater can’t be directly embedded in this post. You can access an example by clicking on the image or at http://www.dchung.com/test/rotate.

Read the rest of this entry »

No Comments

Getting ‘Closure’

I have been a Java developer since 1995, before that I worked in C++. So my language background is primarily statically-typed and object oriented. In the last several years, I’ve been involved in a number of projects that use JavaScript. I’ve come to recognize that JavaScript is a very powerful language in its own right — but it is dramatically different from the languages that I am used to. One of the features of JavaScript that was a mystery to me is closure.

Closure has no direct equivalent in my native language Java so it took a great deal of reading and experimentation for me to come to grips with this concept. The simplest description I can give is this.

In a closure a variable declared in an outer function is visible to an inner function even if the inner function’s lifecycle is longer than that of the outer function.

Here is an example using the Apache Cordova (PhoneGap) API. The phone Cordova API allows you to package HTML5/CSS/JavaScript applications natively for a number of mobile platforms. It also provides a JavaScript API to wrap many of the native device features like the accelerometer. This example shows a closure.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function startWatch() {

  var previousReading = { x: null, y: null, z: null };

  navigator.accelerometer.watchAcceleration(

    function (acceleration) {
      // use previousReading value here
    },
    onError,
    { frequency: 500 }
 );

}

In this example the startWatch() function declares a variable previousReading and sets its x, y and z members to null. The three values will be used to represent acceleration in meters per second squared. The function then calls navigator.accelerometer.watchAcceleration(), passing in an anonymous callback for success. The anonymous callback defined on line 7 in the source code will be called at a rate of once every 500ms and it will compare the current acceleration with previousReading then update previousReading with the current acceleration.

The code is relatively straightforward except for one important detail previousReading was declared in the scope of the outer function startWatch. But the anonymous inner function (on line 7) will be called repeatedly even after the outer function is out of scope! What happens here is that the inner function keeps a reference to any values in the outer scope that it will need when it is invoked.

For those of you who are Java programmers, don’t think you are immune from this discussion. Closures are on the proposed feature list for JDK 8.

1 Comment