Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn
Jose Ruiz
PHP Backend Developer and other stuff in Portal team
Contributions by octavio izaguirre
Posted on May 6th 2016

Update:  Since this blog was first published, Genuitec has released an Angular IDE with advanced support for both TypeScript and Angular 2. 

Resources

Angular is a JavaScript framework used to create and maintain single-page web applications. It all began in 2009 when Misko Hevery was working on the Google Feedback project. He found it daunting to maintain 17,000 lines of code, and suggested to use his Angular framework (created with Adam Abrons). The result was 1,500 lines of code—10 time less!!

In May 2014, the Angular team announced they were working on Angular 2. Improvements included:

  • Framework for mobile apps
  • Use of ECMAScript 6 (compatible with ES5)
  • Faster change detection
  • Instrumented
  • Modular
  • Dependency injection
  • Templating and directives
  • Touch animations
  • Router
  • Persistence

The web evolved so much in the years since Angular’s inception, this new version was necessary to make the framework modern again. However, to include all these features, they needed to start from scratch. This requires a whole new learning process for the Angular developer, something many developers don’t like.

This article focuses on Angular 2 (now available as a release candidate). While many developers are impatiently waiting for the final version, others don’t want to know about Angular at all. Read this article to learn more, and then pick your side.

Main Features in Angular 2

There are three main improvements with Angular 2.

  • Speed—Angular computes updates based on changes to data, not DOM, for fast updates that scale to the largest data sets with minimal memory overhead.
  • Mobile—Mobile development was lacking with version 1. Angular 2 solves the main problem with mobile web development.
  • Flexible—Supports several languages, including plain JavaScript, TypeScript, and Dart. Also supports both object-style data structure with POJO data-binding, and functional reactive style with unidirectional data flow and support for observables and immutable data structures.

Building Blocks

Now that you are more familiar with Angular, I’m going to explain the main building blocks of an Angular app architecture. Attached to this article you can find an application of a simple todo list performed in Angular 2 with TypeScript.

TodoListScreen
Todo list sample project

You can follow along in the project as the code is explained below.

The Module

An application in Angular is generally organized in a modular structure. A typical module is a block of code dedicated to a single purpose. Modules are optional, but highly recommended to structure and organize code. In general, a module exports a component class, this is one of the basic Angular blocks, a component class is a thing we export from a module.

Most applications have an AppComponent. By convention, I named mine app.component.ts. Inside this file is an export sentence that tells TypeScript that this is a module whose AppComponent class is public and is accessible from other modules in the application.

In the next example, we have a class named TodoAppComponent in the file named todo_app.component.ts.

Angular2Code1
todo_app.component.ts

To reference TodoAppComponent, import the class as follows.

Angular2Code2

The import sentence tells the system that it can get TodoAppComponent from a module named todo_app.component located in a specific directory.

Import modules from the Angular Library in a similar way, except you don’t need to specify a path, only the bare module name.

Angular2Code3

In brief, we can say that Angular applications are composed of modules that export things that other modules import. It is best practice to write our applications as a modules collection each one exporting something.

The Component

A component controls a patch of the real state screen, usually called a view. In our example, the layout of root application with links, the tasks list, and the form to add a new task are all views controlled by components. Angular creates, updates and destroys components as the user moves through the application and the developer can take action at each moment in this lifecycle through optional lifecycle hooks.

Below, we can see the code of the component that controls the view of new tasks form.

Angular2Code4
todo_form.component.ts

Here an event is emitted with the input value captured from the form to be inserted in the todo list.

The Template

The view of a component is defined with its respective template. A template is a block of HTML code that tells Angular how to render the component. At first sight it seems just basic HTML, but gets interesting once you notice the special Angular code and tags. Below we can see the template of the component class form previously shown.

Angular2Code5
todo_form.component.html

Notice not only the familiar labels <form> and <input>, but also unfamiliar items like (ngSubmit) and [(ngModel)]. In this example you can see how you can comfortably mix Angular labels and HTML without a problem.

