Angular2 series – Routing

This post is part of a series of posts about Angular2. You can find them all in the introduction: http://julienrenaux.fr/2015/11/30/angular2-series-introduction/


Before we start and to make sure we are in line on the terminology, I will use the name AngularJS to define AngularJS 1.x and Angular2 to define AngularJS 2.x.

All the following code examples are part of a boilerplate I created. It is available on GitHub: https://github.com/shprink/angular2-nobullshit-boilerplate.


If you are used to AngularJS applications you have probably used the ui-router instead of the Angular basic router (ngRoute). The ui-router is more popular because it has more features (such as nested views) and was adopted by big projects such as Ionic Framework.

The Angular2 router is a complete rewrite of the old ngRoute module. It was created keeping the ui-router use cased in mind, but also Angular2 components based architecture (a concept not yet adopted with AngularJS).

If you want to know more details about the Router history I recommend watching this video (beware the API changed a little bit since this video):

If you want to know more about components in Angular2 I suggest you to read this previous article of mine: Angular2 series – Component, Directive, Pipe and Service.

Path location strategies

Using AngularJS

With the ui-router in AngularJS you have the choice between two modes. The default one, aka the Hash mode (#products/id) that is not interpreted by servers or the HTML5 mode (/products/id).

One or the other can be selected using the $locationProvider

$locationProvider.html5Mode(true);

Notice: This HTML5 mode requires your web server to be configured.

Using Angular2

In Angular2 we have the same “modes” but they are called PathLocationStrategy and HashLocationStrategy.

PathLocationStrategy

PathLocationStrategy is the default strategy used by the new router. It is equivalent to the HTML5 mode in AngularJS.

If you want to use this strategy, you must define the APP_BASE_HREF to a string representing the URL prefix that should be preserved when switching pages.

import {ROUTER_PROVIDERS, APP_BASE_HREF} from 'angular2/router';

bootstrap(yourApp, [
  ROUTER_PROVIDERS, // includes binding to PathLocationStrategy
  provide(APP_BASE_HREF, {useValue: '/my/prefix/here'})
]);

If you have problems understanding the above example, learn how to create an application with Angular2 first by reading: Angular2 series – Component, Directive, Pipe and Service.

If you do not want any prefix to be kept you can set APP_BASE_HREF to be:

provide(APP_BASE_HREF, {useValue: '/'})

Official docs

HashLocationStrategy

HashLocationStrategy is the strategy equivalent to the default strategy in AngularJS ui-router. This strategy is used to configure the Location service to represent its state with the hash fragment of the browser’s URL.

import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';
bootstrap(yourApp, [
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy})
]);

Official docs

Define Routes

Using AngularJS

In AngularJS and ui-router here is how to define states (or Routes) during the configuration phase:

$stateProvider.state('home', {
    url: '/',
    templateUrl: 'home.html',
    controller: 'HomeCtrl'
}).state('about', {
    url: '/about',
    templateUrl: 'about.html',
    controller: 'AboutCtrl'
})

Using Angular2

In Angular2 a state is created from a Route class. Using the @RouteConfig annotation you can create your application route definition.

@RouteConfig takes as first argument an Array of Route that have the following properties:

  • path equivalent to url in ui-router states
  • component a component type.
  • name is an optional CamelCase string representing the name of the route.
  • data is an optional property of any type representing arbitrary route metadata for the given route (we talk about it in the Passing data between routes section)

With that in mind let’s create an equivalent of the routes we created in the AngularJS version:

import {RouteConfig, Route} from 'angular2/router';
import {MyComponentHome, MyComponentAbout} from './myComponents';
@Component({
    selector: "app"
})
@RouteConfig([
    new Route({ path: '/', component: MyComponentHome, name: 'Home' }),
    new Route({ path: '/about', component: MyComponentAbout, name: 'About' })
])
export class App {...}

Template update

We have now defined our Routes, the next step is to define where to display the components when switching pages.

Using AngularJS

In AngularJS and ui-router we can use the ui-view directive to insert dynamic content from each state:

<body>
    <ui-view>
        <i>Some content will load here!</i>
    </ui-view>
</body>

Using Angular2

Using Angular2, it is similar, only the name of the directive change!

First we need to import the RouterOutlet directive and inject it into our App component, then we can use it in our template.

import {RouterOutlet} from 'angular2/router';
@Component({
    selector: "app"
})
@View({
    directives: [RouterOutlet]
    template: `
      <router-outlet></router-outlet>
    `
})

