Upgrading from 1.x

This guide is still in the process of being updated to RC5 and it's samples may not work correctly.

Having an existing Angular 1 application doesn't mean that we can't begin enjoying everything Angular 2 has to offer. That's because Angular 2 comes with built-in tools for migrating Angular 1 projects over to the Angular 2 platform.

Some applications will be easier to upgrade than others, and there are ways in which we can make it easier for ourselves. It is possible to prepare and align Angular 1 applications with Angular 2 even before beginning the upgrade process. These preparation steps are all about making the code more decoupled, more maintainable, and up to speed with modern development tools. That means the preparation work will not only make the eventual upgrade easier, but will also generally improve our Angular 1 applications.

One of the keys to a successful upgrade is to do it incrementally, by running the two frameworks side by side in the same application, and porting Angular 1 components to Angular 2 one by one. This makes it possible to upgrade even large and complex applications without disrupting other business, because the work can be done collaboratively and spread over a period of time. The upgrade module in Angular 2 has been designed to make incremental upgrading seamless.

  1. Preparation
    1. Following The Angular Style Guide
    2. Using a Module Loader
    3. Migrating to TypeScript
    4. Using Component Directives
  2. Upgrading with The Upgrade Adapter
    1. How The Upgrade Adapter Works
    2. Bootstrapping Hybrid Angular 1+2 Applications
    3. Using Angular 2 Components from Angular 1 Code
    4. Using Angular 1 Component Directives from Angular 2 Code
    5. Projecting Angular 1 Content into Angular 2 Components
    6. Transcluding Angular 2 Content into Angular 1 Component Directives
    7. Making Angular 1 Dependencies Injectable to Angular 2
    8. Making Angular 2 Dependencies Injectable to Angular 1
  3. PhoneCat Upgrade Tutorial
    1. Switching to TypeScript
    2. Installing Angular 2
    3. Bootstrapping A Hybrid 1+2 PhoneCat
    4. Upgrading the Phone service
    5. Upgrading Components
    6. Switching To The Angular 2 Router And Bootstrap
    7. Saying Goodbye to Angular 1
  4. Appendix: Upgrading PhoneCat Tests

Preparation

There are many ways to structure Angular 1 applications. When we begin to upgrade these applications to Angular 2, some will turn out to be much more easy to work with than others. There are a few key techniques and patterns that we can apply to future proof our apps even before we begin the migration.

Following The Angular Style Guide

The Angular 1 Style Guide collects patterns and practices that have been proven to result in cleaner and more maintainable Angular 1 applications. It contains a wealth of information about how to write and organize Angular code - and equally importantly - how not to write and organize Angular code.

Angular 2 is a reimagined version of the best parts of Angular 1. In that sense, its goals are the same as the Angular Style Guide's: To preserve the good parts of Angular 1, and to avoid the bad parts. There's a lot more to Angular 2 than just that of course, but this does mean that following the style guide helps make your Angular 1 app more closely aligned with Angular 2.

There are a few rules in particular that will make it much easier to do an incremental upgrade using the Angular 2 upgrade module:

  • The Rule of 1 states that there should be one component per file. This not only makes components easy to navigate and find, but will also allow us to migrate them between languages and frameworks one at a time. In this example application, each controller, component, service, and filter is in its own source file.
  • The Folders-by-Feature Structure and Modularity rules define similar principles on a higher level of abstraction: Different parts of the application should reside in different directories and Angular modules.

When an application is laid out feature per feature in this way, it can also be migrated one feature at a time. For applications that don't already look like this, applying the rules in the Angular style guide is a highly recommended preparation step. And this is not just for the sake of the upgrade - it is just solid advice in general!

Using a Module Loader

When we break application code down into one component per file, we often end up with a project structure with a large number of relatively small files. This is a much neater way to organize things than a small number of large files, but it doesn't work that well if you have to load all those files to the HTML page with <script> tags. Especially when you also have to maintain those tags in the correct order. That's why it's a good idea to start using a module loader.

Using a module loader such as SystemJS, Webpack, or Browserify allows us to use the built-in module systems of the TypeScript or ES2015 languages in our apps. We can use the import and export features that explicitly specify what code can and will be shared between different parts of the application. For ES5 applications we can use CommonJS style require and module.exports features. In both cases, the module loader will then take care of loading all the code the application needs in the correct order.

When we then take our applications into production, module loaders also make it easier to package them all up into production bundles with batteries included.

Migrating to TypeScript

If part of our Angular 2 upgrade plan is to also take TypeScript into use, it makes sense to bring in the TypeScript compiler even before the upgrade itself begins. This means there's one less thing to learn and think about during the actual upgrade. It also means we can start using TypeScript features in our Angular 1 code.

Since TypeScript is a superset of ECMAScript 2015, which in turn is a superset of ECMAScript 5, "switching" to TypeScript doesn't necessarily require anything more than installing the TypeScript compiler and switching renaming files from *.js to *.ts. But just doing that is not hugely useful or exciting, of course. Additional steps like the following can give us much more bang for the buck:

  • For applications that use a module loader, TypeScript imports and exports (which are really ECMAScript 2015 imports and exports) can be used to organize code into modules.
  • Type annotations can be gradually added to existing functions and variables to pin down their types and get benefits like build-time error checking, great autocompletion support and inline documentation.
  • JavaScript features new to ES2015, like arrow functions, lets and consts, default function parameters, and destructuring assignments can also be gradually added to make the code more expressive.
  • Services and controllers can be turned into classes. That way they'll be a step closer to becoming Angular 2 service and component classes, which will make our life easier once we do the upgrade.

Using Component Directives

In Angular 2, components are the main primitive from which user interfaces are built. We define the different parts of our UIs as components, and then compose the UI by using components in our templates.

You can also do this in Angular 1, using component directives. These are directives that define their own templates, controllers, and input/output bindings - the same things that Angular 2 components define. Applications built with component directives are much easier to migrate to Angular 2 than applications built with lower-level features like ng-controller, ng-include, and scope inheritance.

To be Angular 2 compatible, an Angular 1 component directive should configure these attributes:

  • restrict: 'E'. Components are usually used as elements.
  • scope: {} - an isolate scope. In Angular 2, components are always isolated from their surroundings, and we should do this in Angular 1 too.
  • bindToController: {}. Component inputs and outputs should be bound to the controller instead of using the $scope.
  • controller and controllerAs. Components have their own controllers.
  • template or templateUrl. Components have their own templates.

Component directives may also use the following attributes:

  • transclude: true, if the component needs to transclude content from elsewhere.
  • require, if the component needs to communicate with some parent component's controller.

Component directives may not use the following attributes:

  • compile. This will not be supported in Angular 2.
  • replace: true. Angular 2 never replaces a component element with the component template. This attribute is also deprecated in Angular 1.
  • priority and terminal. While Angular 1 components may use these, they are not used in Angular 2 and it is better not to write code that relies on them.

An Angular 1 component directive that is fully aligned with the Angular 2 architecture may look something like this:

export function heroDetailDirective() {
  return {
    restrict: 'E',
    scope: {},
    bindToController: {
      hero: '=',
      deleted: '&'
    },
    template: `
      <h2>{{ctrl.hero.name}} details!</h2>
      <div><label>id: </label>{{ctrl.hero.id}}</div>
      <button ng-click="ctrl.onDelete()">Delete</button>
    `,
    controller: function() {
      this.onDelete = () => {
        this.deleted({hero: this.hero});
      };
    },
    controllerAs: 'ctrl'
  };
}

Angular 1.5 introduces the component API that makes it easier to define directives like these. It is a good idea to use this API for component directives for several reasons:

  • It requires less boilerplate code.
  • It enforces the use of component best practices like controllerAs.
  • It has good default values for directive attributes like scope and restrict.

The component directive example from above looks like this when expressed using the component API:

export const heroDetail = {
  bindings: {
    hero: '<',
    deleted: '&'
  },
  template: `
    <h2>{{$ctrl.hero.name}} details!</h2>
    <div><label>id: </label>{{$ctrl.hero.id}}</div>
    <button ng-click="$ctrl.onDelete()">Delete</button>
  `,
  controller: function() {
    this.onDelete = () => {
      this.deleted(this.hero);
    };
  }
};

Controller lifecycle hook methods $onInit(), $onDestroy(), and $onChanges() are another convenient feature that Angular 1.5 introduces. They all have nearly exact equivalents in Angular 2, so organizing component lifecycle logic around them will ease the eventual Angular 2 upgrade process.

Upgrading with The Upgrade Adapter

The upgrade module in Angular 2 is a very useful tool for upgrading anything but the smallest of applications. With it we can mix and match Angular 1 and 2 components in the same application and have them interoperate seamlessly. That means we don't have to do the upgrade work all at once, since there's a natural coexistence between the two frameworks during the transition period.

How The Upgrade Adapter Works

The primary tool provided by the upgrade module is called the UpgradeAdapter. This is a service that can bootstrap and manage hybrid applications that support both Angular 2 and Angular 1 code.

When we use UpgradeAdapter, what we're really doing is running both versions of Angular at the same time. All Angular 2 code is running in the Angular 2 framework, and Angular 1 code in the Angular 1 framework. Both of these are the actual, fully featured versions of the frameworks. There is no emulation going on, so we can expect to have all the features and natural behavior of both frameworks.

What happens on top of this is that components and services managed by one framework can interoperate with those from the other framework. This happens in three main areas: Dependency injection, the DOM, and change detection.

Dependency Injection

Dependency injection is front and center in both Angular 1 and Angular 2, but there are some key differences between the two frameworks in how it actually works.

Angular 1 Angular 2

Dependency injection tokens are always strings

Tokens can have different types. They are often classes. They may also be strings.

There is exactly one injector. Even in multi-module applications, everything is poured into one big namespace.

There is a tree hierarchy of injectors, with a root injector and an additional injector for each component.