Metadata

The metadata tells Angular how to process a class. We include metadata in the TodoFormComponent class to tell Angular that this is a component.

Angular2Code6
todo_form.component.ts

@Component tells Angular that the class immediately below is a component class. This decorator takes a configuration object with the information necessary so Angular can create the component and the view.

Some possible settings are:

  • selector:—a css selector that tells Angular to insert an instance of the component where it finds the label <todo-form> in the parent HTML.
    Angular2Code7
  • template:—the template location path of the component or we could put the HTML code instead.
  • directives:—a components array that this template requires.
  • providers:—an array of dependency injection providers. This is one way to tell Angular that our component’s constructor requires a service so it can get some data from service to show in the view.

The @component function transforms the configuration object in metadata to bind it to the component class definition. The component, template and metadata describe together the view.

Data Binding

If we don’t use a framework, we have to keep the variables up to date with the fields in our form (or vice versa). This can be a tedious task in which errors can be easily made and detecting them can be very difficult. If you have used jQuery before, you can understand this issue.

Angular supports data binding that allows coordinating parts of the template with parts of the component. There are four forms of data binding syntax and each one has a direction, from the DOM, to the DOM, and both directions.

AngularDataBinding

In our example todo list app, we include the four kinds of syntax in different parts of the code. In the following example, you can see four lines of code that demonstrate each of the forms.

Angular2Code8

In the first line, as part of the class name and inside the label <span>, the interpolation shows the component property values todo.done and todo.text respectively. In this case the direction is from the component to the DOM.

In the second line, in the same way, from the component to the view, the [todos] property binding passes the “todos” value from the parent component to the todos property of the child component.

In the third line, the (newTask) event binding calls the addTask($event) method of the component. The newTask event is a customized event declared in the child component todo_form.component.ts and the addTask() is a method declared in the parent component.

In the fourth line we can see a two-way data binding that combines property and event binding in a single notation using the ngModel directive. With the property binding a data property value flows to the input box from the component and with the event binding the user changes the value in the component with the value entered in the input box.

The Directive

A directive is a class with directive metadata. In TypeScript we used the @directive decorator to attach metadata to class. We have already known a directive class that is the component. There are two other types: structural and attribute directives. Most of the time these appear inside element tags as attributes, sometimes by its name, but regularly as the target of an assignment or a binding.

Structural directives modify the DOM by adding, removing or replacing elements. For example to show in the view the list of created tasks, we use *ngFor to tell Angular to show each todo contained in the todo list.

Angular2Code9

The attribute directives alter the look or behavior of an existing element, and are named such because they look like regular HTML. For example, see the ngModel directive in following code.

Angular2Code10

These directives alter the behavior of an element, generating an event that modifies the task value in the component or modifies the content of the input if the task value is modified from the component.

The Service

A typical service is a class with a well-defined purpose to do specific things. Although Angular does not specifically have classes that define a service as a ServiceBase class, these are fundamental in any Angular application.

The Angular components are heavy consumers of services and depend on them to manage most tasks. The components don’t validate data that the user introduces or consult data from the server, they delegate these tasks to services that are usually generated from the server side. The services are available to components through dependency injection.

Dependency Injection

Dependency injection is a way to supply a new instance of a class with dependencies it requires. Angular uses dependency injection to provide a new component with the services it needs. When Angular creates a component, the first thing it does is examine the types of the constructor parameters to know what services the component needs. When a service instance is unavailable in the container, the injector can create the instance and add it to the container before returning the service to Angular.

Previously we must have registered a provider with the Injector. A provider is something that can create or return a service, typically the service class itself.

Angular2Code11

Attachments

todolist.zip—Sample project

Let Us Hear from You!

We are interested in your opinion. Do you see the value in Angular 2? Want us to write more about it? If you have any comments or questions, we would love to hear from you @Webclipse on twitter or via the Webclipse forum.

If you haven’t already subscribed to our blog posts, why not take a moment to subscribe to receive notification of future posts?