Angular 2 Demystified

Angular-2

23/06/2015 • Software • Views: 550

As I mentioned in my recent blog post Angular 2 is a complete rewrite. Many concepts that are known from Angular 1.x are gone or changed dramatically. Angular 2 looks like a completely different framework: no controllers*, no DDO, no $scope, no angular.module and completely rewritten binding and change detection (no ng-model).

Although Angular 2 is still work in progress many new features have already been revealed. In this blog post I will share some basic concepts of the framework via code samples that I presented during my lecture at InfoShare 2015.

Please note the code is created with the most recent version of Angular 2 (Angular 2 Alpha 26 as of time of writing this article).

Angular 2 is built with… TypeScript (1.5)

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

We could say it is ECMAScript 6 on steroids, as it offers what ECMAScript 6 has to offer. But it adds many more features: type checking, interfaces, generics, enums or decorators to name just a few.

Let’s see some sample code created in TypeScript:

1

TypeScript is optional for Angular 2 applications and although it is a recommended approach, developers have choice. They can choose from: ES5, ES6, CoffeScript or any other language that compiles to JavaScript.

Want to learn more about TypeScript? Visit http://www.typescriptlang.org/

Hello, World!

Let’s see two “Hello, World!” Angular 2 applications written in TypeScript and ECMAScript 5 accordingly.

TypeScript (1.5):

2

JavaScript (ES5):

3

As you can see the TypeScript version is a bit less verbose and decorators (@) clearly separate the code from meta data information.

Angular 2 Building Blocks

As you could notice, the the above code did not contain much of what you learned about Angular 1.x: no angular.module, no Directive Definition Object (DDO), no $scope.

Component

A component is the main UI building block of Angular 2 app: Angular 2 is a tree of components. Every Angular 2 application must have at least one component. A component class is an execution context for the template or it is a component controller. A component requires a single @Component decorator and at least one @View decorator.

Let’s see a really basic component in Angular 2:

4

HelloAngular2Cmp has two properties: text and clickCount that are bound to a view defined by a template attribute of a @View decorator. Templates have access to any properties or functions of a component controller.

View

The template itself looks like this:

rafal_code

The syntax is very easy:

  • {{ expression | pipe }} – Angular 2 interpolation,
  • #variable – local variables available in the scope of the component. The variable can be later referred in the component’s template,
  • (event) – binding to events of element or directive,
  • [property] – binding to properties of element.

Bindings

Every time the text property of a component changes, the change is automatically reflected in the template. The properties of elements are accessed with square brackets ([property]) syntax. In the above example the button will be disabled once the text property of a component is equal to “Angular 2”. This is a property binding in Angular 2.

Angular 2 Property Binding

To propagate changes from DOM to a component event binding must be utilized. Event bindings in Angular 2 are represented by brackets syntax: (event). In the above example when a click event occurs on a button, onClick function of a component will be executed.

Angular 2 Property and Event Binding

To sum up, in Angular 2:

Property bindings are executed automatically, Event bindings allow propagation of DOM changes.

Watch this video to better understand the data binding in Angular 2: https://angularu.com/Video/2015sf/misko-hevery-talks-about-databinding-in-angular-2

Forms

Property and event bindings makes two two-way data binding possiblebut an additional effort is required in order to achieve it. Fortunately, Angular 2 will be shipped with Angular 2 Forms module. This module will be used for handling user input, by defining and building a control objects and mapping them onto the DOM. Control objects can then be used to read information from the form elements.

Read more about Angular 2 Forms: http://angularjs.blogspot.com/2015/03/forms-in-angular-2.html

Directive

A component is not the only UI building block in Angular 2. There are also directives which allow you to attach behavior to elements in the DOM.

The difference between a component and a directive in Angular 2 is that a component is a directive with a view whereas a directive is a decorator with no view.

A directive requires a single @Directive decorator and a directive class:

5

The above directive, when used on an element, adds an outline effect to the host element – the element it is used on. ElementRef is automatically provided by Angular 2 Dependency Injection module.

Usage example:

6

Dependency Injection

In Angular 2 there is a single way to inject dependencies into a directive or a component. In the below example a user-defined service is injected into a component. MessageService declares some business logic:

7

The component is requesting framework to provide a required dependency via its constructor:

8

The MessageService is imported from an external module and later it must be made available to Angular 2. One way to make dependencies available is to register them globally with a bootstrap() function like the one below:

9

Please note that framework services, directives or components, an iterable live list of components (@Query) and attributes (@Attribute) can be injected in the same, uniform way. The new DI module is designed the way it supports easy extending (DependencyAnnotation) so even custom dependency injection annotation can be created. In addition, Angular 2 supports injecting promises (@InjectPromise), lazy dependencies (@InjectLazy) or optional dependencies (@Optional).

Read more about Angular 2 Dependency Injection in this great article: http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html

Summary

As you can see Angular 2 is much different from Angular 1.x. No DDO, no $scope, no angular.module, new change detection and binding, uniform template syntax, new dependency injection, new forms module, new router and much more.

The new version of the framework should also be much simpler to learn thanks to easier and more concise concepts like component-based architecture. Moreover, Angular 2 should be significantly faster than its ancestor thanks to completely rewritten data binding and change detection.