Even accounting for these differences we can still have dependency injection interoperability. The UpgradeAdapter resolves the differences and makes everything work seamlessly:

  • We can make Angular 1 services available for injection to Angular 2 code by upgrading them. The same singleton instance of each service is shared between the frameworks. In Angular 2 these services will always be in the root injector and available to all components. They will always have string tokens - the same tokens that they have in Angular 1.
  • We can also make Angular 2 services available for injection to Angular 1 code by downgrading them. Only services from the Angular 2 root injector can be downgraded. Again, the same singleton instances are shared between the frameworks. When we register a downgrade, we explicitly specify a string token that we want to use in Angular 1.

The two injectors in a hybrid application

Components and the DOM

What we'll find in the DOM of a hybrid application are components and directives from both Angular 1 and Angular 2. These components communicate with each other by using the input and output bindings of their respective frameworks, which the UpgradeAdapter bridges together. They may also communicate through shared injected dependencies, as described above.

There are two key things to understand about what happens in the DOM of a hybrid application:

  1. Every element in the DOM is owned by exactly one of the two frameworks. The other framework ignores it. If an element is owned by Angular 1, Angular 2 treats it as if it didn't exist, and vice versa.
  2. The root of the application is always an Angular 1 template.

So a hybrid application begins life as an Angular 1 application, and it is Angular 1 that processes its root template. Angular 2 then steps into the picture when an Angular 2 component is used somewhere in the application templates. That component's view will then be managed by Angular 2, and it may use any number of Angular 2 components and directives.

Beyond that, we may interleave the two frameworks as much as we need to. We always cross the boundary between the two frameworks by one of two ways:

  1. By using a component from the other framework: An Angular 1 template using an Angular 2 component, or an Angular 2 template using an Angular 1 component.
  2. By transcluding or projecting content from the other framework. The UpgradeAdapter bridges the related concepts of Angular 1 transclusion and Angular 2 content projection together.

DOM element ownership in a hybrid application

Whenever we use a component that belongs to the other framework, a switch between framework boundaries occurs. However, that switch only happens to the children of the component element. Consider a situation where we use an Angular 2 component from Angular 1 like this:

<ng2-component></ng2-component>

The DOM element <ng2-component> will remain to be an Angular 1 managed element, because it's defined in an Angular 1 template. That also means you can apply additional Angular 1 directives to it, but not Angular 2 directives. It is only in the template of the Ng2Component component where Angular 2 steps in. This same rule also applies when you use Angular 1 component directives from Angular 2.

Change Detection

Change detection in Angular 1 is all about scope.$apply(). After every event that occurs, scope.$apply() gets called. This is done either automatically by the framework, or in some cases manually by our own code. It is the point in time when change detection occurs and data bindings get updated.

In Angular 2 things are different. While change detection still occurs after every event, no one needs to call scope.$apply() for that to happen. This is because all Angular 2 code runs inside something called the Angular zone. Angular always knows when the code finishes, so it also knows when it should kick off change detection. The code itself doesn't have to call scope.$apply() or anything like it.

In the case of hybrid applications, the UpgradeAdapter bridges the Angular 1 and Angular 2 approaches. Here's what happens:

  • Everything that happens in the application runs inside the Angular 2 zone. This is true whether the event originated in Angular 1 or Angular 2 code. The zone triggers Angular 2 change detection after every event.
  • The UpgradeAdapter will invoke the Angular 1 $rootScope.$apply() after every turn of the Angular zone. This also triggers Angular 1 change detection after every event.

Change detection in a hybrid application

What this means in practice is that we do not need to call $apply() in our code, regardless of whether it is in Angular 1 on Angular 2. The UpgradeAdapter does it for us. We can still call $apply() so there is no need to remove such calls from existing code. Those calls just don't have any effect in a hybrid application.

When we downgrade an Angular 2 component and then use it from Angular 1, the component's inputs will be watched using Angular 1 change detection. When those inputs change, the corresponding properties in the component are set. We can also hook into the changes by implementing the OnChanges interface in the component, just like we could if it hadn't been downgraded.

Correspondingly, when we upgrade an Angular 1 component and use it from Angular 2, all the bindings defined for the component directive's scope (or bindToController) will be hooked into Angular 2 change detection. They will be treated as regular Angular 2 inputs and set onto the scope (or controller) when they change.

Bootstrapping Hybrid Angular 1+2 Applications

The first step to upgrading an application using the UpgradeAdapter is always to bootstrap it as a hybrid that supports both Angular 1 and Angular 2.

Pure Angular 1 applications can be bootstrapped in two ways: By using an ng-app directive somewhere on the HTML page, or by calling angular.bootstrap from JavaScript. In Angular 2, only the second method is possible - there is no ng-app in Angular 2. This is also the case for hybrid applications. Therefore, it is a good preliminary step to switch Angular 1 applications to use the JavaScript bootstrap method even before switching them to hybrid mode.

Say we have an ng-app driven bootstrap such as this one:

<!DOCTYPE HTML>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
    <script src="app/1-ng-app/app.module.js"></script>
  </head>

  <body ng-app="heroApp" ng-strict-di>
    <div id="message" ng-controller="MainCtrl as mainCtrl">
      {{ mainCtrl.message }}
    </div>
  </body>
</html>

We can remove the ng-app and ng-strict-di directives from the HTML and instead switch to calling angular.bootstrap from JavaScript, which will result in the same thing:

angular.bootstrap(document.body, ['heroApp'], {strictDi: true});

To then switch the application into hybrid mode, we must first install Angular 2 to the project. Follow the instructions in the QuickStart for some pointers on this. When we have Angular 2 installed, we can import and instantiate the UpgradeAdapter, and then call its bootstrap method. It is designed to take the exact same arguments as angular.bootstrap so that it is easy to make the switch:

import { UpgradeAdapter } from '@angular/upgrade';

/* . . . */

const upgradeAdapter = new UpgradeAdapter();

upgradeAdapter.bootstrap(document.body, ['heroApp'], {strictDi: true});

At this point we'll be running a hybrid Angular 1+2 application! All the existing Angular 1 code will work as it always did, but we are now ready to run Angular 2 code as well.

One notable difference between angular.bootstrap and upgradeAdapter.bootstrap is that the latter works asynchronously. This means that we cannot assume that the application has been instantiated immediately after the bootstrap call returns.

As we begin to migrate components to Angular 2, we'll be using the UpgradeAdapter for more than just bootstrapping. It'll be important to use the same instance of the adapter across the whole application, because it stores internal information about what's going on in the application. It'll be useful to have a module for a shared UpgradeAdapter instance in the project:

upgrade_adapter.ts

import { UpgradeAdapter } from '@angular/upgrade';
export const upgradeAdapter = new UpgradeAdapter();

This shared instance can then be pulled in to all the modules that need it:

import { upgradeAdapter } from './upgrade_adapter';

/* . . . */

upgradeAdapter.bootstrap(document.body, ['heroApp'], {strictDi: true});

Using Angular 2 Components from Angular 1 Code

Using an Angular 2 component from Angular 1 code

Once we're running a hybrid app, we can start the gradual process of upgrading code. One of the more common patterns for doing that is to use an Angular 2 component in an Angular 1 context. This could be a completely new component or one that was previously Angular 1 but has been rewritten for Angular 2.

Say we have a simple Angular 2 component that shows information about a hero:

hero-detail.component.ts

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

@Component({
  selector: 'hero-detail',
  template: `
    <h2>Windstorm details!</h2>
    <div><label>id: </label>1</div>
  `
})
export class HeroDetailComponent {

}

If we want to use this component from Angular 1, we need to downgrade it using the upgrade adapter. What we get when we do that is an Angular 1 directive, which we can then register into our Angular 1 module:

import { HeroDetailComponent } from './hero-detail.component';

/* . . . */

angular.module('heroApp', [])
  .directive('heroDetail', upgradeAdapter.downgradeNg2Component(HeroDetailComponent));

What we have here is an Angular 1 directive called heroDetail, which we can use like any other directive in our Angular 1 templates.

<hero-detail></hero-detail>

Note that since Angular 1 directives are matched based on their name, the selector metadata of the Angular 2 component is not used in Angular 1. It is matched as an element directive (restrict: 'E') called heroDetail.

Most components are not quite this simple, of course. Many of them have inputs and outputs that connect them to the outside world. An Angular 2 hero detail component with inputs and outputs might look like this:

hero-detail.component.ts

import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Hero } from '../hero';

@Component({
  selector: 'hero-detail',
  template: `
    <h2>{{hero.name}} details!</h2>
    <div><label>id: </label>{{hero.id}}</div>
    <button (click)="onDelete()">Delete</button>
  `
})
export class HeroDetailComponent {
  @Input() hero: Hero;
  @Output() deleted = new EventEmitter<Hero>();
  onDelete() {
    this.deleted.emit(this.hero);
  }
}

These inputs and outputs can be supplied from the Angular 1 template, and the UpgradeAdapter takes care of bridging them over:

<div ng-controller="MainController as mainCtrl">
  <hero-detail [hero]="mainCtrl.hero"
               (deleted)="mainCtrl.onDelete($event)">
  </hero-detail>
</div>

Note that even though we are in an Angular 1 template, we're using Angular 2 attribute syntax to bind the inputs and outputs. This is a requirement for downgraded components. The expressions themselves are still regular Angular 1 expressions.

Use kebab-case for downgraded component attributes

There's one notable exception to the rule of using Angular 2 attribute syntax for downgraded components. It has to do with input or output names that consist of multiple words. In Angular 2 we would bind these attributes using camelCase:

[myHero]="hero"

But when using them from Angular 1 templates, we need to use kebab-case:

[my-hero]="hero"

The $event variable can be used in outputs to gain access to the object that was emitted. In this case it will be the Hero object, because that is what was passed to this.deleted.emit().