Now any location change will load a different component inside the RouterOutlet directive.

Navigate between pages

Using AngularJS

To navigate between pages (or states) in AngularJS and the ui-router we can use the ui-sref directive.

<a ui-sref="home">Home page</a>
<a ui-sref="about">About page</a>

Using Angular2

With Angular2 we can use the RouterLink directive instead.

This directive needs to be injected in your component first:

import {RouterLink} from 'angular2/router';
@Component({
  selector: "menu",
  directives: [RouterLink],
  template: `
     <a [routerLink]="['./Home']">Home page</a>
     <a [routerLink]="['./About']">About page</a>
  `
})
export class Menu {...}

Please note that [routerLink] uses the Route name that we defined earlier in the

Passing data between routes

Using AngularJS

In AngularJS we could defined URL parameters in state definitions:

$stateProvider.state('product.item', {
    url: '/product/:id',
    templateUrl: 'item.html',
    controller: 'ItemCtrl'
})

To pass the id from a state to another we have two choices. We can use the ui-sref directive or the $state service:

<a ui-sref="product.item({id: 4})">Go to item 4</a>
function($state) {
    // Go to item 4
    $state.go('product.item', {id: 4});
}

Then getting this data in our controller is easy using the $stateParams service:

function($stateParams) {
    var id = $stateParams.id;
}

BEWARE: The concept of params (passing data between states but without using URL parameters) in the ui-router does not exist in Angular2 (see my question on stackoverflow). A similar concept exist though and it is called data.

Using Angular2

Similar to AngularJS, we can define URL parameters using path from the Route class:

@RouteConfig([
    new Route({ 
        path: '/product/:id', 
        component: MyProductItemComponent, 
        name: 'ProductItem'
    })
])
export class App {...}

To pass the id from a Route to another we also have two choices. We can use the routerLink directive or the Router service.

In a template:

<a [routerLink]="['./ProductItem', {id: 4}]">Go to item 4</a>

In a Component:

import {Router} from 'angular2/router';
class {
  constructor(private _router: Router) {
    this._router.navigate( ['./ProductItem', { id: 4 }] );
  }
}

Then getting this data in a Component is easy using the RouteParams service:

import {RouteParams} from 'angular2/router';
class {
  id: number;
  constructor(private _params: RouteParams) {
    this.id = _params.get('id');
  }
}

Official docs

You can also retrieve data from a Route using RouteData service. I think this feature would not be used often (I probably will not use it on my applications) but it is good to know that it exists:

@RouteConfig([
    new Route({ 
        path: '/product/:id', 
        component: MyProductItemComponent, 
        name: 'ProductItem',
        data: {
            isAdmin: true
        }
    })
])
export class App {...}

You can now retrieve the isAdmin flag or any other Route metadata in your Components using the RouteData service:

class {
  isAdmin: boolean;
  constructor(private _data: RouteData) {
    this.isAdmin = _data.get('isAdmin');
  }
}

Official docs


Thanks for reading, you can interact about this post by leaving a comment here, or directly on Twitter and Facebook!

Angular2 series – Component, Directive, Pipe and Service

This post is part of a series of posts about Angular2. You can find them all in the introduction: http://julienrenaux.fr/2015/11/30/angular2-series-introduction/


Before we start and to make sure we are in line on the terminology, I will use the name AngularJS to define AngularJS 1.x and Angular2 to define AngularJS 2.x.

Component

A component is what you used to call a directive in AngularJS. It contains a template, styles, a list of injectables (directives, services) and a selector.

Official docs

Let’s create a component that lists the US Democratic Party presidential candidates.

import {Component, View, NgFor} from 'angular2/angular2';

@Component({
    selector: "navbar",
    directives: [NgFor], 
    styles: [`
        li{
          color: gray;
        }
    `],
    template: `
        <h2>Democratic Party presidential candidates</h2>
        <ul>
            <li *ngFor="#item of items; #i = index">{{item}} {{i}}</li>
        </ul>
    `
})
export class Navbar {
    items: Array<String>

    constructor() {
      this.items = [
        "Hillary Clinton",
        "Martin O'Malley",
        "Bernie Sanders"
      ]
    }

    ngOnInit() {
        console.log('[Component] navbar ngOnInit');
    }
}

