Please move, here comes Angular 2
Development | Dino Repac

Please move, here comes Angular 2

Wednesday, Aug 3, 2016 • 5 min read
With it's successful predecessor, no wonder Angular 2 has raised the hype to a completely new level. In this post we'll talk about Angular 2 in general, focusing on the new features.

AngularJS framework was a huge success, and it changed the way we build our applications. Google continued to put a lot of effort into developing the ultimate Single Page Application (SPA) framework. Angular 2 is being built by the same people who built the first version, and they are bringing all their hard-earned knowledge with them.

If you are using AngularJS as your UI framework, be prepared, Angular 2 delivers a substantial change. No more plain old JavaScript - say hi to Typescript. Well, Angular 2 can be written in JavaScript, Typescript, and Dart, but sympathy mostly goes to Typescript as it is the language Angular 2 was written in. Although it does eventually compile to plain JavaScript, Typescript is a powerful language that lets you build things that would otherwise take time and time to do. What you’re actually doing with Angular 2 is writing templates in Typescript. Angular 2 then turns that templates into code that’s highly optimized for today’s JavaScript virtual machines, says the Angular 2 team, but more on that later.

Say bye to $scope and controllers

Angular 2 is entirely component based; there are no $scopes or controllers. Instead, you are writing small chunks of code that are later connected to form one big application. Those small chunks of code are components - below you can see an example of one. The component is defined by the @Component decorator, and each one has its own custom selector (HTML tag), template (or template URL for external template), directives, providers, and pipes (which we’ll talk about later). Each component also has its own class called component class. In order to use (import) it somewhere else, we have to export it.

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

@Component({
    selector: 'my-custom-component',
    //templateUrl: 'my-custom.component.html';
    template: `<p>Hello reader!</p>`,
    directives: [],
    providers:  [],
    pipes:      []
})

export class CustomComponent{
    //do something
}

As for the naming convention, each component name ends with Component, and the name of the file that holds it with .component. All the files are in kebab-case, so no worries about case sensitivity. Applied to the example component above, the file name would look like this: my-custom.component.ts.

You will need components for almost everything, from basic UI elements to complex routing. As mentioned before, all components will have to be connected to form an application. This means each Angular 2 application will have a root component, and through that, it will form a tree of components. The example of a root component is shown below.

Component tree

What about directives?

Directives are still present. As a matter of fact, each time you create a new component, you also create a new Directive. Yes, you read that correctly. Components are Directives with a template. A @Component decorator is a @Directive decorator extended with template-oriented features.

In Angular 2, two other kinds of directives exist. These are attribute directives and structural directives.

Attribute directives are the ones that change the appearance or behavior of an element they are applied to. These directives are specified by their selector using square brackets (read more about attribute directives here).

Structural directives are here to add, remove, and replace elements in DOM. If you used AngularJS, you have seen them or used them plenty of times. Like in AngularJS, ng-if and ng-repeat exist in Angular 2 too, but are slightly changed. Structural directives now start with a “*"(*ngFor, *ngIf). If you see that in an HTML code, that is a structural directive (read more about structural directives here).

Template features

Angular 2 brings a set of refurbished template features. We are talking about bootstrapping, data and event binding and filtering (or should I call it “the piping”).

All bindings can be grouped into three categories by the data flow direction.

Data binding Data binding. Source

So for example, if you ever wanted a click event in Angular 2, it should look like this:

<button (click)="DoSomething()">Do something</button>

What is also new is that there is no bootstrap directive. What we are doing instead is calling the bootstrap function and passing in the root application component. By convention, root component is called “AppComponent”.

import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';

bootstrap(AppComponent);

There are more things that are different; I tried to cover the most significant changes. If you want to see what else has changed, check the official quick reference page.

Filters are now Pipes

The not-so-significant change happened with Filters, or now - pipes. Angular 2 pipes, similar to AngularJS filters, provide formatting and transformation for data in the template. They are called pipes because they uses the pipe character - “|.” Much of it is the same as AngularJS and also fairly easy to write.

The services!

At this moment, you probably have a clear picture of how Angular 2 application looks like - many components bound together. However, there’s one thing missing - services.

Service is a standard class. It remains like that up until we register it with an Angular injector. Right here we scratched the surface of dependency injection in Angular 2. Dependency Injection (or just DI) is a vital design pattern, and Angular 2 couldn’t be built without it. We won’t talk about DI here, but rather about how Angular 2 utilizes its own injector. During the bootstrap process, an application-wide injector is created, but we have to configure it by adding providers. Following the best practices, providers are registered inside Components that use them.

Services are not components!

Services are specific for their @Injectable() decorator. It marks a class as available to an injector for instantiation. For example, we have a service like this:

import { Injectable } from 'angular2/core';
import { FakeData } from 'fake-data';

@Injectable()
export class MyService{

    getFakeData(){
        return FakeData;
     }
}

Service, as is, is doing nothing. We have to inject it into a component, where all the functionality provided by the service will be used (notice the word provided).

import { Component } from '@angular/core';
import { MyService } from 'my-service';

@Component({
  selector: 'my-component',
  template: `
    {{fakeData | json}}
  `,
  directives: [],
  providers: [MyService]
})

export class MyComponent {
    constructor(service: MyService) { }

    fakeData = this.service.getFakeData();
}

Inside @Component, we see a special property called providers, where we register our dependencies - our service. Since the injector injected the instance of MyService into a component, all we have to do now is ask for it. We do that by assigning it as a constructor parameter and voilà! That’s it. Now you can freely use methods provided by the service inside your component class.

In Angular 2, services are often used to fetch the data from the server. While doing so they use HTTP client that is built in Angular 2. There was a slight twist in how the data can be fetched. Just as AngularJS use promises, Angular 2 uses promises, but wait… Angular 2 new favorite way of getting data is via Observables! Now, observables are great. They are a part of Reactive Extensions. If you haven’t seen them yet, it’s time to learn more. But what’s the difference between promises and observables? Observables are lazy - meaning you have to subscribe to them in order to trigger their behavior and you can also cancel your request thanks to disposability. Ben Lesh compared them in this great video which is worth watching.

Conclusion

Currently, Angular 2 is in release candidate 4 (RC4). Over the past few releases, we witnessed major changes to the entire framework. Angular 2 RC5 has been announced recently, but what will the final product look like? No one knows. For now, at this stage of development, Angular 2 shows its potential to become a leading UI framework. No wonder it has raised so much hype.