Since this is an Angular 1 template, we can still use other Angular 1 directives on the element, even though it has Angular 2 binding attributes on it. For example, we can easily make multiple copies of the component using ng-repeat:

<div ng-controller="MainController as mainCtrl">
  <hero-detail [hero]="hero"
               (deleted)="mainCtrl.onDelete($event)"
               ng-repeat="hero in mainCtrl.heroes">
  </hero-detail>
</div>

Using Angular 1 Component Directives from Angular 2 Code

Using an Angular 1 component from Angular 2 code

So, we can write an Angular 2 component and then use it from Angular 1 code. This is very useful when we start our migration from lower-level components and work our way up. But in some cases it is more convenient to do things in the opposite order: To start with higher-level components and work our way down. This too can be done using the UpgradeAdapter. We can upgrade Angular 1 component directives and then use them from Angular 2.

Not all kinds of Angular 1 directives can be upgraded. The directive really has to be a component directive, with the characteristics described in the preparation guide above. Our safest bet for ensuring compatibility is using the component API introduced in Angular 1.5.

A simple example of an upgradable component is one that just has a template and a controller:

hero-detail.component.ts

export const heroDetail = {
  template: `
    <h2>Windstorm details!</h2>
    <div><label>id: </label>1</div>
  `,
  controller: function() {
  }
};

We can upgrade this component to Angular 2 using the UpgradeAdapter's upgradeNg1Component method. It takes the name of an Angular 1 component directive and returns an Angular 2 component class. When we then want to use it from an Angular 2 component, we list it the in the directives metadata of the component and then just use it in the Angular 2 template:

container.component.ts

import { Component } from '@angular/core';
import { upgradeAdapter } from './upgrade_adapter';

const HeroDetail = upgradeAdapter.upgradeNg1Component('heroDetail');

@Component({
  selector: 'my-container',
  template: `
    <h1>Tour of Heroes</h1>
    <hero-detail></hero-detail>
  `,
  directives: [HeroDetail]
})
export class ContainerComponent {

}

Upgraded components always have an element selector, which is based on the original name of the original Angular 1 component directive.

An upgraded component may also have inputs and outputs, as defined by the scope/controller bindings of the original Angular 1 component directive. When we use the component from an Angular 2 template, we provide the inputs and outputs using Angular 2 template syntax, with the following rules:

Binding definition Template syntax
Attribute binding

myAttribute: '@myAttribute'

<my-component myAttribute="value">

Expression binding

myOutput: '&myOutput'

<my-component (myOutput)="action()">

One-way binding

myValue: '<myValue'

<my-component [myValue]="anExpression">

Two-way binding

myValue: '=myValue'

As a two-way binding: <my-component [(myValue)]="anExpression">. Since most Angular 1 two-way bindings actually only need a one-way binding in practice, <my-component [myValue]="anExpression"> is often enough.

As an example, say we have a hero detail Angular 1 component directive with one input and one output:

hero-detail.component.ts

export const heroDetail = {
  bindings: {
    hero: '<',
    deleted: '&'
  },
  template: `
    <h2>{{$ctrl.hero.name}} details!</h2>
    <div><label>id: </label>{{$ctrl.hero.id}}</div>
    <button ng-click="$ctrl.onDelete()">Delete</button>
  `,
  controller: function() {
    this.onDelete = () => {
      this.deleted(this.hero);
    };
  }
};

We can upgrade this component to Angular 2, and then provide the input and output using Angular 2 template syntax:

container.component.ts

import { Component } from '@angular/core';
import { upgradeAdapter } from './upgrade_adapter';
import { Hero } from '../hero';

const HeroDetail = upgradeAdapter.upgradeNg1Component('heroDetail');

@Component({
  selector: 'my-container',
  template: `
    <h1>Tour of Heroes</h1>
    <hero-detail [hero]="hero"
                 (deleted)="heroDeleted($event)">
    </hero-detail>
  `,
  directives: [HeroDetail]
})
export class ContainerComponent {
  hero = new Hero(1, 'Windstorm');
  heroDeleted(hero: Hero) {
    hero.name = 'Ex-' + hero.name;
  }
}

Projecting Angular 1 Content into Angular 2 Components

Projecting Angular 1 content into Angular 2

When we are using a downgraded Angular 2 component from an Angular 1 template, the need may arise to transclude some content into it. This is also possible. While there is no such thing as transclusion in Angular 2, there is a very similar concept called content projection. The UpgradeAdapter is able to make these two features interoperate.

Angular 2 components that support content projection make use of an <ng-content> tag within them. Here's an example of such a component:

hero-detail.component.ts

import { Component, Input } from '@angular/core';
import { Hero } from '../hero';

@Component({
  selector: 'hero-detail',
  template: `
    <h2>{{hero.name}}</h2>
    <div>
      <ng-content></ng-content>
    </div>
  `
})
export class HeroDetailComponent {
  @Input() hero: Hero;
}

When using the component from Angular 1, we can supply contents for it. Just like they would be transcluded in Angular 1, they get projected to the location of the <ng-content> tag in Angular 2:

<div ng-controller="MainController as mainCtrl">
  <hero-detail [hero]="mainCtrl.hero">
    <!-- Everything here will get projected -->
    <p>{{mainCtrl.hero.description}}</p>
  </hero-detail>
</div>

When Angular 1 content gets projected inside an Angular 2 component, it still remains in "Angular 1 land" and is managed by the Angular 1 framework.

Transcluding Angular 2 Content into Angular 1 Component Directives

Projecting Angular 2 content into Angular 1

Just like we can project Angular 1 content into Angular 2 components, we can transclude Angular 2 content into Angular 1 components, whenever we are using upgraded versions from them.

When an Angular 1 component directive supports transclusion, it may use the ng-transclude directive in its template to mark the transclusion point:

hero-detail.component.ts

export const heroDetailComponent = {
  bindings: {
    hero: '='
  },
  template: `
    <h2>{{$ctrl.hero.name}}</h2>
    <div>
      <ng-transclude></ng-transclude>
    </div>
  `
};

The directive also needs to have the transclude: true option enabled. It is on by default for component directives defined with the 1.5 component API.

If we upgrade this component and use it from Angular 2, we can populate the component tag with contents that will then get transcluded:

container.component.ts

import { Component } from '@angular/core';
import { upgradeAdapter } from './upgrade_adapter';
import { Hero } from '../hero';

const HeroDetail = upgradeAdapter.upgradeNg1Component('heroDetail');

@Component({
  selector: 'my-container',
  template: `
    <hero-detail [hero]="hero">
      <!-- Everything here will get transcluded -->
      <p>{{hero.description}}</p>
    </hero-detail>
  `,
  directives: [HeroDetail]
})
export class ContainerComponent {
  hero = new Hero(1, 'Windstorm', 'Specific powers of controlling winds');
}

Making Angular 1 Dependencies Injectable to Angular 2

When running a hybrid app, we may bump into situations where we need to have some Angular 1 dependencies to be injected to Angular 2 code. This may be because we have some business logic still in Angular 1 services, or because we need some of Angular 1's built-in services like $location or $timeout.

In these situations, it is possible to upgrade an Angular 1 provider to Angular 2. This makes it possible to then inject it somewhere in Angular 2 code. For example, we might have a service called HeroesService in Angular 1:

heroes.service.ts

import { Hero } from '../hero';

export class HeroesService {
  get() {
    return [
      new Hero(1, 'Windstorm'),
      new Hero(2, 'Spiderman')
    ];
  }
}

We can upgrade the service using the UpgradeAdapter's upgradeNg1Provider method by giving it the name of the service. This adds the service into Angular 2's root injector.

app.module.ts

angular.module('heroApp', [])
  .service('heroes', HeroesService)
  .directive('heroDetail',
    upgradeAdapter.downgradeNg2Component(HeroDetailComponent));

upgradeAdapter.upgradeNg1Provider('heroes');

We can then inject it in Angular 2 using a string token that matches its original name in Angular 1:

hero-detail.component.ts

import { Component, Inject } from '@angular/core';
import { HeroesService } from './heroes.service';
import { Hero } from '../hero';

@Component({
  selector: 'hero-detail',
  template: `
    <h2>{{hero.id}}: {{hero.name}}</h2>
  `
})
export class HeroDetailComponent {
  hero: Hero;
  constructor(@Inject('heroes') heroes: HeroesService) {
    this.hero = heroes.get()[0];
  }
}

In this example we upgraded a service class, which has the added benefit that we can use a TypeScript type annotation when we inject it. While it doesn't affect how the dependency is handled, it enables the benefits of static type checking. This is not required though, and any Angular 1 service, factory, or provider can be upgraded.

Making Angular 2 Dependencies Injectable to Angular 1

In addition to upgrading Angular 1 dependencies, we can also downgrade Angular 2 dependencies, so that we can use them from Angular 1. This can be useful when we start migrating services to Angular 2 or creating new services in Angular 2 while we still have components written in Angular 1.

For example, we might have an Angular 2 service called Heroes:

heroes.ts

import { Injectable } from '@angular/core';
import { Hero } from '../hero';

@Injectable()
export class Heroes {
  get() {
    return [
      new Hero(1, 'Windstorm'),
      new Hero(2, 'Spiderman')
    ];
  }
}

We can again use the UpgradeAdapter for this, but first we need to register Heroes to the Angular 2 injector itself. In a pure Angular 2 application we would do this when we bootstrap the app, as described in the dependency injection guide. But since hybrid applications are bootstrapped using the UpgradeAdapter, we also need to register our Angular 2 providers using UpgradeAdapter. It has a method called addProvider for this purpose.

Once we've registered the Angular 2 provider, we can turn Heroes into an Angular 1 factory function using upgradeAdapter.downgradeNg2Provider(). We can then plug the factory into an Angular 1 module, at which point we also choose what the name of the dependency will be in Angular 1:

app.module.ts

upgradeAdapter.addProvider(Heroes);