When a component is instantiated, Angular2 creates a shadow DOM for the component (Shadow DOM provides encapsulation for the JavaScript, CSS, and templating in a Web Component). Then, the template and styles are injected inside it.

Learn a bit more about Web component and specifically about the <template> tag by reading the previous article of this series of posts: Angular2 series – Template Syntax.

You can now use your component by inserting it into your html page:

<navbar></navbar>

Demo

Screen Shot 2015-12-12 at 19.32.27

http://embed.plnkr.co/cUCWoUDRzd31YRRbo5Rg/preview

Lifecycle hooks

In the previous example, we used the ngOnInit Class method to dump a message [Component] navbar ngOnInit in the console. It is called only when the component is initiated. It exists several hooks that make your life easier when it comes to plug yourself in between component life phases.

  • ngOnChanges (if any bindings have changed)
  • ngOnInit (after the first check only)
  • ngOnDestroy (at the very end before destruction) Implement this interface to get notified when any data-bound property of your directive changes
  • ngDoCheck
  • ngAfterContentInit
  • ngAfterContentChecked
  • ngAfterViewInit
  • ngAfterViewChecked

Official docs


Directive

Directives allow you to attach behaviour to elements in the DOM. It is also what you used to call a directive in AngularJS, but without a proper view. You can therefore place as many directives as you want on one DOM-element. This is not possible with components.

Official docs

Let’s get back to our previous component and this time, let’s make our presidential candidates red. To do so, we are going to create the redify directive:

import {Directive, ElementRef, Renderer} from 'angular2/angular2';

@Directive({
  selector: '[redify]'
})
export class Redify {
  constructor(private _element: ElementRef, private renderer: Renderer) {
      renderer.setElementStyle(_element, 'color', 'red');
  }
}

Notice that in order to obtain a reference to our Presidential Candidate element we injected _element: ElementRef.

Official docs for ElementRef

To modify the element style we injected renderer: Renderer, which is a service that gives you methods to manipulate the style of a particular element.

Official docs for Renderer

Then we can add the redify directive to our component:

import {Redify} from 'path/to/your/Redify/directive';

@Component({
    selector: "navbar",
    directives: [NgFor, Redify], 
    ...
    template: `
        <li redify *ngFor="#item of items; #i = index">{{item}} {{i}}</li>
    `
})

Result

Screen Shot 2015-12-12 at 19.28.28

http://embed.plnkr.co/iJiZVqixM0qAo4RMelB7/preview


Pipe

A pipe in Angular2 is the equivalent of filters in AngularJS. As in AngularJS, pipes can be stateless (pure functions, not reevaluated) or stateful (has dependencies that can modify the output).

A better explanation of what is a pipe is available in the previous article of this series of posts: Angular2 series – Template Syntax

Official docs

Let’s get back again to our previous component and this time, let’s create a pipe to transform our presidential candidates last name to uppercase.

First we create lastnameUppercase pipe:

import {Pipe} from 'angular2/angular2';

@Pipe({
  name: 'lastnameUppercase'
})
export class LastnameUppercase {
  transform(v, args) {
    return `${v.split(' ')[0]} ${v.split(' ')[1].toUpperCase()}`;
  }
}

Then let’s add this pipe to our navbar component in order to consume it.

import {LastnameUppercase} from './pipes';
@Component({
    selector: "navbar",
    ...
    pipes: [LastnameUppercase],
    template: `
        <li redify *ngFor="#item of items; #i = index">{{item | lastnameUppercase}} {{i}}</li>
    `
})

Demo

Screen Shot 2015-12-12 at 19.37.13

http://embed.plnkr.co/L1ERY1Pn6qmGl0B1hi0K/preview

Built in pipes

In Angular2 you have access to the following pipes for free:

  • currency
  • date
  • uppercase
  • json
  • limitTo
  • lowercase
  • async
  • decimal
  • percent

Service

Now that we saw how to create a component, a directive and a pipe, we are going to clean up our code and separate the data retrieval (the presidential candidates) into a service.

Official docs

import {Injectable} from 'angular2/angular2';

@Injectable()
export class PresidentialCandidate {

    constructor() {}

    getRepublicainList() {
        return [
        "Donald Trump",
        "Rand Paul",
        "Ben Carson"
      ]
    }

    getDemocraticList() {
        return [
        "Hillary Clinton",
        "Martin O'Malley",
        "Bernie Sanders"
      ]
    }
}