Is there a way to migrate from Angular 1.x? In my opinion it will not be easy. But there are some tips out there that may help in migration:

  • Prefer one-way data-bindings to two-way data-bindings,
  • Use ControllerAs syntax for easier migration to components,
  • Do not update application state inside watch functions,
  • Follow the newest releases (1.4, 1.5) and upgrade,
  • Think of using New Router (1.5) (https://angular.github.io/router/),
  • Think of using TypeScript in Angular 1.x applications.

References

IT professional, open source enthusiast, certified Java developer, team leader. Follow me on twiiter: kolorobot

Related Post

  • Skandar De Anaya

    I want to use Ecmascript aka Javascript. Not Microsoft (proprietary) Typescript, I know is open source but is controlled by Microsoft. I’m so disappointing of Angular 2 with all the decisions and drastically changes. I guess I will be moving into other frameworks as Ember.js or using libs as knockout.js and backbone.js

  • Skandar De Anaya

    Also I know I can use ES5 or ES6 for develop but the framework is built with Typescript, remember that we need sometimes to tweak or check source code to understand the framework and that is using Typescript. but is not also that is drastically changes trying to be a React.js clone, really I see many wrong decisions with Angular2, looks like child playground trying new things and see what happens.

  • Rene Dev

    I currently don’t know neither Angular 1.x or Angular 2.x, I just need a suggestion from someone whose being using Angular for a while, should I wait till Angular 2.x comes out? since it seems there is a dramatic change from version 1.x to version 2 I think it’d be wise to just wait till Angular 2.x comes out, what do you Angular experts suggest?

    By the way, thank you for this valuable post.

  • http://blog.codeleak.pl Rafał Borowiec

    Thanks for your comment.

    I think TypeScript is not a problem since Angular2 code will be completely written in TypeScript. I think that was a good choice of Angular2 team: TypeScript instead of AtScript. In fact, TypeScript is currently used by many developers doing Angular1 apps with quite some success. More and more people find the language good enough for their projects.

    Deciding today about using or not using the framework is too early in my opinion. Angular team is experimenting with many things at this moment and therefore some concepts are not yet clear or fully known. From my perspective, Angular2 looks much more simpler than Angular1: easier concepts, easier to understand, easier to scale.

    On the higher level, I don’t miss anything in Angular2. But of course we need to wait for more stable releases to see how it can be used in a real cases.

  • http://blog.codeleak.pl Rafał Borowiec

    Thanks for the comment.

    For new projects you need to go with Angular1. Angular2 release data is unknown and in my opinion it will be changing. In addtion, I expect first release will not be stable enough to be used in production – we will need to wait for some maintenance releases.

    BTW. I don’t know Angular2 release date.End of 2015 in my opinion is not realistic.

  • http://blog.codeleak.pl Rafał Borowiec

    1. Taking what is good from other frameworks (like reactjs or ember) is good thing in my opinion. It is better than reinventing the wheel. Example from Oracle: when they decided to introduce Lambda expressions in Java 8 they said they will use C# syntax because it is just good. I like the approach.

    2. Playing around with things and experimenting is very good in my opinion. I prefere experimenting before the release instead of experimenting after the release. The possible drawback of the approach is that it may take more time to bring a stable release. And meantime more people can switch to ember or reactjs.

  • Skandar De Anaya

    Thanks for your reply Rafal.

    I agree that Typescript is much better than atscript. but I think people is missing the point with javascript.

    With Typescript feels really we are bringing all Java/C# monster to the Client side. The annotations will be abused and it will be soup of that. Its funny but I find more simple and understandable ES5 or ES6 code than the typescript maybe less noise, with typescript we are all over again designing classes, defining types and verbosity. (ES6 have classes but I see them as optional).

    I’m a C# and Java developer and those are good on the server side but What Im saying is Typescript is trying to do that bring all the idiosyncrasy of those platforms to the client side and I feel that’s a wrong approach.

    I’m happy with Angular1. It is an awesome and simple framework to work on the client. but after Angular2 Im so skeptical about it. for some people will be good for others not.

    Also you are right still to early to decide today.

  • Skandar De Anaya

    1. I agree with you but I feel Angular2 is trying to re invent the wheel instead to contribute to react.js
    2.I agree too but so they should play around whats best for them and then when they really have a plan post it to the community. How they handle Angular2 announcements have been a disaster that many people is confused about it.

  • http://blog.codeleak.pl Rafał Borowiec

    1. That would be cool! On the other hand, what I understand from Angular announcements and design docs is that Angular2 will have modules (e.g. DI, Router) that will be easier to use as libraries. So using what is best from Angular2 with reactjs should be possible. But again, who knows…
    2. Totally true!

  • http://blog.codeleak.pl Rafał Borowiec

    I think the point about JS is that it is going the direction no one expected in the past. The apps on the client are just way too complex. This has an impact on future maintenance that with JS is harder then with languages like C#, Java or even TypeScript.

    Of course, this is just a simplification. In Java, bad programmer, can created similar mess as bad programmer in JS.

    Anyways, thanks for your comments and valuable feedback!

  • Skandar De Anaya

    I think I jumped straight to suggestions but I want to say that your article is the one with more clear information about Angular2, Thank you.