angular.module('heroApp', [])
  .factory('heroes', upgradeAdapter.downgradeNg2Provider(Heroes))
  .component('heroDetail', heroDetailComponent);

After this, the service is injectable anywhere in our Angular 1 code:

hero-detail.component.ts

export const heroDetailComponent = {
  template: `
    <h2>{{$ctrl.hero.id}}: {{$ctrl.hero.name}}</h2>
  `,
  controller: ['heroes', function(heroes: Heroes) {
    this.hero = heroes.get()[0];
  }]
};

PhoneCat Upgrade Tutorial

In this section and we will look at a complete example of preparing and upgrading an application using the upgrade module. The app we're going to work on is Angular PhoneCat from the original Angular 1 tutorial, which is where many of us began our Angular adventures. Now we'll see how to bring that application to the brave new world of Angular 2.

During the process we'll learn how to apply the steps outlined in the preparation guide in practice: We'll align the application with Angular 2 and also take TypeScript into use.

To follow along with the tutorial, clone the angular-phonecat repository and apply the steps as we go.

In terms of project structure, this is where our work begins:

angular-phonecat
bower.json
karma.conf.js
package.json
app
core
checkmark
checkmark.filter.js
checkmark.filter.spec.js
phone
phone.module.js
phone.service.js
phone.service.spec.js
core.module.js
phone-detail
phone-detail.component.js
phone-detail.component.spec.js
phone-detail.module.js
phone-detail.template.html
phone-list
phone-list.component.js
phone-list.component.spec.js
phone-list.module.js
phone-list.template.html
img
...
phones
...
app.animations.js
app.config.js
app.css
app.module.js
index.html
e2e-tests
protractor-conf.js
scenarios.js

This is actually a pretty good starting point. The code uses the Angular 1.5 component API and the organization follows the Angular 1 Style Guide, which is an important preparation step before a successful upgrade.

  • Each component, service, and filter is in its own source file, as per the Rule of 1.
  • The core, phone-detail, and phone-list modules are each in their own subdirectory. Those subdirectories contain the JavaScript code as well as the HTML templates that go with each particular feature. This is in line with the Folders-by-Feature Structure and Modularity rules.
  • Unit tests are located side-by-side with application code where they are easily found, as described in the rules for Organizing Tests.

Switching to TypeScript

Since we're going to be writing our Angular 2 code in TypeScript, it makes sense to bring in the TypeScript compiler even before we begin upgrading.

We will also start to gradually phase out the Bower package manager in favor of NPM. We'll install all new dependencies using NPM, and will eventually be able to remove Bower from the project.

Let's begin by installing TypeScript to the project. While we're at it, let's also install the Typings type definition manager. It will allow us to install type definitions for libraries that don't come with prepackaged types.

npm i typescript typings --save-dev

Let's also add run scripts for the tsc TypeScript compiler and the typings tool to package.json:

package.json

{
  "scripts": {
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  }
}

We can now use Typings to install type definitions for the existing libraries that we're using: Angular 1 and the Jasmine unit test framework.

npm run typings install dt~jquery dt~angular dt~angular-route \
  dt~angular-resource dt~angular-mocks dt~angular-animate \
  dt~jasmine -- --save --global

This will add these typings into a typings.json configuration file as well as download them into the typings directory.

We should also configure the TypeScript compiler so that it can understand our project. We'll add a tsconfig.json file to the project directory, just like we do in the Quickstart. It instructs the TypeScript compiler how to interpret our source files.

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true
  }
}

We are telling the TypeScript compiler to turn our TypeScript files to ES5 code bundled into CommonJS modules.

We can now launch the TypeScript compiler from the command line. It will watch our .ts source files and compile them to JavaScript on the fly. Those compiled .js files are then loaded into the browser by SystemJS. This is a process we'll want to have continuously running in the background as we go along.

npm run tsc:w

The next thing we'll do is convert our JavaScript files to TypeScript. Since TypeScript is a superset of ECMAScript 2015, which in turn is a superset of ECMAScript 5, we can simply switch the file extensions from .js to .ts and everything will work just like it did before. As the TypeScript compiler runs, it emits the corresponding .js file for every .ts file and the compiled JavaScript is what actually gets executed. If you start the project HTTP server with npm start, you should see the fully functional application in your browser.

Now that we have TypeScript though, we can start benefiting from some of its features. There's a lot of value the language can provide to Angular 1 applications.

For one thing, TypeScript is a superset of ES2015. Any app that has previously been written in ES5 - like the PhoneCat example has - can with TypeScript start incorporating all of the JavaScript features that are new to ES2015. These include things like lets and consts, arrow functions, default function parameters, and destructuring assignments.

Another thing we can do is start adding type safety to our code. This has actually partially already happened because of the Angular 1 typings we installed. TypeScript are checking that we are calling Angular 1 APIs correctly when we do things like register components to Angular modules.

But we can also start adding type annotations for our own code to get even more out of TypeScript's type system. For instance, we can annotate the checkmark filter so that it explicitly expects booleans as arguments. This makes it clearer what the filter is supposed to do.

app/core/checkmark/checkmark.filter.ts

angular.
  module('core').
  filter('checkmark', function() {
    return function(input: boolean) {
      return input ? '\u2713' : '\u2718';
    };
  });

In the Phone service we can explicitly annotate the $resource service dependency as an angular.resource.IResourceService - a type defined by the Angular 1 typings.

app/core/phone/phone.service.ts

angular.
  module('core.phone').
  factory('Phone', ['$resource',
    function($resource: angular.resource.IResourceService) {
      return $resource('phones/:phoneId.json', {}, {
        query: {
          method: 'GET',
          params: {phoneId: 'phones'},
          isArray: true
        }
      });
    }
  ]);

We can apply the same trick to the application's route configuration file in app.config.ts, where we are using the location and route services. By annotating them accordingly TypeScript can verify we're calling their APIs with the correct kinds of arguments.

app/app.config.ts

angular.
  module('phonecatApp').
  config(['$locationProvider', '$routeProvider',
    function config($locationProvider: angular.ILocationProvider,
                    $routeProvider: angular.route.IRouteProvider) {
      $locationProvider.hashPrefix('!');

      $routeProvider.
        when('/phones', {
          template: '<phone-list></phone-list>'
        }).
        when('/phones/:phoneId', {
          template: '<phone-detail></phone-detail>'
        }).
        otherwise('/phones');
    }
  ]);

The Angular 1.x type definitions we installed with Typings are not officially maintained by the Angular team, but are quite comprehensive. It is possible to make an Angular 1.x application fully type-annotated with the help of these definitions.

If this is something we wanted to do, it would be a good idea to enable the noImplicitAny configuration option in tsconfig.json. This would cause the TypeScript compiler to display a warning when there's any code that does not yet have type annotations. We could use it as a guide to inform us about how close we are to having a fully annotated project.

Another TypeScript feature we can make use of is classes. In particular, we can turn our component controllers into classes. That way they'll be a step closer to becoming Angular 2 component classes, which will make our life easier once we do the upgrade.

Angular 1 expects controllers to be constructor functions. That's exactly what ES2015/TypeScript classes are under the hood, so that means we can just plug in a class as a component controller and Angular 1 will happily use it.

Here's what our new class for the phone list component controller looks like:

app/phone-list/phone-list.component.ts

class PhoneListController {
  phones: any[];
  orderProp: string;
  query: string;

  static $inject = ['Phone'];
  constructor(Phone: any) {
    this.phones = Phone.query();
    this.orderProp = 'age';
  }

}

angular.
  module('phoneList').
  component('phoneList', {
    templateUrl: 'phone-list/phone-list.template.html',
    controller: PhoneListController
  });

What was previously done in the controller function is now done in the class constructor function. The dependency injection annotations are attached to the class using a static property $inject. At runtime this becomes the PhoneListController.$inject property.

The class additionally declares three members: The array of phones, the name of the current sort key, and the search query. These are all things we have already been attaching to the controller but that weren't explicitly declared anywhere. The last one of these isn't actually used in the TypeScript code since it's only referred to in the template, but for the sake of clarity we want to define all the members our controller will have.

In the Phone detail controller we'll have two members: One for the phone that the user is looking at and another for the URL of the currently displayed image:

app/phone-detail/phone-detail.component.ts

class PhoneDetailController {
  phone: any;
  mainImageUrl: string;

  static $inject = ['$routeParams', 'Phone'];
  constructor($routeParams: angular.route.IRouteParamsService, Phone: any) {
    let phoneId = $routeParams['phoneId'];
    this.phone = Phone.get({phoneId}, (phone: any) => {
      this.setImage(phone.images[0]);
    });
  }

  setImage(imageUrl: string) {
    this.mainImageUrl = imageUrl;
  }
}

angular.
  module('phoneDetail').
  component('phoneDetail', {
    templateUrl: 'phone-detail/phone-detail.template.html',
    controller: PhoneDetailController
  });

This makes our controller code look a lot more like Angular 2 already. We're all set to actually introduce Angular 2 into the project.

If we had any Angular 1 services in the project, those would also be a good candidate for converting to classes, since like controllers, they're also constructor functions. But we only have the Phone factory in this project, and that's a bit special since it's an ngResource factory. So we won't be doing anything to it in the preparation stage. We'll instead turn it directly into an Angular 2 service.

Installing Angular 2

Having completed our preparation work, let's get going with the Angular 2 upgrade of PhoneCat. We'll do this incrementally with the help of the upgrade module that comes with Angular 2. By the time we're done, we'll be able to remove Angular 1 from the project completely, but the key is to do this piece by piece without breaking the application.

The project also contains some animations, which we are not yet upgrading in this version of the guide. This will change in a later release.

Let's install Angular 2 into the project, along with the SystemJS module loader. Take a look into the Quickstart guide and get the following configurations from there:

  • Add Angular 2 and the other new dependencies to package.json
  • Add the new typings into typings.json
  • The SystemJS configuration file systemjs.config.js to the project root directory.