Now let’s consume this service on our navbar component:

import {PresidentialCandidate} from './services';

@Component({
    selector: "navbar",
    providers: [PresidentialCandidate],
    ...
    template: `
        <h2>Democratic Party presidential candidates</h2>
        <ul>
        <li redify *ngFor="#item of democrats; #i = index">{{item | lastnameUppercase}} {{i}}</li>
        </ul>
        <h2>Republican Party presidential candidates</h2>
        <ul>
        <li redify *ngFor="#item of republicans; #i = index">{{item | lastnameUppercase}} {{i}}</li>
        </ul>
    `
})
export class Navbar {
    democrats: Array<String>
    republicans: Array<String>

    constructor(private presidentialService :PresidentialCandidate) {
      this.democrats = presidentialService.getDemocraticList(); 
      this.republicans = presidentialService.getRepublicainList();
    }
}

We have decoupled the presidential candidates retrieval with the component that displays them. It is now easier for other components to consume this data.

Demo

Screen Shot 2015-12-12 at 19.40.57

http://embed.plnkr.co/z1B96b4OX7BHwkT0492G/preview


Application

AngularJS

With AngularJS an application was a simple module. It had no difference from any other module of your application.

angular.module('yourApp', []);

Angular2

With Angular2, it is similar. An application is a simple component as any other component of your application. It is just the root component that basically contains the scaffolding of your page.

@Component({
    selector: "yourApp"
})
@View({
    directives: [Header, Navbar, Content, Footer]
    template: `
      <header></header>
      <navbar></navbar>
      <content></content>
      <footer></footer>
    `
})
export class App {
  constructor() {
   
  }
}

Header, Navbar, Content and Footer are custom components, they do not exist within Angular2 core.

Bootstrap

Now that you know how to create components and a root component (or app), you need to bootstrap the application.

AngularJS

In AngularJS you could use angular.bootstrap(document, ['yourApp']); or the ng-app directive <body ng-app="yourApp">.

Angular2

In Angular2 it is very similar.

import {bootstrap} from 'angular2/angular2';
import {yourApp} from 'path/to/your/app/component';

bootstrap(yourApp, []);

Our application is now ready to be rendered. Insert your app component in your index.html file and reload the browser, your app is ready!

<body>
    <app>
        Loading...
    </app>
</body>

Thanks for reading, you can interact about this post by leaving a comment here, or directly on Twitter and Facebook!

Angular2 series – Template Syntax

This post is part of a series of posts about Angular2. You can find them all in the introduction: http://julienrenaux.fr/2015/11/30/angular2-series-introduction/


Before we start and to make sure we are in line on the terminology, I will use the name AngularJS to define AngularJS 1.x and Angular2 to define AngularJS 2.x.

To understand the code blocks in that Angular2 series of posts, we need to learn a bit about the new Angular2 template syntax.

Be careful, as of alpha52 core directives syntax changes from kebab case to camel case. Example: ng-if becomes ngIf. For more information read the migration docs

Bind property

AngularJS

With AngularJS, binding a given expression to a property value requires to use either a core directive such as ng-value or use AngularJS markup {{}}.

ng-value is expecting an AngularJS expression, whose value will be bound to the value attribute of the input element:

<input ng-value="firstName" />

But you could also use it that way:

<input value="{{firstName}}" />

Angular2

With Angular2 it is similar, without the need to use a specific directive. Only the new syntax is necessary [value] and it is not limited to value, you can use it to bind anything to any particular element property:

<input [value]="firstName" [placeholder]="firstNamePlaceholder" />

Exactly like AngularJS you can use the following:

<input value="{{firstName}}" placeholder="{{firstNamePlaceholder}}" />

Event

AngularJS

With AngularJS we need to use special directives to listen to events. The most famous being ng-click. Ng-click listen to the onClick event. Here is the list of all the HMTL5 events that you can normally listen to: http://www.w3schools.com/tags/ref_eventattributes.asp

Most of the HTML5 events are covered by AngularJS directives such as ng-blur, ng-change, ng-focus, ng-keyup etc.

<button ng-click="doSomething($event)">

Angular2

With Angular2 you can listen to any HTML5 native element event using this special syntax: (eventName)

<button (click)="doSomething($event)">

Two-way data binding

Angular2 also has a two-way data binding in place but do not use the famous and decried “digest cycle” of AngularJS. Instead, Angular2 uses zone.js.

