Angular2 – Developing your Applications with Modern JS and Tools (Series)

by
Tags: , ,
Category:

What's Angular 2?

Hmm, let's see. The next generation of the Angular JavaScript Framework. A typed JavaScript framework. A framework that does away with the cyclical $scope and digest cycle tap dance. A framework that uses Reactive JavaScript to handle asynchronous streams of data.

That's a lot. But bottom line, it's a framework that is taking forever to get here, but will have huge payoffs once it lands. We are at the point where the final series of alpha releases are landing (as of this article, v39), and features are starting to work. As Brad Green stated on an open discussion from the Angular Remote Conference this month, the goal now is to document the project and reduce any boilerplate code. So now is the time to start getting acquainted.

So, really, what's Angular 2?

Another way to look at Angular 2 is that it's a modular, fast JavaScript framework for developing applications. Here are some key features:

Modules

The Angular development team takes advantage of the emerging ECMAScript 2015 standard (for sake of sanity, we'll call it ES6) JavaScript language changes to write their code using ES6's modules, classes, arrow functions and a bevy of other things.

Fast UI updates

The first huge change to Angular 2 is that the team has done away with the $scope object, and with traditional controllers. Everything is a component, with properties (state) and methods (behaviors/events). Components can include other components in their templates, be injected with services (which are mostly just JavaScript objects also injected with other objects).

State updates now begin with the root of the Directed Acyclic Graph (DAG) and walk it one time. There are no more cycles. No more repeated runs of the digester. If you make a change, process the tree. If you make another change, process it again. Quickly.

Finally, in addition to supporting native ES6 promises (part of the language) the Angular2 team is embracing RxJs – the Reactive Extensions for JavaScript by Microsoft. The native objects are beginning to work as observable objects, and interested parties can subscribe to the data coming back and get multiple updates. So if you are comfortable with Promises in Angular 1, you'll want to convert that knowledge over to Observables from RxJs in Angular 2.

Almost everything is a component

Yep, in fact, a Directive is a specialized component without an attached template. Since that's rather rare, you won't be building a ton of those.

Forget Filters, welcome to Pipes

Mostly the same thing. We'll discuss what the benefits are of Pipes -vs- the prior API in a later post.

Angular Forms are different

We now have two ways to build up our forms – using directives as before, or using a model-based API where we build the form programmatically. We'll have a special series of blog posts devoted to these.

The new template syntax

This will start by hurting your head – it will start to feel normal though. A typical Angular1 expression for a loop looks like this:

<div class="list-group">
  <li ng-repeat="for task in taskService.tasks">
    {{ task.dueDate | date:'short'}}
    {{ task.cost | currency }}
    {{ task.description }}
     <input type="checkbox"
      ng-model="task.complete"
      ng-click="toggleComplete($event)">
  </li>
</div>

Now, in Angular2, it looks like this (actually there are several variants, I'm cutting
to the chase until we can write up a good blog article about it):

<div class="list-group">
    <li *ng-for="#task of taskService.tasks"
        [task]="task">
        {{ task.dueDate | date:'short'}}
        {{ task.cost | currency }}
        {{ task.description }}
        <input type="checkbox"
            ng-control="task.complete"
            (click)="toggleComplete()">
    </li>
</div>

Besides spitting out your coffee, remember to reserve judgment. There is a good reason the team did what they did to your clean syntax. First of all, the *ng-for keyword has a * in it as shorthand for make a variable named task. the longer form is:

ng-for='var task of taskService.tasks'

And so therefore is more verbose. Next, Angular2 makes you more responsible for what kind of binding you're specifying. So we have these in the example above:

  • [task]="task" – this says that there will be an incoming property for each task and we'll call it task in the template. That is a property binding
  • ng-control="task.complete" – ah, a Directive. By that I mean a component that does direct DOM and model updates for you. More on this later, but it sets up for validation of form elements once we get to the forms post.
  • (click)="toggleComplete()" – this is an event binding – it will call the function in the component when the checkbox is clicked.

Of course, we also have your typical Angular expressions, and the filters, er, pipes, in use above. It's pretty much at feature parity with Angular 1, but then it goes further – for example, pipes can be asynchronous and update the model when they are processed, and you can unbundle two-way bindings as we did above or even go for something like Angular1's two-way data binding with ng-model. Again, we'll wait for the blog post for those details…

Explicit mounting of dependency components

Remember in Angular 1 when you wanted to load a module and refer to its objects in your own module? You just added the whole module to the array at the end of the angular.module function like this:

angular.module('myGreatModule', ['ngAnimate'])

Thereafter, if anything in your app wanted to use a directive, it could, just by using it in the template. But now, we have to declare whether we want the parser to pay attention to any given directives. This is both good and bad. Bad, for new developers are going to cheat and use large arrays like the built-in CORE_DIRECTIVES and FORMS_DIRECTIVES arrays, but good as if you only use ng-for you can just mount that one and save some time.

But I'm getting ahead of myself. Before I show you some Angular2 code, we need to learn about how to practically build Angular2 applications. And that's where the story isn't yet completely well-told. Until now…

Flavors of Angular and JavaScript development

Your browser will not support all of ES6 (and never TypeScript natively, except perhaps for the Edge browser) for some time. Most browsers implement ES5 and a pinch, dash, or semi-avalache of ES6 features. See the Kangax site for where your favorite browser, server or runtime stacks up. Therefore, you don't absolutely need to write your code in ES6. In fact, the Angular team will let you write your code in at least six flavors:

  • ES5 (current browser APIs) using an all-in-one Angular script called angular2.sfx.js
  • ES5 (current browser APIs) using shims to support ES6 features, and a module loader such as AMD or JSPM / SystemJS
  • ES6, transpiled down to ES5, with browser shims and a module loader
  • TypeScript, which adds type safety and annotations to ES6, transpiled down to ES5, with browser shims and a module loader
  • TypeScript or ES6 natively (when a browser that supports it exists in the wild)
  • Dart, as the Angular 2 team generates a suite of Dart libraries for Angular

WHAT??? Can't I just pick one?

Yes. You can. In fact, you want to pick one and stick with it, because you'll be writing a lot of code in Angular 2. What I've learned in the short time I've spent with it (and having worked with Angular 1.x) is that when it comes out, it's worth the wait.

In the 2015 ng-conf conference, Google and Microsoft got up on stage and spoke about the future of AngularJS was going to run right through TypeScript. They are ditching their own tanspiler work in Traceur in favor of using TypeScript and submitting some of their features (annotations, for example) to the ECMAScript committee for ES2016 (nee ES7)…

My recommendation at this point, for enterprise teams, is that you learn at least how to write in the TypeScript way first, and then later, learn both the ES5 and ES6 ways without typescript. Why? Knowing how TypeScript transpiles will help you figure out your code when things go awry, but also give you some pivot points for why to choose one toolchain over the other.

For a brand new Angular2 project, I'd say stick with TypeScript, but nail down the toolchain early on.

Why Am I telling you all of this stuff?

Because you need a lot of background to prepare for Angular2.

So, this series of blog posts will start with a thorough introduction to the Angular2 build system for TypeScript, and show you a simple demo. Then we'll move systematically through the major features of Angular2 as a tour. Along the way, I'll provide a github repo or two to demonstrate the features and to give you a seed to start your exploration. Keep in mind that the Angular team is planning on delivering their own project seeds soon, so once they exist and become stable, some of the things we're doing here might change. But check back frequently over the fall and winter of 2015/16. It's going to be a wild ride.

Next up — The relationship between TypeScript, ES6, and ES5