Once these are done, run:

npm install
npm run typings install

We can soon load Angular 2 dependencies into the application via index.html, but first we need to do some directory path adjustments. This is because we're going to need to load files from node_modules and the project root, whereas so far in this project everything has been loaded from the /app directory.

Move the app/index.html file to the project root directory. Then change the development server root path in package.json to also point to the project root instead of app:

package.json

{
  "scripts": {
    "start": "http-server -a localhost -p 8000 -c-1 ./"
  }
}

Now we're able to serve everything from the project root to the web browser. But we do not want to have to change all the image and data paths used in the application code to match our development setup. For that reason, we'll add a <base> tag to index.html, which will cause relative URLs to be resolved back to the /app directory:

index.html

<base href="/app/">

Now we can load Angular 2 via SystemJS. We'll add the Angular 2 polyfills and the SystemJS config to the end of the <head> section, and then we'll use System.import to load the actual application:

index.html

<script src="/node_modules/core-js/client/shim.min.js"></script>
<script src="/node_modules/zone.js/dist/zone.js"></script>
<script src="/node_modules/reflect-metadata/Reflect.js"></script>
<script src="/node_modules/systemjs/dist/system.src.js"></script>
<script src="/systemjs.config.js"></script>
<script>
  System.import('/app');
</script>

In the systemjs.config.js file we got from the Quickstart we also need to make a couple of adjustments because of our project structure. We want to point the browser to the project root when loading things through SystemJS, instead of using the <base> URL:

systemjs.config.js

var map = {
  'app':                        '/app', // 'dist',

  '@angular':                   '/node_modules/@angular',
  'angular2-in-memory-web-api': '/node_modules/angular2-in-memory-web-api',
  'rxjs':                       '/node_modules/rxjs'
};

var packages = {
  '/app':                       { main: 'main.js',  defaultExtension: 'js' },
  'rxjs':                       { defaultExtension: 'js' },
  'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
};

Bootstrapping A Hybrid 1+2 PhoneCat

What we'll do next is bootstrap the application as a hybrid application that supports both Angular 1 and Angular 2 components. Once we've done that we can start converting the individual pieces to Angular 2.

To bootstrap a hybrid application, we first need to initialize an UpgradeAdapter, which provides the glue that joins the two versions of the framework together. Let's import the UpgradeAdapter class into a new file app/main.ts. This file has been configured as the application entrypoint in systemjs.config.js, so it is already being loaded by the browser.

app/main.ts

import { UpgradeAdapter } from '@angular/upgrade';

We can then make an adapter by instantiating the class:

let upgradeAdapter = new UpgradeAdapter();

Our application is currently bootstrapped using the Angular 1 ng-app directive attached to the <html> element of the host page. This will no longer work with Angular 2. We should switch to a JavaScript-driven bootstrap instead. So, remove the ng-app attribute from index.html, and instead add this to main.ts:

upgradeAdapter.bootstrap(document.documentElement, ['phonecatApp']);

The arguments used here are the root element of the application (which is the same element we had ng-app on earlier), and the Angular 1.x modules that we want to load. Since we're bootstrapping the app through an UpgradeAdapter, we're actually now running the app as a hybrid Angular 1+2 app.

This means we are now running both Angular 1 and 2 at the same time. That's pretty exciting! We're not running any actual Angular 2 components yet though, so let's do that next.

Upgrading the Phone service

The first piece we'll port over to Angular 2 is the Phone service, which resides in app/core/phone/phone.service.ts and makes it possible for components to load phone information from the server. Right now it's implemented with ngResource and we're using it for two things:

  • For loading the list of all phones into the phone list component
  • For loading the details of a single phone into the phone detail component.

We can replace this implementation with an Angular 2 service class, while keeping our controllers in Angular 1 land. In the new version we'll just use the Http service from Angular 2 instead of ngResource.

Before the Http service is available for injection, we need to register it into our application's dependency injector. We should import the HTTP_PROVIDERS constant in main.ts:

import { HTTP_PROVIDERS } from '@angular/http';

In a regular Angular 2 application we would now pass HTTP_PROVIDERS into the application bootstrap function. But we can't do that in a hybrid application such as the one we're working on. That's because the bootstrap method of UpgradeAdapter expects Angular 1 modules as dependencies, not Angular 2 providers.

What we must do instead is register HTTP_PROVIDERS into the UpgradeAdapter separately. It has a method called addProvider for that purpose:

upgradeAdapter.addProvider(HTTP_PROVIDERS);

Now we're ready to upgrade the Phone service itself. We replace the ngResource-based service in phone.service.ts with a TypeScript class decorated as @Injectable:

app/core/phone/phone.service.ts

@Injectable()
export class Phone {
/* . . . */
}

The @Injectable decorator will attach some dependency injection metadata to the class, letting Angular 2 know about its dependencies. As described by our Dependency Injection Guide, this is a marker decorator we need to use for classes that have no other Angular 2 decorators but still need to have their dependencies injected.

In its constructor the class expects to get the Http service. It will be injected to it and it is stored as a private field. The service is then used in the two instance methods, one of which loads the list of all phones, and the other the details of a particular phone:

@Injectable()
export class Phone {
  constructor(private http: Http) { }
  query(): Observable<PhoneData[]> {
    return this.http.get(`phones/phones.json`)
      .map((res: Response) => res.json());
  }
  get(id: string): Observable<PhoneData> {
    return this.http.get(`phones/${id}.json`)
      .map((res: Response) => res.json());
  }
}

The methods now return Observables of type PhoneData and PhoneData[]. This is a type we don't have yet, so let's add a simple interface for it:

app/core/phone/phone.service.ts

export interface PhoneData {
  name: string;
  snippet: string;
  images: string[];
}

Here's the full, final code for the service:

app/core/phone/phone.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import 'rxjs/add/operator/map';

export interface PhoneData {
  name: string;
  snippet: string;
  images: string[];
}

@Injectable()
export class Phone {
  constructor(private http: Http) { }
  query(): Observable<PhoneData[]> {
    return this.http.get(`phones/phones.json`)
      .map((res: Response) => res.json());
  }
  get(id: string): Observable<PhoneData> {
    return this.http.get(`phones/${id}.json`)
      .map((res: Response) => res.json());
  }
}

Notice that we're importing the map operator of the RxJS Observable separately. We need to do this for all RxJS operators that we want to use, since Angular 2 does not load all of them by default.

The new Phone service now has the same features that the original, ngResource based service did. Now we just need to register the new service into the application, so that our Angular 1 components will be able to use it.

UpgradeAdapter has a downgradeNg2Provider method for the purpose of making Angular 2 services available to Angular 1 code. We can use it to plug in our Phone service:

app/main.ts

import { Phone } from './core/phone/phone.service';

/* . . . */

upgradeAdapter.addProvider(Phone);

/* . . . */

angular.module('core.phone')
  .factory('phone', upgradeAdapter.downgradeNg2Provider(Phone));

Note that we actually needed to do two registrations here:

  1. Register Phone as an Angular 2 provider with the addProvider method. That's the same method that we used earlier for HTTP_PROVIDERS.
  2. Register an Angular 1 factory called phone, which will be a downgraded version of the Phone Angular 2 service.

Now that we are loading phone.service.ts through an import that is resolved by SystemJS, we should remove the <script> tag for the service from index.html. This is something we'll do to all our components as we upgrade them. Simultaneously with the Angular 1 to 2 upgrade we're also migrating our code from scripts to modules.

At this point we can switch our two components to use the new service instead of the old one. We $inject it as the downgraded phone factory, but it's really an instance of the Phone class and we can annotate its type accordingly:

app/phone-list/phone-list.component.ts

import { Phone, PhoneData } from '../core/phone/phone.service';

class PhoneListController {
  phones: PhoneData[];
  orderProp: string;

  static $inject = ['phone'];
  constructor(phone: Phone) {
    phone.query().subscribe(phones => {
      this.phones = phones;
    });
    this.orderProp = 'age';
  }

}

angular.
  module('phoneList').
  component('phoneList', {
    templateUrl: 'app/phone-list/phone-list.template.html',
    controller: PhoneListController
  });

app/phone-detail/phone-detail.component.ts

import { Phone, PhoneData } from '../core/phone/phone.service';

class PhoneDetailController {
  phone: PhoneData;
  mainImageUrl: string;

  static $inject = ['$routeParams', 'phone'];
  constructor($routeParams: angular.route.IRouteParamsService, phone: Phone) {
    let phoneId = $routeParams['phoneId'];
    phone.get(phoneId).subscribe(data => {
      this.phone = data;
      this.setImage(data.images[0]);
    });
  }

  setImage(imageUrl: string) {
    this.mainImageUrl = imageUrl;
  }
}

angular.
  module('phoneDetail').
  component('phoneDetail', {
    templateUrl: 'phone-detail/phone-detail.template.html',
    controller: PhoneDetailController
  });

What we have here are two Angular 1 components using an Angular 2 service! The components don't need to be aware of this, though the fact that the service returns Observables and not Promises is a bit of a giveaway. In any case, what we've achieved is a migration of a service to Angular 2 without having to yet migrate the components that use it.

We could also use the toPromise method of Observable to turn those Observables into Promises in the service. This can in many cases further reduce the amount of changes needed in the component controllers.

Upgrading Components

Next, let's upgrade our Angular 1 components to Angular 2 components. We'll do it one at a time, while still keeping the application in hybrid mode. As we make these conversions, we'll also be defining our first Angular 2 pipes.

Let's look at the phone list component first. Right now it contains a TypeScript controller class and a component definition object. We can morph this into an Angular 2 component by just renaming the controller class and turning the Angular 1 component definition object into an Angular 2 @Component decorator. We can then also remove the static $inject property from the class:

app/phone-list/phone-list.component.ts

import { Component } from '@angular/core';
import { Phone, PhoneData } from '../core/phone/phone.service';