A zone is an execution context that persists across async tasks.

If you want to make sense out of this sentence I suggest you watch this talk by Brian Ford:

Basically zone.js gives Angular2 a low level foundation that let it instrument the browser and let it know when asynch operations are finished.

That way, you can combine event and bind property syntaxes that we saw before:

<input type="text" [value]="firstName" (input)="firstName=$event.target.value" />

That being said, ngModel can be used as a simplified version of what we have above:

<input type="text" [(ngModel)]="firstName" />

The result is identical.

Pro tip: you can also run anything outside the Angular2 zone using the NgZone service. The most common use of this service is to optimize performance when starting a work consisting of one (or more) asynchronous task that does not require UI updates.


Local variable

A local template variable is a vehicle for moving data across element lines. As far as I know, there is no equivalent of local variable in AngularJS. A local variable # can be a pointer to an object or an DOM element.

<video #movieplayer ...>
  <button (click)="movieplayer.play()">
</video>

In the above example, having the movieplayer allows us to manipulate the video HTML5 api on the same element, its siblings or its children.

Pro tip: # is the canonical version of the local variable. You can also use it with var-. In our movieplayer case we could have var-movieplayer instead of #movieplayer.


* symbol

This is probably the most disturbing syntax choice of the new Angular2 syntax. It is actually pretty simple to understand what it does if you have a little background on what the template tag is.

template tag

The template tag allows you to declare a piece of DOM that can be instantiated after run time. It guaranties better performance and the usage of a resource only when needed.

Here is an example to be clearer:

<div style="display:none">
  <img src="path/to/your/image.png" />
</div>

As you can see, the image will not be displayed because of display:none on its parent. The problem is that the browser will prefetch this image whether you use it or not. It is a waste of resource and can impact your page performance.

The solution to this very problem is to use the template tag!

<template>
  <img src="path/to/your/image.png" />
</template>

The image in the above example will not be fetch by the browser until we instantiate the template.

Let’s get back to the * symbol now. Using it on a element will turn it into an embedded template:

<hero-detail *ngIf="isActive" [hero]="currentHero"></hero-detail>

The following will be transformed as:

<template [ngIf]="isActive">
  <hero-detail [hero]="currentHero"></hero-detail>
</template>

Now that I explained what the template tag is for, it is easy to understand that the * symbol is used by conditional directives such as ngFor, ngIf, and ngSwitch. Indeed, <hero-detail> component does not need to be instantiated until isActive is true.


Pipe

A pipe in Angular2 is the equivalent of filters in AngularJS. As in AngularJS, pipes can be stateless (pure functions, not reevaluated) or stateful (has dependencies that can modify the output).

Stateful

In Angular2, most built-in pipes are stateless, it is the case with DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe.

You can use them that way:

<p>My birthday is {{ birthday | date:"MM/dd/yy" }} </p>

and even chain them (same as AngularJS):

{{ birthday | date | uppercase}}

Stateful

The Async pipe is a built-in stateful pipe. It can receive a Promise or Observable as input and subscribe to the input automatically, eventually returning the emitted value(s).

@Component({
  selector: 'my-hero',
  template: 'Message: {{delayedMessage | async}}',
})
class MyHeroAsyncMessageComponent {
  delayedMessage:Promise<string> = new Promise((resolve, reject) => {
    setTimeout(() => resolve('You are my Hero!'), 500);
  });
}

Here, <my-hero> component will display Message: You are my Hero! only once the delayedMessage promise is resolved.


Elvis operator

In JavaScript, you often end up checking the existence of object properties. For instance I am sure you have written that kind of conditions before:

if (cordova && cordova.plugins && cordova.plugins.notification){
  // use cordova.plugins.notification
}

All of this to avoid such an error TypeError: Cannot read property 'notification' of undefined.

Pro tip: you can simplify it using lodash _.get function. The previous example could be written that way:

if (_.get(cordova, 'plugins.notification')){
  // use cordova.plugins.notification
}

Even if plugins is not defined _.get will return undefined.

The Elvis operator (?) in Angular2 fixes that very problem but in the template side.

<p>Employer: {{employer?.companyName}}</p>

Here the employer field is optional and if undefined, the rest of the expression should be ignored. Without the Elvis operator here you will get a TypeError.

It also works with long property path: a?.b?.c?.d


Thanks for reading, you can interact about this post by leaving a comment here, or directly on Twitter and Facebook!