@Component({
  selector: 'phone-list',
  templateUrl: 'phone-list/phone-list.template.html'
})
export class PhoneListComponent {
  phones: PhoneData[];
  query: string;
  orderProp: string;

  constructor(phone: Phone) {
    phone.query().subscribe(phones => {
      this.phones = phones;
    });
    this.orderProp = 'age';
  }
}

The selector attribute is a CSS selector that defines where on the page the component should go. In Angular 1 we do matching based on component names, but in Angular 2 we have these explicit selectors. This one will match elements with the name phone-list, just like the Angular 1 version did.

We now also need to convert the template of this component into Angular 2 syntax. In the search controls we need to use Angular 2 syntax for the two ngModels. We should also no longer use the $ctrl prefix in expressions:

app/phone-list/phone-list.template.html

<p>
  Search:
  <input [(ngModel)]="query" />
</p>

<p>
  Sort by:
  <select [(ngModel)]="orderProp">
    <option value="name">Alphabetical</option>
    <option value="age">Newest</option>
  </select>
</p>

In the list we need to replace the ng-repeat with an *ngFor and the let var of iterable syntax, which is described in our Template Syntax guide. For the images, we can replace ng-src with a binding to the standard src property.

app/phone-list/phone-list.template.html

<ul class="phones">
  <li *ngFor="let phone of getPhones()"
      class="thumbnail phone-list-item">
    <a href="/#!/phones/{{phone.id}}" class="thumb">
      <img [src]="phone.imageUrl" [alt]="phone.name" />
    </a>
    <a href="/#!/phones/{{phone.id}}" class="name">{{phone.name}}</a>
    <p>{{phone.snippet}}</p>
  </li>
</ul>

Another thing that we've done here is that we've removed the use of filter and orderBy filters, and replaced them with a call to the getPhones() controller method. The built-in Angular filters filter and orderBy do not exist in Angular 2, so we need to do the filtering and sorting ourselves. We could define our own Angular 2 pipes for this purpose, but in this case it is more convenient to just implement the filtering and ordering logic in the component itself. We expect the getPhones() method to return a collection where the current filtering and ordering has been applied.

app/phone-list/phone-list.component.ts

getPhones(): PhoneData[] {
  return this.sortPhones(this.filterPhones(this.phones));
}

private filterPhones(phones: PhoneData[]) {
  if (phones && this.query) {
    return phones.filter(phone => {
      let name = phone.name.toLowerCase();
      let snippet = phone.snippet.toLowerCase();
      return name.indexOf(this.query) >= 0 || snippet.indexOf(this.query) >= 0;
    });
  }
  return phones;
}

private sortPhones(phones: PhoneData[]) {
    if (phones && this.orderProp) {
        return phones
          .slice(0) // Make a copy
          .sort((a, b) => {
             if (a[this.orderProp] < b[this.orderProp]) {
               return -1;
             } else if ([b[this.orderProp] < a[this.orderProp]]) {
               return 1;
             } else {
               return 0;
             }
          });
    }
    return phones;
}

In the entrypoint file main.ts we're going to plug this component into our application. Instead of registering a component, we register a phoneList directive. The directive is a downgraded version of our Angular 2 component, and the UpgradeAdapter handles the bridging between the two:

app/main.ts

import { PhoneListComponent } from './phone-list/phone-list.component';

/* . . . */

angular.module('phoneList')
  .directive(
    'phoneList',
    <angular.IDirectiveFactory>
      upgradeAdapter.downgradeNg2Component(PhoneListComponent)
  );

The <angular.IDirectiveFactory> type annotation here is to let the TypeScript compiler know that the return value of the downgrade method call will be something that can be used as a directive factory.

At this point, also remove the <script> tag for the phone list component from index.html.

Now we can start looking at our other component, which is the one for the phone details. Set the contents of phone-detail.component.ts as follows:

app/phone-detail/phone-detail.component.ts

import { Component, Inject } from '@angular/core';
import { Phone, PhoneData } from '../core/phone/phone.service';
@Component({
  selector: 'phone-detail',
  templateUrl: 'phone-detail/phone-detail.template.html',
})
export class PhoneDetailComponent {
  phone: PhoneData;
  mainImageUrl: string;

  constructor(@Inject('$routeParams')
                $routeParams: angular.route.IRouteParamsService,
              phone: Phone) {
    phone.get($routeParams['phoneId']).subscribe(phone => {
      this.phone = phone;
      this.setImage(phone.images[0]);
    });
  }

  setImage(imageUrl: string) {
    this.mainImageUrl = imageUrl;
  }
}

This is pretty similar to what we did with the phone list. The one new change here is the use of @Inject for the $routeParams dependency. It tells the Angular 2 injector what this dependency should map to. We have a dependency called $routeParams in the Angular 1 injector, where it is provided by the Angular 1 router. That is what we were already using when PhoneDetails was still an Angular 1 controller.

The things is though, Angular 1 dependencies are not made automatically available to Angular 2 components, so if we were to run this now, it would not work. We need to explicitly tell the UpgradeAdapter to upgrade $routeParams so that it is available for injection in Angular 2. We can do it in main.ts:

app/main.ts

upgradeAdapter.upgradeNg1Provider('$routeParams');

We now also need to convert the template of this component into Angular 2 syntax. Here is the new template in its entirety:

app/phone-detail/phone-detail.template.html

<div *ngIf="phone">
  <div class="phone-images">
    <img [src]="img" class="phone"
        [ngClass]="{selected: img === mainImageUrl}"
        *ngFor="let img of phone.images" />
  </div>

  <h1>{{phone.name}}</h1>

  <p>{{phone.description}}</p>

  <ul class="phone-thumbs">
    <li *ngFor="let img of phone.images">
      <img [src]="img" (click)="setImage(img)" />
    </li>
  </ul>

  <ul class="specs">
    <li>
      <span>Availability and Networks</span>
      <dl>
        <dt>Availability</dt>
        <dd *ngFor="let availability of phone.availability">{{availability}}</dd>
      </dl>
    </li>
    <li>
      <span>Battery</span>
      <dl>
        <dt>Type</dt>
        <dd>{{phone.battery?.type}}</dd>
        <dt>Talk Time</dt>
        <dd>{{phone.battery?.talkTime}}</dd>
        <dt>Standby time (max)</dt>
        <dd>{{phone.battery?.standbyTime}}</dd>
      </dl>
    </li>
    <li>
      <span>Storage and Memory</span>
      <dl>
        <dt>RAM</dt>
        <dd>{{phone.storage?.ram}}</dd>
        <dt>Internal Storage</dt>
        <dd>{{phone.storage?.flash}}</dd>
      </dl>
    </li>
    <li>
      <span>Connectivity</span>
      <dl>
        <dt>Network Support</dt>
        <dd>{{phone.connectivity?.cell}}</dd>
        <dt>WiFi</dt>
        <dd>{{phone.connectivity?.wifi}}</dd>
        <dt>Bluetooth</dt>
        <dd>{{phone.connectivity?.bluetooth}}</dd>
        <dt>Infrared</dt>
        <dd>{{phone.connectivity?.infrared | checkmark}}</dd>
        <dt>GPS</dt>
        <dd>{{phone.connectivity?.gps | checkmark}}</dd>
      </dl>
    </li>
    <li>
      <span>Android</span>
      <dl>
        <dt>OS Version</dt>
        <dd>{{phone.android?.os}}</dd>
        <dt>UI</dt>
        <dd>{{phone.android?.ui}}</dd>
      </dl>
    </li>
    <li>
      <span>Size and Weight</span>
      <dl>
        <dt>Dimensions</dt>
        <dd *ngFor="let dim of phone.sizeAndWeight?.dimensions">{{dim}}</dd>
        <dt>Weight</dt>
        <dd>{{phone.sizeAndWeight?.weight}}</dd>
      </dl>
    </li>
    <li>
      <span>Display</span>
      <dl>
        <dt>Screen size</dt>
        <dd>{{phone.display?.screenSize}}</dd>
        <dt>Screen resolution</dt>
        <dd>{{phone.display?.screenResolution}}</dd>
        <dt>Touch screen</dt>
        <dd>{{phone.display?.touchScreen | checkmark}}</dd>
      </dl>
    </li>
    <li>
      <span>Hardware</span>
      <dl>
        <dt>CPU</dt>
        <dd>{{phone.hardware?.cpu}}</dd>
        <dt>USB</dt>
        <dd>{{phone.hardware?.usb}}</dd>
        <dt>Audio / headphone jack</dt>
        <dd>{{phone.hardware?.audioJack}}</dd>
        <dt>FM Radio</dt>
        <dd>{{phone.hardware?.fmRadio | checkmark}}</dd>
        <dt>Accelerometer</dt>
        <dd>{{phone.hardware?.accelerometer | checkmark}}</dd>
      </dl>
    </li>
    <li>
      <span>Camera</span>
      <dl>
        <dt>Primary</dt>
        <dd>{{phone.camera?.primary}}</dd>
        <dt>Features</dt>
        <dd>{{phone.camera?.features?.join(', ')}}</dd>
      </dl>
    </li>
    <li>
      <span>Additional Features</span>
      <dd>{{phone.additionalFeatures}}</dd>
    </li>
  </ul>
</div>

There are several notable changes here:

  • We've removed the $ctrl. prefix from all expressions.
  • Just like we did in the phone list, we've replaced ng-src with property bindings for the standard src property.
  • We're using the property binding syntax around ng-class. Though Angular 2 does have a very similar ngClass as Angular 1 does, its value is not magically evaluated as an expression. In Angular 2 we always specify in the template when an attribute's value is a property expression, as opposed to a literal string.
  • We've replaced ng-repeats with *ngFors.
  • We've replaced ng-click with an event binding for the standard click.
  • We've wrapped the whole template in an ngIf that causes it only to be rendered when there is a phone present. We need this because when the component first loads, we don't have phone yet and the expressions will refer to a non-existing value. Unlike in Angular 1, Angular 2 expressions do not fail silently when we try to refer to properties on undefined objects. We need to be explicit about cases where this is expected.

In main.ts we'll now register a phoneDetail directive instead of a component. The directive is a downgraded version of the PhoneDetail Angular 2 component.

app/main.ts

import { PhoneDetailComponent } from './phone-detail/phone-detail.component';

/* . . . */

angular.module('phoneDetail')
  .directive(
    'phoneDetail',
    <angular.IDirectiveFactory>
      upgradeAdapter.downgradeNg2Component(PhoneDetailComponent)
  );

We should now also remove the phone detail component <script> tag from index.html.

There's one additional step we need to take, which is to upgrade the checkmark filter that the template is using. We need an Angular 2 pipe instead of an Angular 1 filter.

While there is no upgrade method in the upgrade adapter for filters, we can just turn the filter function into a class that fulfills the contract for Angular 2 Pipes. The implementation is the same as before. It just comes in a different kind of packaging. While changing it, also rename the file to checkmark.pipe.ts:

app/core/checkmark/checkmark.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'checkmark'})
export class CheckmarkPipe implements PipeTransform {

  transform(input: boolean) {
    return input ? '\u2713' : '\u2718';
  }

}

In the component we should now import and declare our newly created pipe (as well as remove the filter <script> tag from index.html):

app/phone-detail/phone-detail.component.ts

import { CheckmarkPipe } from '../core/checkmark/checkmark.pipe';

@Component({
  selector: 'phone-detail',
  templateUrl: 'phone-detail/phone-detail.template.html',
  pipes: [ CheckmarkPipe ]
})

Switching To The Angular 2 Router And Bootstrap

At this point we've replaced all our Angular 1 application components with their Angular 2 counterparts. The application is still bootstrapped as a hybrid, but there isn't really any need for that anymore, and we can begin to pull out the last remnants of Angular 1.

There are just two more things to do: We need to switch the router to the Angular 2 one, and then bootstrap the app as a pure Angular 2 app.

Let's do the routing part first. Angular 2 comes with an all-new router that we can use for this.

Angular 2 applications all have a root component, which, among other things, is where we should plug in the router. We don't yet have such a root component, because our app is still managed as an Angular 1 app. Let's change this now and add an AppComponent class into a new file app.component.ts:

app/app.component.ts

import { Component } from '@angular/core';
import { RouteConfig, ROUTER_DIRECTIVES } from '@angular/router-deprecated';
import { PhoneListComponent } from './phone-list/phone-list.component';
import { PhoneDetailComponent } from './phone-detail/phone-detail.component';

@RouteConfig([
  {path: '/phones', name: 'Phones', component: PhoneListComponent},
  {path: '/phones/:phoneId', name: 'Phone', component: PhoneDetailComponent},
  {path: '/', redirectTo: ['Phones']}
])
@Component({
  selector: 'phonecat-app',
  template: '<router-outlet></router-outlet>',
  directives: [ROUTER_DIRECTIVES]
})
export class AppComponent {
}

This is a component that plugs in to an <phonecat-app> element on the page, and has a simple template that only includes the router outlet component of the Angular router. This means that the component just renders the contents of the current route and nothing else. The @RouteConfig decorator defines the Angular 2 counterparts of our two routes. They refer directly to the two components.

We should put this <phonecat-app> element in the HTML so that the root component has something to attach to. It replaces the old Angular 1 ng-view directive:

index.html

  <body>
    <phonecat-app></phonecat-app>
  </body>
</html>

In the PhoneDetail component we now need to change how the phone id parameter is received. There will be no more $routeParams injection available, because that comes from the Angular 1 router. Instead, what we have is a RouteParams object provided by the Angular 2 router. We use it to obtain the phoneId from the params:

app/phone-detail/phone-detail.component.ts

import { Component } from '@angular/core';
import { RouteParams } from '@angular/router-deprecated';
import { Phone, PhoneData } from '../core/phone/phone.service';
import { CheckmarkPipe } from '../core/checkmark/checkmark.pipe';

@Component({
  selector: 'phone-detail',
  templateUrl: 'phone-detail/phone-detail.template.html',
  pipes: [ CheckmarkPipe ]
})
export class PhoneDetailComponent {
  phone: PhoneData;
  mainImageUrl: string;

  constructor(routeParams: RouteParams, phone: Phone) {
    phone.get(routeParams.get('phoneId')).subscribe(phone => {
      this.phone = phone;
      this.setImage(phone.images[0]);
    });
  }

  setImage(imageUrl: string) {
    this.mainImageUrl = imageUrl;
  }
}

With that, we're ready to switch the bootstrap method of the application from that of the UpgradeAdapter to the main Angular 2 bootstrap. Let's import it together with the router, the new app component, and everything else in main.ts

import {
  LocationStrategy,
  HashLocationStrategy,
  APP_BASE_HREF
} from '@angular/common';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { FormsModule } from '@angular/forms';
import { HTTP_PROVIDERS } from '@angular/http';
import { ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { Phone } from './core/phone/phone.service';
import { AppComponent } from './app.component';

We'll now use the regular Angular 2 bootstrap function to bootstrap the app instead of using UpgradeAdapter. The first argument to bootstrap is the application's root component AppComponent, and the second is an array of the Angular 2 providers that we want to make available for injection. In that array we include all the things we have been registering with upgradeAdapter.addProvider until now, as well as the providers and directives of the router:

bootstrap(AppComponent, {
  imports: [FormsModule],
  providers: [
    HTTP_PROVIDERS,
    ROUTER_PROVIDERS,
    { provide: APP_BASE_HREF, useValue: '!' },
    { provide: LocationStrategy, useClass: HashLocationStrategy },
    Phone
  ]
});

We also configure a couple of things for the router here so that the application URL paths match exactly those we had in the Angular 1 app: We want the hash location strategy with the ! prefix: #!/phones.

At this point we are running a pure Angular 2 application!

But there's actually one more cool thing we can do with the new router. We no longer have to hardcode the links to phone details from the phone list, because the Angular 2 router is able to generate them for us with its routerLink directive. We just need to refer to the route names we used in the @RouteConfig:

app/phone-list/phone-list.template.html

<ul class="phones">
  <li *ngFor="let phone of getPhones()"
      class="thumbnail phone-list-item">
    <a [routerLink]="['/Phone', {phoneId: phone.id}]" class="thumb">
      <img [src]="phone.imageUrl" [alt]="phone.name" />
    </a>
    <a [routerLink]="['/Phone', {phoneId: phone.id}]" class="name">{{phone.name}}</a>
    <p>{{phone.snippet}}</p>
  </li>
</ul>

For this to work the directive just needs to be declared in the component:

import { Component } from '@angular/core';
import { RouterLink } from '@angular/router-deprecated';
import { Phone, PhoneData } from '../core/phone/phone.service';

@Component({
  selector: 'phone-list',
  templateUrl: 'phone-list/phone-list.template.html',
  directives: [ RouterLink ]
})

Saying Goodbye to Angular 1

It is time to take off the training wheels and let our application begin its new life as a pure, shiny Angular 2 app. The remaining tasks all have to do with removing code - which of course is every programmer's favorite task!

If you haven't already, remove all references to the UpgradeAdapter from main.ts. Also remove the Angular 1 bootstrap code.

When you're done, this is what main.ts should look like:

app/main.ts

import {
  LocationStrategy,
  HashLocationStrategy,
  APP_BASE_HREF
} from '@angular/common';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { FormsModule } from '@angular/forms';
import { HTTP_PROVIDERS } from '@angular/http';
import { ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { Phone } from './core/phone/phone.service';
import { AppComponent } from './app.component';

bootstrap(AppComponent, {
  imports: [FormsModule],
  providers: [
    HTTP_PROVIDERS,
    ROUTER_PROVIDERS,
    { provide: APP_BASE_HREF, useValue: '!' },
    { provide: LocationStrategy, useClass: HashLocationStrategy },
    Phone
  ]
});

You may also completely remove the following files. They are Angular 1 module configuration files and not needed in Angular 2:

  • app/app.module.ts
  • app/app.config.ts
  • app/core/core.module.ts
  • app/core/phone/phone.module.ts
  • app/phone-detail/phone-detail.module.ts
  • app/phone-list/phone-list.module.ts

The external typings for Angular 1 may be uninstalled as well. The only ones we still need are for Jasmine and Angular 2 polyfills.

npm run typings uninstall jquery -- --save --global
npm run typings uninstall angular -- --save --global
npm run typings uninstall angular-route -- --save --global
npm run typings uninstall angular-resource -- --save --global
npm run typings uninstall angular-mocks -- --save --global
npm run typings uninstall angular-animate -- --save --global

Finally, from index.html, remove all references to Angular 1 scripts, the Angular 2 upgrade module, and jQuery. When we're done, this is what it should look like:

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <base href="/app/">
    <title>Google Phone Gallery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <link rel="stylesheet" href="app.css" />

    <script src="/node_modules/core-js/client/shim.min.js"></script>
    <script src="/node_modules/zone.js/dist/zone.js"></script>
    <script src="/node_modules/reflect-metadata/Reflect.js"></script>
    <script src="/node_modules/systemjs/dist/system.src.js"></script>
    <script src="/systemjs.config.js"></script>
    <script>
      System.import('/app');
    </script>
  </head>
  <body>
    <phonecat-app></phonecat-app>
  </body>
</html>

That is the last we'll see of Angular 1! It has served us well but now it's time to say goodbye.

Appendix: Upgrading PhoneCat Tests

Tests can not only be retained through an upgrade process, but they can also be used as a valuable safety measure when ensuring that the application does not break during the upgrade. E2E tests are especially useful for this purpose.

E2E Tests

The PhoneCat project has both E2E Protractor tests and some Karma unit tests in it. Of these two, E2E tests can be dealt with much more easily: By definition, E2E tests access our application from the outside by interacting with the various UI elements the app puts on the screen. E2E tests aren't really that concerned with the internal structure of the application components. That also means that although we modify our project quite a bit during the upgrade, the E2E test suite should keep passing with just minor modifications. This is because we don't change how the application behaves from the user's point of view.

During TypeScript conversion, there is nothing we have to do to keep E2E tests working. It is only when we start to upgrade components and their template to Angular 2 that we need to make some changes. This is because the E2E tests have matchers that are specific to Angular 1. For PhoneCat we need to make the following changes in order to make things work with Angular 2:

Previous code New code Notes

by.repeater('phone in $ctrl.phones').column('phone.name')

by.css('.phones .name')

The repeater matcher relies on Angular 1 ng-repeat

by.repeater('phone in $ctrl.phones')

by.css('.phones li')

The repeater matcher relies on Angular 1 ng-repeat

by.model('$ctrl.query')

by.css('input')

The model matcher relies on Angular 1 ng-model

by.model('$ctrl.orderProp')

by.css('select')

The model matcher relies on Angular 1 ng-model

by.binding('$ctrl.phone.name')

by.css('h1')

The binding matcher relies on Angular 1 data binding

When the bootstrap method is switched from that of UpgradeAdapter to pure Angular 2, Angular 1 ceases to exist on the page completely. At this point we need to tell Protractor that it should not be looking for an Angular 1 app anymore, but instead it should find Angular 2 apps from the page. The following change is then needed in protractor-conf.js:

useAllAngular2AppRoots: true,

Also, there are a couple of Protractor API calls in the PhoneCat test code that are using the Angular 1 $location service under the hood. As that service is no longer there after the upgrade, we need to replace those calls with ones that use WebDriver's generic URL APIs instead. The first of these is the redirection spec:

e2e-tests/scenarios.ts

BAD FILENAME: ../../../_fragments/upgrade-phonecat-3-final/e2e-spec-redirect.ts.md   Current path: docs,ts,latest,guide,upgrade PathToDocs: ../../../

And the second is the phone links spec:

e2e-tests/scenarios.ts

BAD FILENAME: ../../../_fragments/upgrade-phonecat-3-final/e2e-spec-links.ts.md   Current path: docs,ts,latest,guide,upgrade PathToDocs: ../../../

Unit Tests

For unit tests, on the other hand, more conversion work is needed. Effectively they need to be upgraded along with the production code.

During TypeScript conversion no changes are strictly necessary. But it may be a good idea to convert the unit test code into TypeScript as well, as the same benefits we from TypeScript in production code also applies to tests.

For instance, in the phone detail component spec we can use not only ES2015 features like arrow functions and block-scoped variables, but also type definitions for some of the Angular 1 services we're consuming:

app/phone-detail/phone-detail.component.spec.ts

describe('phoneDetail', () => {

  // Load the module that contains the `phoneDetail` component before each test
  beforeEach(angular.mock.module('phoneDetail'));

  // Test the controller
  describe('PhoneDetailController', () => {
    let $httpBackend: angular.IHttpBackendService;
    let ctrl: any;
    let xyzPhoneData = {
      name: 'phone xyz',
      images: ['image/url1.png', 'image/url2.png']
    };

    beforeEach(inject(($componentController: any,
                       _$httpBackend_: angular.IHttpBackendService,
                       $routeParams: angular.route.IRouteParamsService) => {
      $httpBackend = _$httpBackend_;
      $httpBackend.expectGET('phones/xyz.json').respond(xyzPhoneData);

      $routeParams['phoneId'] = 'xyz';

      ctrl = $componentController('phoneDetail');
    }));

    it('should fetch the phone details', () => {
      jasmine.addCustomEqualityTester(angular.equals);

      expect(ctrl.phone).toEqual({});

      $httpBackend.flush();
      expect(ctrl.phone).toEqual(xyzPhoneData);
    });

  });

});

Once we start the upgrade process and bring in SystemJS, configuration changes are needed for Karma. We need to let SystemJS load all the new Angular 2 code, which can be done with the following kind of shim file:

karma-test-shim.js

// /*global jasmine, __karma__, window*/
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;

__karma__.loaded = function () {
};

function isJsFile(path) {
  return path.slice(-3) == '.js';
}

function isSpecFile(path) {
  return /\.spec\.js$/.test(path);
}

function isBuiltFile(path) {
  var builtPath = '/base/app/';
  return isJsFile(path) && (path.substr(0, builtPath.length) == builtPath);
}

var allSpecFiles = Object.keys(window.__karma__.files)
  .filter(isSpecFile)
  .filter(isBuiltFile);

System.config({
  baseURL: '/base',
  packageWithIndex: true // sadly, we can't use umd packages (yet?)
});

System.import('systemjs.config.js')
  .then(() => Promise.all([
      System.import('@angular/core/testing'),
      System.import('@angular/platform-browser-dynamic/testing')
    ]))
  .then((providers) => {
    var coreTesting = providers[0];
    var browserTesting = providers[1];
    coreTesting.TestBed.initTestEnvironment(
      browserTesting.BrowserDynamicTestingModule,
      browserTesting.platformBrowserDynamicTesting());
  })
  .then(function () {
    // Finally, load all spec files.
    // This will run the tests directly.
    return Promise.all(
      allSpecFiles.map(function (moduleName) {
        return System.import(moduleName);
      }));
  })
  .then(__karma__.start, __karma__.error);

The shim first loads the SystemJS configuration, then Angular 2's test support libraries, and then the application's spec files themselves.

Karma configuration should then be changed so that it uses the application root dir as the base directory, instead of app.

karma.conf.js

basePath: './',

Once this is done, we can load SystemJS and other dependencies, and also switch the configuration for loading application files so that they are not included to the page by Karma. We'll let the shim and SystemJS load them.

karma.conf.js

// System.js for module loading
'node_modules/systemjs/dist/system.src.js',

// Polyfills
'node_modules/core-js/client/shim.js',
'node_modules/reflect-metadata/Reflect.js',

// zone.js
'node_modules/zone.js/dist/zone.js',
'node_modules/zone.js/dist/long-stack-trace-zone.js',
'node_modules/zone.js/dist/proxy.js',
'node_modules/zone.js/dist/sync-test.js',
'node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/zone.js/dist/async-test.js',
'node_modules/zone.js/dist/fake-async-test.js',

// RxJs.
{ pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },

// Angular 2 itself and the testing library
{pattern: 'node_modules/@angular/**/*.js', included: false, watched: false},
{pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false},

{pattern: 'systemjs.config.js', included: false, watched: false},
'karma-test-shim.js',

{pattern: 'app/**/*.module.js', included: false, watched: true},
{pattern: 'app/*!(.module|.spec).js', included: false, watched: true},
{pattern: 'app/!(bower_components)/**/*!(.module|.spec).js', included: false, watched: true},
{pattern: 'app/**/*.spec.js', included: false, watched: true},

{pattern: '**/*.html', included: false, watched: true},

Since the HTML templates of Angular 2 components will be loaded as well, we need to help Karma out a bit so that it can route them to the right paths:

karma.conf.js

// proxied base paths for loading assets
proxies: {
  // required for component assets fetched by Angular's compiler
  "/phone-detail": '/base/app/phone-detail',
  "/phone-list": '/base/app/phone-list'
},

The unit test files themselves also need to be switched to Angular 2 when their production counterparts are switched. The specs for the checkmark pipe are probably the most straightforward, as the pipe has no dependencies:

app/core/checkmark/checkmark.pipe.spec.ts

BAD FILENAME: ../../../_fragments/upgrade-phonecat-2-hybrid/ts/app/core/checkmark/checkmark.pipe.spec.ts.md   Current path: docs,ts,latest,guide,upgrade PathToDocs: ../../../

The unit test for the phone service is a bit more involved. We need to switch from the mocked-out Angular 1 $httpBackend to a mocked-out Angular 2 Http backend.

app/core/phone/phone.service.spec.ts

BAD FILENAME: ../../../_fragments/upgrade-phonecat-2-hybrid/ts/app/core/phone/phone.service.spec.ts.md   Current path: docs,ts,latest,guide,upgrade PathToDocs: ../../../

For the component specs we can mock out the Phone service itself, and have it provide canned phone data. We use Angular's component unit testing APIs for both components.

app/phone-detail/phone-detail.component.spec.ts

BAD FILENAME: ../../../_fragments/upgrade-phonecat-2-hybrid/ts/app/phone-detail/phone-detail.component.spec.ts.md   Current path: docs,ts,latest,guide,upgrade PathToDocs: ../../../

app/phone-list/phone-list.component.spec.ts

BAD FILENAME: ../../../_fragments/upgrade-phonecat-2-hybrid/ts/app/phone-list/phone-list.component.spec.ts.md   Current path: docs,ts,latest,guide,upgrade PathToDocs: ../../../

Finally, we need to revisit both of the component tests when we switch to the Angular 2 router. For the details component we need to provide an Angular 2 RouteParams object instead of using the Angular 1 $routeParams.

app/phone-detail/phone-detail.component.spec.ts

BAD FILENAME: ../../../_fragments/upgrade-phonecat-3-final/ts/app/phone-detail/phone-detail.component.spec-routeparams.ts.md   Current path: docs,ts,latest,guide,upgrade PathToDocs: ../../../

And for the phone list component we need to set up a few things for the router itself so that the route link directive will work.

app/phone-list/phone-list.component.spec.ts

BAD FILENAME: ../../../_fragments/upgrade-phonecat-3-final/ts/app/phone-list/phone-list.component.spec-routestuff.ts.md   Current path: docs,ts,latest,guide,upgrade PathToDocs: ../../../
doc_Angular
2016-10-06 09:47:10
Comments
Leave a Comment

Please login to continue.