{ "id": "guide/upgrade", "title": "Upgrading from AngularJS to Angular", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Upgrading from AngularJS to Angularlink

\n

Angular is the name for the Angular of today and tomorrow.
\nAngularJS is the name for all 1.x versions of Angular.

\n

AngularJS apps are great.\nAlways consider the business case before moving to Angular.\nAn important part of that case is the time and effort to get there.\nThis guide describes the built-in tools for efficiently migrating AngularJS projects over to the\nAngular platform, a piece at a time.

\n

Some applications will be easier to upgrade than others, and there are\nmany ways to make it easier for yourself. It is possible to\nprepare and align AngularJS applications with Angular even before beginning\nthe upgrade process. These preparation steps are all about making the code\nmore decoupled, more maintainable, and better aligned with modern development\ntools. That means in addition to making the upgrade easier,\nyou will also improve the existing AngularJS applications.

\n

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

\n

Preparationlink

\n

There are many ways to structure AngularJS applications. When you begin\nto upgrade these applications to Angular, some will turn out to be\nmuch more easy to work with than others. There are a few key techniques\nand patterns that you can apply to future proof apps even before you\nbegin the migration.

\n\n

Follow the AngularJS Style Guidelink

\n

The AngularJS Style Guide\ncollects patterns and practices that have been proven to result in\ncleaner and more maintainable AngularJS applications. It contains a wealth\nof information about how to write and organize AngularJS code - and equally\nimportantly - how not to write and organize AngularJS code.

\n

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

\n

There are a few rules in particular that will make it much easier to do\nan incremental upgrade using the Angular upgrade/static module:

\n\n

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

\n

Using a Module Loaderlink

\n

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

\n

Using a module loader such as SystemJS,\nWebpack, or Browserify\nallows us to use the built-in module systems of TypeScript or ES2015.\nYou can use the import and export features that explicitly specify what code can\nand will be shared between different parts of the application. For ES5 applications\nyou can use CommonJS style require and module.exports features. In both cases,\nthe module loader will then take care of loading all the code the application needs\nin the correct order.

\n

When moving applications into production, module loaders also make it easier\nto package them all up into production bundles with batteries included.

\n

Migrating to TypeScriptlink

\n

If part of the Angular upgrade plan is to also take TypeScript into use, it makes\nsense to bring in the TypeScript compiler even before the upgrade itself begins.\nThis means there's one less thing to learn and think about during the actual upgrade.\nIt also means you can start using TypeScript features in your AngularJS code.

\n

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

\n\n

Using Component Directiveslink

\n

In Angular, components are the main primitive from which user interfaces\nare built. You define the different portions of the UI as components and\ncompose them into a full user experience.

\n

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

\n

To be Angular compatible, an AngularJS component directive should configure\nthese attributes:

\n\n

Component directives may also use the following attributes:

\n\n

Component directives should not use the following attributes:

\n\n

An AngularJS component directive that is fully aligned with the Angular\narchitecture may look something like this:

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

AngularJS 1.5 introduces the component API\nthat makes it easier to define component directives like these. It is a good idea to use\nthis API for component directives for several reasons:

\n\n

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

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

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

\n

Upgrading with ngUpgradelink

\n

The ngUpgrade library in Angular is a very useful tool for upgrading\nanything but the smallest of applications. With it you can mix and match\nAngularJS and Angular components in the same application and have them interoperate\nseamlessly. That means you don't have to do the upgrade work all at once,\nsince there's a natural coexistence between the two frameworks during the\ntransition period.

\n

How ngUpgrade Workslink

\n

One of the primary tools provided by ngUpgrade is called the UpgradeModule.\nThis is a module that contains utilities for bootstrapping and managing hybrid\napplications that support both Angular and AngularJS code.

\n

When you use ngUpgrade, what you're really doing is running both AngularJS and\nAngular at the same time. All Angular code is running in the Angular\nframework, and AngularJS code in the AngularJS framework. Both of these are the\nactual, fully featured versions of the frameworks. There is no emulation going on,\nso you can expect to have all the features and natural behavior of both frameworks.

\n

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

\n

Dependency Injectionlink

\n

Dependency injection is front and center in both AngularJS and\nAngular, but there are some key differences between the two\nframeworks in how it actually works.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n
\n AngularJS\n \n Angular\n
\n Dependency injection tokens are always strings\n \n

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

\n
\n

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

\n
\n

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

\n
\n

Even accounting for these differences you can still have dependency injection\ninteroperability. upgrade/static resolves the differences and makes\neverything work seamlessly:

\n\n
\n \"The\n
\n

Components and the DOMlink

\n

In the DOM of a hybrid ngUpgrade application are components and\ndirectives from both AngularJS and Angular. These components\ncommunicate with each other by using the input and output bindings\nof their respective frameworks, which ngUpgrade bridges together. They may also\ncommunicate through shared injected dependencies, as described above.

\n

The key thing to understand about a hybrid application is that every element in the DOM is owned by exactly one of the two frameworks.\nThe other framework ignores it. If an element is\nowned by AngularJS, Angular treats it as if it didn't exist,\nand vice versa.

\n

So normally a hybrid application begins life as an AngularJS application,\nand it is AngularJS that processes the root template, e.g. the index.html.\nAngular then steps into the picture when an Angular component is used somewhere\nin an AngularJS template. That component's template will then be managed\nby Angular, and it may contain any number of Angular components and\ndirectives.

\n

Beyond that, you may interleave the two frameworks.\nYou always cross the boundary between the two frameworks by one of two\nways:

\n
    \n
  1. \n

    By using a component from the other framework: An AngularJS template\nusing an Angular component, or an Angular template using an\nAngularJS component.

    \n
  2. \n
  3. \n

    By transcluding or projecting content from the other framework. ngUpgrade\nbridges the related concepts of AngularJS transclusion and Angular content\nprojection together.

    \n
  4. \n
\n
\n \"DOM\n
\n

Whenever you use a component that belongs to the other framework, a\nswitch between framework boundaries occurs. However, that switch only\nhappens to the elements in the template of that component. Consider a situation\nwhere you use an Angular component from AngularJS like this:

\n\n <a-component></a-component>\n\n

The DOM element <a-component> will remain to be an AngularJS managed\nelement, because it's defined in an AngularJS template. That also\nmeans you can apply additional AngularJS directives to it, but not\nAngular directives. It is only in the template of the <a-component>\nwhere Angular steps in. This same rule also applies when you\nuse AngularJS component directives from Angular.

\n

Change Detectionlink

\n

The scope.$apply() is how AngularJS detects changes and updates data bindings.\nAfter every event that occurs, scope.$apply() gets called. This is done either\nautomatically by the framework, or manually by you.

\n

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

\n

In the case of hybrid applications, the UpgradeModule bridges the\nAngularJS and Angular approaches. Here's what happens:

\n\n
\n \"Change\n
\n

In practice, you do not need to call $apply(),\nregardless of whether it is in AngularJS or Angular. The\nUpgradeModule does it for us. You can still call $apply() so there\nis no need to remove such calls from existing code. Those calls just trigger\nadditional AngularJS change detection checks in a hybrid application.

\n

When you downgrade an Angular component and then use it from AngularJS,\nthe component's inputs will be watched using AngularJS change detection.\nWhen those inputs change, the corresponding properties in the component\nare set. You can also hook into the changes by implementing the\nOnChanges interface in the component,\njust like you could if it hadn't been downgraded.

\n

Correspondingly, when you upgrade an AngularJS component and use it from Angular,\nall the bindings defined for the component directive's scope (or bindToController)\nwill be hooked into Angular change detection. They will be treated\nas regular Angular inputs. Their values will be written to the upgraded component's\nscope (or controller) when they change.

\n

Using UpgradeModule with Angular NgModuleslink

\n

Both AngularJS and Angular have their own concept of modules\nto help organize an application into cohesive blocks of functionality.

\n

Their details are quite different in architecture and implementation.\nIn AngularJS, you add Angular assets to the angular.module property.\nIn Angular, you create one or more classes adorned with an NgModule decorator\nthat describes Angular assets in metadata. The differences blossom from there.

\n

In a hybrid application you run both versions of Angular at the same time.\nThat means that you need at least one module each from both AngularJS and Angular.\nYou will import UpgradeModule inside the NgModule, and then use it for\nbootstrapping the AngularJS module.

\n
\n

For more information, see NgModules.

\n
\n

Bootstrapping hybrid applicationslink

\n

To bootstrap a hybrid application, you must bootstrap each of the Angular and\nAngularJS parts of the application. You must bootstrap the Angular bits first and\nthen ask the UpgradeModule to bootstrap the AngularJS bits next.

\n

In an AngularJS application you have a root AngularJS module, which will also\nbe used to bootstrap the AngularJS application.

\n\nangular.module('heroApp', [])\n .controller('MainCtrl', function() {\n this.message = 'Hello world';\n });\n\n\n

Pure AngularJS applications can be automatically bootstrapped by using an ng-app\ndirective somewhere on the HTML page. But for hybrid applications, you manually bootstrap via the\nUpgradeModule. Therefore, it is a good preliminary step to switch AngularJS applications to use the\nmanual JavaScript angular.bootstrap\nmethod even before switching them to hybrid mode.

\n

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

\n\n<!DOCTYPE HTML>\n<html lang=\"en\">\n <head>\n <base href=\"/\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js\"></script>\n <script src=\"app/ajs-ng-app/app.module.js\"></script>\n </head>\n\n <body ng-app=\"heroApp\" ng-strict-di>\n <div id=\"message\" ng-controller=\"MainCtrl as mainCtrl\">\n {{ mainCtrl.message }}\n </div>\n </body>\n</html>\n\n\n\n

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

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

To begin converting your AngularJS application to a hybrid, you need to load the Angular framework.\nYou can see how this can be done with SystemJS by following the instructions in Setup for Upgrading to AngularJS for selectively copying code from the QuickStart github repository.

\n

You also need to install the @angular/upgrade package via npm install @angular/upgrade --save\nand add a mapping for the @angular/upgrade/static package:

\n\n'@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',\n\n\n

Next, create an app.module.ts file and add the following NgModule class:

\n\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { UpgradeModule } from '@angular/upgrade/static';\n\n@NgModule({\n imports: [\n BrowserModule,\n UpgradeModule\n ]\n})\nexport class AppModule {\n constructor(private upgrade: UpgradeModule) { }\n ngDoBootstrap() {\n this.upgrade.bootstrap(document.body, ['heroApp'], { strictDi: true });\n }\n}\n\n\n

This bare minimum NgModule imports BrowserModule, the module every Angular browser-based app must have.\nIt also imports UpgradeModule from @angular/upgrade/static, which exports providers that will be used\nfor upgrading and downgrading services and components.

\n

In the constructor of the AppModule, use dependency injection to get a hold of the UpgradeModule instance,\nand use it to bootstrap the AngularJS app in the AppModule.ngDoBootstrap method.\nThe upgrade.bootstrap method takes the exact same arguments as angular.bootstrap:

\n
\n

Note that you do not add a bootstrap declaration to the @NgModule decorator, since\nAngularJS will own the root template of the application.

\n
\n

Now you can bootstrap AppModule using the platformBrowserDynamic.bootstrapModule method.

\n\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\nplatformBrowserDynamic().bootstrapModule(AppModule);\n\n\n

Congratulations! You're running a hybrid application! The\nexisting AngularJS code works as before and you're ready to start adding Angular code.

\n

Using Angular Components from AngularJS Codelink

\n\"Using\n

Once you're running a hybrid app, you can start the gradual process of upgrading\ncode. One of the more common patterns for doing that is to use an Angular component\nin an AngularJS context. This could be a completely new component or one that was\npreviously AngularJS but has been rewritten for Angular.

\n

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

\n\nimport { Component } from '@angular/core';\n\n@Component({\n selector: 'hero-detail',\n template: `\n <h2>Windstorm details!</h2>\n <div><label>id: </label>1</div>\n `\n})\nexport class HeroDetailComponent { }\n\n\n\n

If you want to use this component from AngularJS, you need to downgrade it\nusing the downgradeComponent() method. The result is an AngularJS\ndirective, which you can then register in the AngularJS module:

\n\nimport { HeroDetailComponent } from './hero-detail.component';\n\n/* . . . */\n\nimport { downgradeComponent } from '@angular/upgrade/static';\n\nangular.module('heroApp', [])\n .directive(\n 'heroDetail',\n downgradeComponent({ component: HeroDetailComponent }) as angular.IDirectiveFactory\n );\n\n\n\n
\n

By default, Angular change detection will also run on the component for every\nAngularJS $digest cycle. If you wish to only have change detection run when\nthe inputs change, you can set propagateDigest to false when calling\ndowngradeComponent().

\n
\n

Because HeroDetailComponent is an Angular component, you must also add it to the\ndeclarations in the AppModule.

\n

And because this component is being used from the AngularJS module, and is an entry point into\nthe Angular application, you must add it to the entryComponents for the\nNgModule.

\n\nimport { HeroDetailComponent } from './hero-detail.component';\n\n@NgModule({\n imports: [\n BrowserModule,\n UpgradeModule\n ],\n declarations: [\n HeroDetailComponent\n ],\n entryComponents: [\n HeroDetailComponent\n ]\n})\nexport class AppModule {\n constructor(private upgrade: UpgradeModule) { }\n ngDoBootstrap() {\n this.upgrade.bootstrap(document.body, ['heroApp'], { strictDi: true });\n }\n}\n\n\n
\n

All Angular components, directives and pipes must be declared in an NgModule.

\n
\n

The net result is an AngularJS directive called heroDetail, that you can\nuse like any other directive in AngularJS templates.

\n\n<hero-detail></hero-detail>\n\n\n
\n

Note that this AngularJS is an element directive (restrict: 'E') called heroDetail.\nAn AngularJS element directive is matched based on its name.\nThe selector metadata of the downgraded Angular component is ignored.

\n
\n

Most components are not quite this simple, of course. Many of them\nhave inputs and outputs that connect them to the outside world. An\nAngular hero detail component with inputs and outputs might look\nlike this:

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

These inputs and outputs can be supplied from the AngularJS template, and the\ndowngradeComponent() method takes care of wiring them up:

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

Note that even though you are in an AngularJS template, you're using Angular\nattribute syntax to bind the inputs and outputs. This is a requirement for downgraded\ncomponents. The expressions themselves are still regular AngularJS expressions.

\n
\n
\n Use kebab-case for downgraded component attributes\n
\n

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

\n\n [myHero]=\"hero\"\n (heroDeleted)=\"handleHeroDeleted($event)\"\n\n

But when using them from AngularJS templates, you must use kebab-case:

\n\n [my-hero]=\"hero\"\n (hero-deleted)=\"handleHeroDeleted($event)\"\n\n
\n

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

\n

Since this is an AngularJS template, you can still use other AngularJS\ndirectives on the element, even though it has Angular binding attributes on it.\nFor example, you can easily make multiple copies of the component using ng-repeat:

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

Using AngularJS Component Directives from Angular Codelink

\n\"Using\n

So, you can write an Angular component and then use it from AngularJS\ncode. This is useful when you start to migrate from lower-level\ncomponents and work your way up. But in some cases it is more convenient\nto do things in the opposite order: To start with higher-level components\nand work your way down. This too can be done using the upgrade/static.\nYou can upgrade AngularJS component directives and then use them from\nAngular.

\n

Not all kinds of AngularJS directives can be upgraded. The directive\nreally has to be a component directive, with the characteristics\ndescribed in the preparation guide above.\nThe safest bet for ensuring compatibility is using the\ncomponent API\nintroduced in AngularJS 1.5.

\n

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

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

You can upgrade this component to Angular using the UpgradeComponent class.\nBy creating a new Angular directive that extends UpgradeComponent and doing a super call\ninside its constructor, you have a fully upgraded AngularJS component to be used inside Angular.\nAll that is left is to add it to AppModule's declarations array.

\n\nimport { Directive, ElementRef, Injector, SimpleChanges } from '@angular/core';\nimport { UpgradeComponent } from '@angular/upgrade/static';\n\n@Directive({\n selector: 'hero-detail'\n})\nexport class HeroDetailDirective extends UpgradeComponent {\n constructor(elementRef: ElementRef, injector: Injector) {\n super('heroDetail', elementRef, injector);\n }\n}\n\n\n\n@NgModule({\n imports: [\n BrowserModule,\n UpgradeModule\n ],\n declarations: [\n HeroDetailDirective,\n/* . . . */\n ]\n})\nexport class AppModule {\n constructor(private upgrade: UpgradeModule) { }\n ngDoBootstrap() {\n this.upgrade.bootstrap(document.body, ['heroApp'], { strictDi: true });\n }\n}\n\n\n
\n

Upgraded components are Angular directives, instead of components, because Angular\nis unaware that AngularJS will create elements under it. As far as Angular knows, the upgraded\ncomponent is just a directive - a tag - and Angular doesn't have to concern itself with\nits children.

\n
\n

An upgraded component may also have inputs and outputs, as defined by\nthe scope/controller bindings of the original AngularJS component\ndirective. When you use the component from an Angular template,\nprovide the inputs and outputs using Angular template syntax,\nobserving the following rules:

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n Binding definition\n \n Template syntax\n
\n Attribute binding\n \n

myAttribute: '@myAttribute'

\n
\n

<my-component myAttribute=\"value\">

\n
\n Expression binding\n \n

myOutput: '&myOutput'

\n
\n

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

\n
\n One-way binding\n \n

myValue: '<myValue'

\n
\n

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

\n
\n Two-way binding\n \n

myValue: '=myValue'

\n
\n

As a two-way binding: <my-component [(myValue)]=\"anExpression\">.\nSince most AngularJS two-way bindings actually only need a one-way binding\nin practice, <my-component [myValue]=\"anExpression\"> is often enough.

\n
\n

For example, imagine a hero detail AngularJS component directive\nwith one input and one output:

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

You can upgrade this component to Angular, annotate inputs and outputs in the upgrade directive,\nand then provide the input and output using Angular template syntax:

\n\nimport { Directive, ElementRef, Injector, Input, Output, EventEmitter } from '@angular/core';\nimport { UpgradeComponent } from '@angular/upgrade/static';\nimport { Hero } from '../hero';\n\n@Directive({\n selector: 'hero-detail'\n})\nexport class HeroDetailDirective extends UpgradeComponent {\n @Input() hero: Hero;\n @Output() deleted: EventEmitter<Hero>;\n\n constructor(elementRef: ElementRef, injector: Injector) {\n super('heroDetail', elementRef, injector);\n }\n}\n\n\n\nimport { Component } from '@angular/core';\nimport { Hero } from '../hero';\n\n@Component({\n selector: 'my-container',\n template: `\n <h1>Tour of Heroes</h1>\n <hero-detail [hero]=\"hero\"\n (deleted)=\"heroDeleted($event)\">\n </hero-detail>\n `\n})\nexport class ContainerComponent {\n hero = new Hero(1, 'Windstorm');\n heroDeleted(hero: Hero) {\n hero.name = 'Ex-' + hero.name;\n }\n}\n\n\n\n

Projecting AngularJS Content into Angular Componentslink

\n\"Projecting\n

When you are using a downgraded Angular component from an AngularJS\ntemplate, the need may arise to transclude some content into it. This\nis also possible. While there is no such thing as transclusion in Angular,\nthere is a very similar concept called content projection. upgrade/static\nis able to make these two features interoperate.

\n

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

\n\nimport { Component, Input } from '@angular/core';\nimport { Hero } from '../hero';\n\n@Component({\n selector: 'hero-detail',\n template: `\n <h2>{{hero.name}}</h2>\n <div>\n <ng-content></ng-content>\n </div>\n `\n})\nexport class HeroDetailComponent {\n @Input() hero: Hero;\n}\n\n\n\n

When using the component from AngularJS, you can supply contents for it. Just\nlike they would be transcluded in AngularJS, they get projected to the location\nof the <ng-content> tag in Angular:

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

When AngularJS content gets projected inside an Angular component, it still\nremains in \"AngularJS land\" and is managed by the AngularJS framework.

\n
\n

Transcluding Angular Content into AngularJS Component Directiveslink

\n\"Projecting\n

Just as you can project AngularJS content into Angular components,\nyou can transclude Angular content into AngularJS components, whenever\nyou are using upgraded versions from them.

\n

When an AngularJS component directive supports transclusion, it may use\nthe ng-transclude directive in its template to mark the transclusion\npoint:

\n\nexport const heroDetail = {\n bindings: {\n hero: '='\n },\n template: `\n <h2>{{$ctrl.hero.name}}</h2>\n <div>\n <ng-transclude></ng-transclude>\n </div>\n `,\n transclude: true\n};\n\n\n

If you upgrade this component and use it from Angular, you can populate\nthe component tag with contents that will then get transcluded:

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

Making AngularJS Dependencies Injectable to Angularlink

\n

When running a hybrid app, you may encounter situations where you need to inject\nsome AngularJS dependencies into your Angular code.\nMaybe you have some business logic still in AngularJS services.\nMaybe you want access to AngularJS's built-in services like $location or $timeout.

\n

In these situations, it is possible to upgrade an AngularJS provider to\nAngular. This makes it possible to then inject it somewhere in Angular\ncode. For example, you might have a service called HeroesService in AngularJS:

\n\nimport { Hero } from '../hero';\n\nexport class HeroesService {\n get() {\n return [\n new Hero(1, 'Windstorm'),\n new Hero(2, 'Spiderman')\n ];\n }\n}\n\n\n\n

You can upgrade the service using a Angular factory provider\nthat requests the service from the AngularJS $injector.

\n

Many developers prefer to declare the factory provider in a separate ajs-upgraded-providers.ts file\nso that they are all together, making it easier to reference them, create new ones and\ndelete them once the upgrade is over.

\n

It's also recommended to export the heroesServiceFactory function so that Ahead-of-Time\ncompilation can pick it up.

\n
\n

Note: The 'heroes' string inside the factory refers to the AngularJS HeroesService.\nIt is common in AngularJS apps to choose a service name for the token, for example \"heroes\",\nand append the \"Service\" suffix to create the class name.

\n
\n\nimport { HeroesService } from './heroes.service';\n\nexport function heroesServiceFactory(i: any) {\n return i.get('heroes');\n}\n\nexport const heroesServiceProvider = {\n provide: HeroesService,\n useFactory: heroesServiceFactory,\n deps: ['$injector']\n};\n\n\n\n

You can then provide the service to Angular by adding it to the @NgModule:

\n\nimport { heroesServiceProvider } from './ajs-upgraded-providers';\n\n@NgModule({\n imports: [\n BrowserModule,\n UpgradeModule\n ],\n providers: [\n heroesServiceProvider\n ],\n/* . . . */\n})\nexport class AppModule {\n constructor(private upgrade: UpgradeModule) { }\n ngDoBootstrap() {\n this.upgrade.bootstrap(document.body, ['heroApp'], { strictDi: true });\n }\n}\n\n\n

Then use the service inside your component by injecting it in the component constructor using its class as a type annotation:

\n\nimport { Component } from '@angular/core';\nimport { HeroesService } from './heroes.service';\nimport { Hero } from '../hero';\n\n@Component({\n selector: 'hero-detail',\n template: `\n <h2>{{hero.id}}: {{hero.name}}</h2>\n `\n})\nexport class HeroDetailComponent {\n hero: Hero;\n constructor(heroes: HeroesService) {\n this.hero = heroes.get()[0];\n }\n}\n\n\n\n
\n

In this example you upgraded a service class.\nYou can use a TypeScript type annotation when you inject it. While it doesn't\naffect how the dependency is handled, it enables the benefits of static type\nchecking. This is not required though, and any AngularJS service, factory, or\nprovider can be upgraded.

\n
\n

Making Angular Dependencies Injectable to AngularJSlink

\n

In addition to upgrading AngularJS dependencies, you can also downgrade\nAngular dependencies, so that you can use them from AngularJS. This can be\nuseful when you start migrating services to Angular or creating new services\nin Angular while retaining components written in AngularJS.

\n

For example, you might have an Angular service called Heroes:

\n\nimport { Injectable } from '@angular/core';\nimport { Hero } from '../hero';\n\n@Injectable()\nexport class Heroes {\n get() {\n return [\n new Hero(1, 'Windstorm'),\n new Hero(2, 'Spiderman')\n ];\n }\n}\n\n\n\n

Again, as with Angular components, register the provider with the NgModule by adding it to the module's providers list.

\n\nimport { Heroes } from './heroes';\n\n@NgModule({\n imports: [\n BrowserModule,\n UpgradeModule\n ],\n providers: [ Heroes ]\n})\nexport class AppModule {\n constructor(private upgrade: UpgradeModule) { }\n ngDoBootstrap() {\n this.upgrade.bootstrap(document.body, ['heroApp'], { strictDi: true });\n }\n}\n\n\n

Now wrap the Angular Heroes in an AngularJS factory function using downgradeInjectable()\nand plug the factory into an AngularJS module.\nThe name of the AngularJS dependency is up to you:

\n\nimport { Heroes } from './heroes';\n/* . . . */\nimport { downgradeInjectable } from '@angular/upgrade/static';\n\nangular.module('heroApp', [])\n .factory('heroes', downgradeInjectable(Heroes))\n .component('heroDetail', heroDetailComponent);\n\n\n

After this, the service is injectable anywhere in AngularJS code:

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

Lazy Loading AngularJSlink

\n

When building applications, you want to ensure that only the required resources are loaded when necessary. Whether that be loading of assets or code, making sure everything that can be deferred until needed keeps your application running efficiently. This is especially true when running different frameworks in the same application.

\n

Lazy loading is a technique that defers the loading of required assets and code resources until they are actually used. This reduces startup time and increases efficiency, especially when running different frameworks in the same application.

\n

When migrating large applications from AngularJS to Angular using a hybrid approach, you want to migrate some of the most commonly used features first, and only use the less commonly used features if needed. Doing so helps you ensure that the application is still providing a seamless experience for your users while you are migrating.

\n

In most environments where both Angular and AngularJS are used to render the application, both frameworks are loaded in the initial bundle being sent to the client. This results in both increased bundle size and possible reduced performance.

\n

Overall application performance is affected in cases where the user stays on Angular-rendered pages because the AngularJS framework and application are still loaded and running, even if they are never accessed.

\n

You can take steps to mitigate both bundle size and performance issues. By isolating your AngularJS app to a separate bundle, you can take advantage of lazy loading to load, bootstrap, and render the AngularJS application only when needed. This strategy reduces your initial bundle size, defers any potential impact from loading both frameworks until absolutely necessary, and keeps your application running as efficiently as possible.

\n

The steps below show you how to do the following:

\n\n

Create a service to lazy load AngularJSlink

\n

As of Angular version 8, lazy loading code can be accomplished simply by using the dynamic import syntax import('...'). In your application, you create a new service that uses dynamic imports to lazy load AngularJS.

\n\nimport { Injectable } from '@angular/core';\nimport * as angular from 'angular';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class LazyLoaderService {\n private app: angular.auto.IInjectorService;\n\n load(el: HTMLElement): void {\n import('./angularjs-app').then(app => {\n try {\n this.app = app.bootstrap(el);\n } catch (e) {\n console.error(e);\n }\n });\n }\n\n destroy() {\n if (this.app) {\n this.app.get('$rootScope').$destroy();\n }\n }\n}\n\n\n\n

The service uses the import() method to load your bundled AngularJS application lazily. This decreases the initial bundle size of your application as you're not loading code your user doesn't need yet. You also need to provide a way to bootstrap the application manually after it has been loaded. AngularJS provides a way to manually bootstrap an application using the angular.bootstrap() method with a provided HTML element. Your AngularJS app should also expose a bootstrap method that bootstraps the AngularJS app.

\n

To ensure any necessary teardown is triggered in the AngularJS app, such as removal of global listeners, you also implement a method to call the $rootScope.destroy() method.

\n\nimport * as angular from 'angular';\nimport 'angular-route';\n\nconst appModule = angular.module('myApp', [\n 'ngRoute'\n])\n.config(['$routeProvider', '$locationProvider',\n function config($routeProvider, $locationProvider) {\n $locationProvider.html5Mode(true);\n\n $routeProvider.\n when('/users', {\n template: `\n <p>\n Users Page\n </p>\n `\n }).\n otherwise({\n template: ''\n });\n }]\n);\n\nexport function bootstrap(el: HTMLElement) {\n return angular.bootstrap(el, [appModule.name]);\n}\n\n\n\n

Your AngularJS application is configured with only the routes it needs to render content. The remaining routes in your application are handled by the Angular Router. The exposed bootstrap method is called in your Angular app to bootstrap the AngularJS application after the bundle is loaded.

\n
\n

Note: After AngularJS is loaded and bootstrapped, listeners such as those wired up in your route configuration will continue to listen for route changes. To ensure listeners are shut down when AngularJS isn't being displayed, configure an otherwise option with the $routeProvider that renders an empty template. This assumes all other routes will be handled by Angular.

\n
\n

Create a component to render AngularJS contentlink

\n

In your Angular application, you need a component as a placeholder for your AngularJS content. This component uses the service you create to load and bootstrap your AngularJS app after the component is initialized.

\n\nimport { Component, OnInit, OnDestroy, ElementRef } from '@angular/core';\nimport { LazyLoaderService } from '../lazy-loader.service';\n\n@Component({\n selector: 'app-angular-js',\n template: '<div ng-view></div>'\n})\nexport class AngularJSComponent implements OnInit, OnDestroy {\n constructor(\n private lazyLoader: LazyLoaderService,\n private elRef: ElementRef\n ) {}\n\n ngOnInit() {\n this.lazyLoader.load(this.elRef.nativeElement);\n }\n\n\n ngOnDestroy() {\n this.lazyLoader.destroy();\n }\n}\n\n\n\n

When the Angular Router matches a route that uses AngularJS, the AngularJSComponent is rendered, and the content is rendered within the AngularJS ng-view directive. When the user navigates away from the route, the $rootScope is destroyed on the AngularJS application.

\n

Configure a custom route matcher for AngularJS routeslink

\n

To configure the Angular Router, you must define a route for AngularJS URLs. To match those URLs, you add a route configuration that uses the matcher property. The matcher allows you to use custom pattern matching for URL paths. The Angular Router tries to match on more specific routes such as static and variable routes first. When it doesn't find a match, it then looks at custom matchers defined in your route configuration. If the custom matchers don't match a route, it then goes to catch-all routes, such as a 404 page.

\n

The following example defines a custom matcher function for AngularJS routes.

\n\nexport function isAngularJSUrl(url: UrlSegment[]) {\n return url.length > 0 && url[0].path.startsWith('users') ? ({consumed: url}) : null;\n}\n\n\n

The following code adds a route object to your routing configuration using the matcher property and custom matcher, and the component property with AngularJSComponent.

\n\nimport { NgModule } from '@angular/core';\nimport { Routes, RouterModule, UrlSegment } from '@angular/router';\nimport { AngularJSComponent } from './angular-js/angular-js.component';\nimport { HomeComponent } from './home/home.component';\nimport { App404Component } from './app404/app404.component';\n\n// Match any URL that starts with `users`\nexport function isAngularJSUrl(url: UrlSegment[]) {\n return url.length > 0 && url[0].path.startsWith('users') ? ({consumed: url}) : null;\n}\n\nexport const routes: Routes = [\n // Routes rendered by Angular\n { path: '', component: HomeComponent },\n\n // AngularJS routes\n { matcher: isAngularJSUrl, component: AngularJSComponent },\n\n // Catch-all route\n { path: '**', component: App404Component }\n];\n\n@NgModule({\n imports: [RouterModule.forRoot(routes)],\n exports: [RouterModule]\n})\nexport class AppRoutingModule { }\n\n\n\n

When your application matches a route that needs AngularJS, the AngularJS app is loaded and bootstrapped, the AngularJS routes match the necessary URL to render their content, and your application continues to run with both AngularJS and Angular frameworks.

\n

Using the Unified Angular Location Servicelink

\n

In AngularJS, the $location service handles all routing configuration and navigation, encoding and decoding of URLS, redirects, and interactions with browser APIs. Angular uses its own underlying Location service for all of these tasks.

\n

When you migrate from AngularJS to Angular you will want to move as much responsibility as possible to Angular, so that you can take advantage of new APIs. To help with the transition, Angular provides the LocationUpgradeModule. This module enables a unified location service that shifts responsibilities from the AngularJS $location service to the Angular Location service.

\n

To use the LocationUpgradeModule, import the symbol from @angular/common/upgrade and add it to your AppModule imports using the static LocationUpgradeModule.config() method.

\n\n// Other imports ...\nimport { LocationUpgradeModule } from '@angular/common/upgrade';\n\n@NgModule({\n imports: [\n // Other NgModule imports...\n LocationUpgradeModule.config()\n ]\n})\nexport class AppModule {}\n\n

The LocationUpgradeModule.config() method accepts a configuration object that allows you to configure options including the LocationStrategy with the useHash property, and the URL prefix with the hashPrefix property.

\n

The useHash property defaults to false, and the hashPrefix defaults to an empty string. Pass the configuration object to override the defaults.

\n\nLocationUpgradeModule.config({\n useHash: true,\n hashPrefix: '!'\n})\n\n
\n

Note: See the LocationUpgradeConfig for more configuration options available to the LocationUpgradeModule.config() method.

\n
\n

This registers a drop-in replacement for the $location provider in AngularJS. Once registered, all navigation, routing broadcast messages, and any necessary digest cycles in AngularJS triggered during navigation are handled by Angular. This gives you a single way to navigate within both sides of your hybrid application consistently.

\n

For usage of the $location service as a provider in AngularJS, you need to downgrade the $locationShim using a factory provider.

\n\n// Other imports ...\nimport { $locationShim } from '@angular/common/upgrade';\nimport { downgradeInjectable } from '@angular/upgrade/static';\n\nangular.module('myHybridApp', [...])\n .factory('$location', downgradeInjectable($locationShim));\n\n

Once you introduce the Angular Router, using the Angular Router triggers navigations through the unified location service, still providing a single source for navigating with AngularJS and Angular.

\n\n

PhoneCat Upgrade Tutoriallink

\n

In this section, you'll learn to prepare and upgrade an application with ngUpgrade.\nThe example app is Angular PhoneCat\nfrom the original AngularJS tutorial,\nwhich is where many of us began our Angular adventures. Now you'll see how to\nbring that application to the brave new world of Angular.

\n

During the process you'll learn how to apply the steps outlined in the\npreparation guide. You'll align the application\nwith Angular and also start writing in TypeScript.

\n

To follow along with the tutorial, clone the\nangular-phonecat repository\nand apply the steps as you go.

\n

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

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

This is actually a pretty good starting point. The code uses the AngularJS 1.5\ncomponent API and the organization follows the\nAngularJS Style Guide,\nwhich is an important preparation step before\na successful upgrade.

\n\n

Switching to TypeScriptlink

\n

Since you're going to be writing Angular code in TypeScript, it makes sense to\nbring in the TypeScript compiler even before you begin upgrading.

\n

You'll also start to gradually phase out the Bower package manager in favor\nof NPM, installing all new dependencies using NPM, and eventually removing Bower from the project.

\n

Begin by installing TypeScript to the project.

\n\n npm i typescript --save-dev\n\n

Install type definitions for the existing libraries that\nyou're using but that don't come with prepackaged types: AngularJS, AngularJS Material, and the\nJasmine unit test framework.

\n

For the PhoneCat app, we can install the necessary type definitions by running the following command:

\n\n npm install @types/jasmine @types/angular @types/angular-animate @types/angular-aria @types/angular-cookies @types/angular-mocks @types/angular-resource @types/angular-route @types/angular-sanitize --save-dev\n\n

If you are using AngularJS Material, you can install the type definitions via:

\n\n npm install @types/angular-material --save-dev\n\n

You should also configure the TypeScript compiler with a tsconfig.json in the project directory\nas described in the TypeScript Configuration guide.\nThe tsconfig.json file tells the TypeScript compiler how to turn your TypeScript files\ninto ES5 code bundled into CommonJS modules.

\n

Finally, you should add some npm scripts in package.json to compile the TypeScript files to\nJavaScript (based on the tsconfig.json configuration file):

\n\n \"scripts\": {\n \"tsc\": \"tsc\",\n \"tsc:w\": \"tsc -w\",\n ...\n\n

Now launch the TypeScript compiler from the command line in watch mode:

\n\n npm run tsc:w\n\n

Keep this process running in the background, watching and recompiling as you make changes.

\n

Next, convert your current JavaScript files into TypeScript. Since\nTypeScript is a super-set of ECMAScript 2015, which in turn is a super-set\nof ECMAScript 5, you can simply switch the file extensions from .js to .ts\nand everything will work just like it did before. As the TypeScript compiler\nruns, it emits the corresponding .js file for every .ts file and the\ncompiled JavaScript is what actually gets executed. If you start\nthe project HTTP server with npm start, you should see the fully functional\napplication in your browser.

\n

Now that you have TypeScript though, you can start benefiting from some of its\nfeatures. There's a lot of value the language can provide to AngularJS applications.

\n

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

\n

Another thing you can do is start adding type safety to your code. This has\nactually partially already happened because of the AngularJS typings you installed.\nTypeScript are checking that you are calling AngularJS APIs correctly when you do\nthings like register components to Angular modules.

\n

But you can also start adding type annotations to get even more\nout of TypeScript's type system. For instance, you can annotate the checkmark\nfilter so that it explicitly expects booleans as arguments. This makes it clearer\nwhat the filter is supposed to do.

\n\nangular.\n module('core').\n filter('checkmark', () => {\n return (input: boolean) => input ? '\\u2713' : '\\u2718';\n });\n\n\n\n

In the Phone service, you can explicitly annotate the $resource service dependency\nas an angular.resource.IResourceService - a type defined by the AngularJS typings.

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

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

\n\nangular.\n module('phonecatApp').\n config(['$locationProvider', '$routeProvider',\n function config($locationProvider: angular.ILocationProvider,\n $routeProvider: angular.route.IRouteProvider) {\n $locationProvider.hashPrefix('!');\n\n $routeProvider.\n when('/phones', {\n template: '<phone-list></phone-list>'\n }).\n when('/phones/:phoneId', {\n template: '<phone-detail></phone-detail>'\n }).\n otherwise('/phones');\n }\n ]);\n\n\n\n
\n

The AngularJS 1.x type definitions\nyou installed are not officially maintained by the Angular team,\nbut are quite comprehensive. It is possible to make an AngularJS 1.x application\nfully type-annotated with the help of these definitions.

\n

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

\n
\n

Another TypeScript feature you can make use of is classes. In particular, you\ncan turn component controllers into classes. That way they'll be a step\ncloser to becoming Angular component classes, which will make life\neasier once you upgrade.

\n

AngularJS expects controllers to be constructor functions. That's exactly what\nES2015/TypeScript classes are under the hood, so that means you can just plug in a\nclass as a component controller and AngularJS will happily use it.

\n

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

\n\nclass PhoneListController {\n phones: any[];\n orderProp: string;\n query: string;\n\n static $inject = ['Phone'];\n constructor(Phone: any) {\n this.phones = Phone.query();\n this.orderProp = 'age';\n }\n\n}\n\nangular.\n module('phoneList').\n component('phoneList', {\n templateUrl: 'phone-list/phone-list.template.html',\n controller: PhoneListController\n });\n\n\n\n

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

\n

The class additionally declares three members: The array of phones, the name of\nthe current sort key, and the search query. These are all things you have already\nbeen attaching to the controller but that weren't explicitly declared anywhere.\nThe last one of these isn't actually used in the TypeScript code since it's only\nreferred to in the template, but for the sake of clarity you should define all of the\ncontroller members.

\n

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

\n\nclass PhoneDetailController {\n phone: any;\n mainImageUrl: string;\n\n static $inject = ['$routeParams', 'Phone'];\n constructor($routeParams: angular.route.IRouteParamsService, Phone: any) {\n const phoneId = $routeParams.phoneId;\n this.phone = Phone.get({phoneId}, (phone: any) => {\n this.setImage(phone.images[0]);\n });\n }\n\n setImage(imageUrl: string) {\n this.mainImageUrl = imageUrl;\n }\n}\n\nangular.\n module('phoneDetail').\n component('phoneDetail', {\n templateUrl: 'phone-detail/phone-detail.template.html',\n controller: PhoneDetailController\n });\n\n\n\n

This makes the controller code look a lot more like Angular already. You're\nall set to actually introduce Angular into the project.

\n

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

\n

Installing Angularlink

\n

Having completed the preparation work, get going with the Angular\nupgrade of PhoneCat. You'll do this incrementally with the help of\nngUpgrade that comes with Angular.\nBy the time you're done, you'll be able to remove AngularJS from the project\ncompletely, but the key is to do this piece by piece without breaking the application.

\n
\n

The project also contains some animations.\nYou won't upgrade them in this version of the guide.\nTurn to the Angular animations guide to learn about that.

\n
\n

Install Angular into the project, along with the SystemJS module loader.\nTake a look at the results of the upgrade setup instructions\nand get the following configurations from there:

\n\n

Once these are done, run:

\n\n npm install\n\n

Soon you can load Angular dependencies into the application via index.html,\nbut first you need to do some directory path adjustments.\nYou'll need to load files from node_modules and the project root instead of\nfrom the /app directory as you've been doing to this point.

\n

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

\n\n \"start\": \"http-server ./ -a localhost -p 8000 -c-1\",\n\n

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

\n\n<base href=\"/app/\">\n\n\n

Now you can load Angular via SystemJS. You'll add the Angular polyfills and the\nSystemJS config to the end of the <head> section, and then you'll use System.import\nto load the actual application:

\n\n<script src=\"/node_modules/core-js/client/shim.min.js\"></script>\n<script src=\"/node_modules/zone.js/bundles/zone.umd.js\"></script>\n<script src=\"/node_modules/systemjs/dist/system.src.js\"></script>\n<script src=\"/systemjs.config.js\"></script>\n<script>\n System.import('/app');\n</script>\n\n\n

You also need to make a couple of adjustments\nto the systemjs.config.js file installed during upgrade setup.

\n

Point the browser to the project root when loading things through SystemJS,\ninstead of using the <base> URL.

\n

Install the upgrade package via npm install @angular/upgrade --save\nand add a mapping for the @angular/upgrade/static package.

\n\n System.config({\n paths: {\n // paths serve as alias\n 'npm:': '/node_modules/'\n },\n map: {\n 'ng-loader': '../src/systemjs-angular-loader.js',\n app: '/app',\n/* . . . */\n '@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',\n/* . . . */\n },\n\n\n

Creating the AppModulelink

\n

Now create the root NgModule class called AppModule.\nThere is already a file named app.module.ts that holds the AngularJS module.\nRename it to app.module.ajs.ts and update the corresponding script name in the index.html as well.\nThe file contents remain:

\n\n// Define the `phonecatApp` AngularJS module\nangular.module('phonecatApp', [\n 'ngAnimate',\n 'ngRoute',\n 'core',\n 'phoneDetail',\n 'phoneList',\n]);\n\n\n\n

Now create a new app.module.ts with the minimum NgModule class:

\n\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\n\n@NgModule({\n imports: [\n BrowserModule,\n ],\n})\nexport class AppModule {\n}\n\n\n

Bootstrapping a hybrid PhoneCatlink

\n

Next, you'll bootstrap the application as a hybrid application\nthat supports both AngularJS and Angular components. After that,\nyou can start converting the individual pieces to Angular.

\n

The application is currently bootstrapped using the AngularJS ng-app directive\nattached to the <html> element of the host page. This will no longer work in the hybrid\napp. Switch to the ngUpgrade bootstrap method\ninstead.

\n

First, remove the ng-app attribute from index.html.\nThen import UpgradeModule in the AppModule, and override its ngDoBootstrap method:

\n\nimport { UpgradeModule } from '@angular/upgrade/static';\n\n@NgModule({\n imports: [\n BrowserModule,\n UpgradeModule,\n ],\n})\nexport class AppModule {\n constructor(private upgrade: UpgradeModule) { }\n ngDoBootstrap() {\n this.upgrade.bootstrap(document.documentElement, ['phonecatApp']);\n }\n}\n\n\n

Note that you are bootstrapping the AngularJS module from inside ngDoBootstrap.\nThe arguments are the same as you would pass to angular.bootstrap if you were manually\nbootstrapping AngularJS: the root element of the application; and an array of the\nAngularJS 1.x modules that you want to load.

\n

Finally, bootstrap the AppModule in app/main.ts.\nThis file has been configured as the application entrypoint in systemjs.config.js,\nso it is already being loaded by the browser.

\n\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\nimport { AppModule } from './app.module';\n\nplatformBrowserDynamic().bootstrapModule(AppModule);\n\n\n

Now you're running both AngularJS and Angular at the same time. That's pretty\nexciting! You're not running any actual Angular components yet. That's next.

\n
\n

Why declare angular as angular.IAngularStatic?link

\n

@types/angular is declared as a UMD module, and due to the way\nUMD typings\nwork, once you have an ES6 import statement in a file all UMD typed modules must also be\nimported via import statements instead of being globally available.

\n

AngularJS is currently loaded by a script tag in index.html, which means that the whole app\nhas access to it as a global and uses the same instance of the angular variable.\nIf you used import * as angular from 'angular' instead, you'd also have to\nload every file in the AngularJS app to use ES2015 modules in order to ensure AngularJS was being\nloaded correctly.

\n

This is a considerable effort and it often isn't worth it, especially since you are in the\nprocess of moving your code to Angular.\nInstead, declare angular as angular.IAngularStatic to indicate it is a global variable\nand still have full typing support.

\n
\n

Upgrading the Phone servicelink

\n

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

\n\n

You can replace this implementation with an Angular service class, while\nkeeping the controllers in AngularJS land.

\n

In the new version, you import the Angular HTTP module and call its HttpClient service instead of ngResource.

\n

Re-open the app.module.ts file, import and add HttpClientModule to the imports array of the AppModule:

\n\nimport { HttpClientModule } from '@angular/common/http';\n\n@NgModule({\n imports: [\n BrowserModule,\n UpgradeModule,\n HttpClientModule,\n ],\n})\nexport class AppModule {\n constructor(private upgrade: UpgradeModule) { }\n ngDoBootstrap() {\n this.upgrade.bootstrap(document.documentElement, ['phonecatApp']);\n }\n}\n\n\n

Now you're ready to upgrade the Phone service itself. Replace the ngResource-based\nservice in phone.service.ts with a TypeScript class decorated as @Injectable:

\n\n@Injectable()\nexport class Phone {\n/* . . . */\n}\n\n\n

The @Injectable decorator will attach some dependency injection metadata\nto the class, letting Angular know about its dependencies. As described\nby the Dependency Injection Guide,\nthis is a marker decorator you need to use for classes that have no other\nAngular decorators but still need to have their dependencies injected.

\n

In its constructor the class expects to get the HttpClient service. It will\nbe injected to it and it is stored as a private field. The service is then\nused in the two instance methods, one of which loads the list of all phones,\nand the other loads the details of a specified phone:

\n\n@Injectable()\nexport class Phone {\n constructor(private http: HttpClient) { }\n query(): Observable<PhoneData[]> {\n return this.http.get<PhoneData[]>(`phones/phones.json`);\n }\n get(id: string): Observable<PhoneData> {\n return this.http.get<PhoneData>(`phones/${id}.json`);\n }\n}\n\n\n

The methods now return observables of type PhoneData and PhoneData[]. This is\na type you don't have yet. Add a simple interface for it:

\n\nexport interface PhoneData {\n name: string;\n snippet: string;\n images: string[];\n}\n\n\n

@angular/upgrade/static has a downgradeInjectable method for the purpose of making\nAngular services available to AngularJS code. Use it to plug in the Phone service:

\n\ndeclare var angular: angular.IAngularStatic;\nimport { downgradeInjectable } from '@angular/upgrade/static';\n/* . . . */\n@Injectable()\nexport class Phone {\n/* . . . */\n}\n\nangular.module('core.phone')\n .factory('phone', downgradeInjectable(Phone));\n\n\n

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

\n\nimport { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { Observable } from 'rxjs';\n\ndeclare var angular: angular.IAngularStatic;\nimport { downgradeInjectable } from '@angular/upgrade/static';\n\nexport interface PhoneData {\n name: string;\n snippet: string;\n images: string[];\n}\n\n@Injectable()\nexport class Phone {\n constructor(private http: HttpClient) { }\n query(): Observable<PhoneData[]> {\n return this.http.get<PhoneData[]>(`phones/phones.json`);\n }\n get(id: string): Observable<PhoneData> {\n return this.http.get<PhoneData>(`phones/${id}.json`);\n }\n}\n\nangular.module('core.phone')\n .factory('phone', downgradeInjectable(Phone));\n\n\n\n

Notice that you're importing the map operator of the RxJS Observable separately.\nDo this for every RxJS operator.

\n

The new Phone service has the same features as the original, ngResource-based service.\nBecause it's an Angular service, you register it with the NgModule providers:

\n\nimport { Phone } from './core/phone/phone.service';\n\n@NgModule({\n imports: [\n BrowserModule,\n UpgradeModule,\n HttpClientModule,\n ],\n providers: [\n Phone,\n ]\n})\nexport class AppModule {\n constructor(private upgrade: UpgradeModule) { }\n ngDoBootstrap() {\n this.upgrade.bootstrap(document.documentElement, ['phonecatApp']);\n }\n}\n\n\n

Now that you are loading phone.service.ts through an import that is resolved\nby SystemJS, you should remove the <script> tag for the service from index.html.\nThis is something you'll do to all components as you upgrade them. Simultaneously\nwith the AngularJS to Angular upgrade you're also migrating code from scripts to modules.

\n

At this point, you can switch the two components to use the new service\ninstead of the old one. While you $inject it as the downgraded phone factory,\nit's really an instance of the Phone class and you annotate its type accordingly:

\n\ndeclare var angular: angular.IAngularStatic;\nimport { Phone, PhoneData } from '../core/phone/phone.service';\n\nclass PhoneListController {\n phones: PhoneData[];\n orderProp: string;\n\n static $inject = ['phone'];\n constructor(phone: Phone) {\n phone.query().subscribe(phones => {\n this.phones = phones;\n });\n this.orderProp = 'age';\n }\n\n}\n\nangular.\n module('phoneList').\n component('phoneList', {\n templateUrl: 'app/phone-list/phone-list.template.html',\n controller: PhoneListController\n });\n\n\n\n\ndeclare var angular: angular.IAngularStatic;\nimport { Phone, PhoneData } from '../core/phone/phone.service';\n\nclass PhoneDetailController {\n phone: PhoneData;\n mainImageUrl: string;\n\n static $inject = ['$routeParams', 'phone'];\n constructor($routeParams: angular.route.IRouteParamsService, phone: Phone) {\n const phoneId = $routeParams.phoneId;\n phone.get(phoneId).subscribe(data => {\n this.phone = data;\n this.setImage(data.images[0]);\n });\n }\n\n setImage(imageUrl: string) {\n this.mainImageUrl = imageUrl;\n }\n}\n\nangular.\n module('phoneDetail').\n component('phoneDetail', {\n templateUrl: 'phone-detail/phone-detail.template.html',\n controller: PhoneDetailController\n });\n\n\n\n

Now there are two AngularJS components using an Angular service!\nThe components don't need to be aware of this, though the fact that the\nservice returns observables and not promises is a bit of a giveaway.\nIn any case, what you've achieved is a migration of a service to Angular\nwithout having to yet migrate the components that use it.

\n
\n

You could use the toPromise method of Observable to turn those\nobservables into promises in the service. In many cases that reduce\nthe number of changes to the component controllers.

\n
\n

Upgrading Componentslink

\n

Upgrade the AngularJS components to Angular components next.\nDo it one component at a time while still keeping the application in hybrid mode.\nAs you make these conversions, you'll also define your first Angular pipes.

\n

Look at the phone list component first. Right now it contains a TypeScript\ncontroller class and a component definition object. You can morph this into\nan Angular component by just renaming the controller class and turning the\nAngularJS component definition object into an Angular @Component decorator.\nYou can then also remove the static $inject property from the class:

\n\nimport { Component } from '@angular/core';\nimport { Phone, PhoneData } from '../core/phone/phone.service';\n\n@Component({\n selector: 'phone-list',\n templateUrl: './phone-list.template.html'\n})\nexport class PhoneListComponent {\n phones: PhoneData[];\n query: string;\n orderProp: string;\n\n constructor(phone: Phone) {\n phone.query().subscribe(phones => {\n this.phones = phones;\n });\n this.orderProp = 'age';\n }\n/* . . . */\n}\n\n\n

The selector attribute is a CSS selector that defines where on the page the component\nshould go. In AngularJS you do matching based on component names, but in Angular you\nhave these explicit selectors. This one will match elements with the name phone-list,\njust like the AngularJS version did.

\n

Now convert the template of this component into Angular syntax.\nThe search controls replace the AngularJS $ctrl expressions\nwith Angular's two-way [(ngModel)] binding syntax:

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

Replace the list's ng-repeat with an *ngFor as\ndescribed in the Template Syntax page.\nReplace the image tag's ng-src with a binding to the native src property.

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

No Angular filter or orderBy filterslink

\n

The built-in AngularJS filter and orderBy filters do not exist in Angular,\nso you need to do the filtering and sorting yourself.

\n

You replaced the filter and orderBy filters with bindings to the getPhones() controller method,\nwhich implements the filtering and ordering logic inside the component itself.

\n\ngetPhones(): PhoneData[] {\n return this.sortPhones(this.filterPhones(this.phones));\n}\n\nprivate filterPhones(phones: PhoneData[]) {\n if (phones && this.query) {\n return phones.filter(phone => {\n const name = phone.name.toLowerCase();\n const snippet = phone.snippet.toLowerCase();\n return name.indexOf(this.query) >= 0 || snippet.indexOf(this.query) >= 0;\n });\n }\n return phones;\n}\n\nprivate sortPhones(phones: PhoneData[]) {\n if (phones && this.orderProp) {\n return phones\n .slice(0) // Make a copy\n .sort((a, b) => {\n if (a[this.orderProp] < b[this.orderProp]) {\n return -1;\n } else if ([b[this.orderProp] < a[this.orderProp]]) {\n return 1;\n } else {\n return 0;\n }\n });\n }\n return phones;\n}\n\n\n

Now you need to downgrade the Angular component so you can use it in AngularJS.\nInstead of registering a component, you register a phoneList directive,\na downgraded version of the Angular component.

\n

The as angular.IDirectiveFactory cast tells the TypeScript compiler\nthat the return value of the downgradeComponent method is a directive factory.

\n\ndeclare var angular: angular.IAngularStatic;\nimport { downgradeComponent } from '@angular/upgrade/static';\n\n/* . . . */\n@Component({\n selector: 'phone-list',\n templateUrl: './phone-list.template.html'\n})\nexport class PhoneListComponent {\n/* . . . */\n}\n\nangular.module('phoneList')\n .directive(\n 'phoneList',\n downgradeComponent({component: PhoneListComponent}) as angular.IDirectiveFactory\n );\n\n\n

The new PhoneListComponent uses the Angular ngModel directive, located in the FormsModule.\nAdd the FormsModule to NgModule imports, declare the new PhoneListComponent and\nfinally add it to entryComponents since you downgraded it:

\n\nimport { FormsModule } from '@angular/forms';\nimport { PhoneListComponent } from './phone-list/phone-list.component';\n\n@NgModule({\n imports: [\n BrowserModule,\n UpgradeModule,\n HttpClientModule,\n FormsModule,\n ],\n declarations: [\n PhoneListComponent,\n ],\n entryComponents: [\n PhoneListComponent,\n})\nexport class AppModule {\n constructor(private upgrade: UpgradeModule) { }\n ngDoBootstrap() {\n this.upgrade.bootstrap(document.documentElement, ['phonecatApp']);\n }\n}\n\n\n

Remove the <script> tag for the phone list component from index.html.

\n

Now set the remaining phone-detail.component.ts as follows:

\n\ndeclare var angular: angular.IAngularStatic;\nimport { downgradeComponent } from '@angular/upgrade/static';\n\nimport { Component } from '@angular/core';\n\nimport { Phone, PhoneData } from '../core/phone/phone.service';\nimport { RouteParams } from '../ajs-upgraded-providers';\n\n@Component({\n selector: 'phone-detail',\n templateUrl: './phone-detail.template.html',\n})\nexport class PhoneDetailComponent {\n phone: PhoneData;\n mainImageUrl: string;\n\n constructor(routeParams: RouteParams, phone: Phone) {\n phone.get(routeParams.phoneId).subscribe(data => {\n this.phone = data;\n this.setImage(data.images[0]);\n });\n }\n\n setImage(imageUrl: string) {\n this.mainImageUrl = imageUrl;\n }\n}\n\nangular.module('phoneDetail')\n .directive(\n 'phoneDetail',\n downgradeComponent({component: PhoneDetailComponent}) as angular.IDirectiveFactory\n );\n\n\n\n

This is similar to the phone list component.\nThe new wrinkle is the RouteParams type annotation that identifies the routeParams dependency.

\n

The AngularJS injector has an AngularJS router dependency called $routeParams,\nwhich was injected into PhoneDetails when it was still an AngularJS controller.\nYou intend to inject it into the new PhoneDetailsComponent.

\n

Unfortunately, AngularJS dependencies are not automatically available to Angular components.\nYou must upgrade this service via a factory provider\nto make $routeParams an Angular injectable.\nDo that in a new file called ajs-upgraded-providers.ts and import it in app.module.ts:

\n\nexport abstract class RouteParams {\n [key: string]: string;\n}\n\nexport function routeParamsFactory(i: any) {\n return i.get('$routeParams');\n}\n\nexport const routeParamsProvider = {\n provide: RouteParams,\n useFactory: routeParamsFactory,\n deps: ['$injector']\n};\n\n\n\n\nimport { routeParamsProvider } from './ajs-upgraded-providers';\n providers: [\n Phone,\n routeParamsProvider\n ]\n\n\n

Convert the phone detail component template into Angular syntax as follows:

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

There are several notable changes here:

\n\n

Add PhoneDetailComponent component to the NgModule declarations and entryComponents:

\n\nimport { PhoneDetailComponent } from './phone-detail/phone-detail.component';\n\n@NgModule({\n imports: [\n BrowserModule,\n UpgradeModule,\n HttpClientModule,\n FormsModule,\n ],\n declarations: [\n PhoneListComponent,\n PhoneDetailComponent,\n ],\n entryComponents: [\n PhoneListComponent,\n PhoneDetailComponent\n ],\n providers: [\n Phone,\n routeParamsProvider\n ]\n})\nexport class AppModule {\n constructor(private upgrade: UpgradeModule) { }\n ngDoBootstrap() {\n this.upgrade.bootstrap(document.documentElement, ['phonecatApp']);\n }\n}\n\n\n

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

\n

Add the CheckmarkPipelink

\n

The AngularJS directive had a checkmark filter.\nTurn that into an Angular pipe.

\n

There is no upgrade method to convert filters into pipes.\nYou won't miss it.\nIt's easy to turn the filter function into an equivalent Pipe class.\nThe implementation is the same as before, repackaged in the transform method.\nRename the file to checkmark.pipe.ts to conform with Angular conventions:

\n\nimport { Pipe, PipeTransform } from '@angular/core';\n\n@Pipe({name: 'checkmark'})\nexport class CheckmarkPipe implements PipeTransform {\n transform(input: boolean) {\n return input ? '\\u2713' : '\\u2718';\n }\n}\n\n\n\n

Now import and declare the newly created pipe and\nremove the filter <script> tag from index.html:

\n\nimport { CheckmarkPipe } from './core/checkmark/checkmark.pipe';\n\n@NgModule({\n imports: [\n BrowserModule,\n UpgradeModule,\n HttpClientModule,\n FormsModule,\n ],\n declarations: [\n PhoneListComponent,\n PhoneDetailComponent,\n CheckmarkPipe\n ],\n entryComponents: [\n PhoneListComponent,\n PhoneDetailComponent\n ],\n providers: [\n Phone,\n routeParamsProvider\n ]\n})\nexport class AppModule {\n constructor(private upgrade: UpgradeModule) { }\n ngDoBootstrap() {\n this.upgrade.bootstrap(document.documentElement, ['phonecatApp']);\n }\n}\n\n\n

AOT compile the hybrid applink

\n

To use AOT with a hybrid app, you have to first set it up like any other Angular application,\nas shown in the Ahead-of-time Compilation chapter.

\n

Then change main-aot.ts to bootstrap the AppComponentFactory that was generated\nby the AOT compiler:

\n\nimport { platformBrowser } from '@angular/platform-browser';\n\nimport { AppModuleNgFactory } from './app.module.ngfactory';\n\nplatformBrowser().bootstrapModuleFactory(AppModuleNgFactory);\n\n\n\n

You need to load all the AngularJS files you already use in index.html in aot/index.html\nas well:

\n\n<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n\n <base href=\"/app/\">\n\n <title>Google Phone Gallery</title>\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" />\n <link rel=\"stylesheet\" href=\"app.css\" />\n <link rel=\"stylesheet\" href=\"app.animations.css\" />\n\n <script src=\"https://code.jquery.com/jquery-2.2.4.js\"></script>\n <script src=\"https://code.angularjs.org/1.5.5/angular.js\"></script>\n <script src=\"https://code.angularjs.org/1.5.5/angular-animate.js\"></script>\n <script src=\"https://code.angularjs.org/1.5.5/angular-resource.js\"></script>\n <script src=\"https://code.angularjs.org/1.5.5/angular-route.js\"></script>\n\n <script src=\"app.module.ajs.js\"></script>\n <script src=\"app.config.js\"></script>\n <script src=\"app.animations.js\"></script>\n <script src=\"core/core.module.js\"></script>\n <script src=\"core/phone/phone.module.js\"></script>\n <script src=\"phone-list/phone-list.module.js\"></script>\n <script src=\"phone-detail/phone-detail.module.js\"></script>\n\n <script src=\"/node_modules/core-js/client/shim.min.js\"></script>\n <script src=\"/node_modules/zone.js/bundles/zone.umd.min.js\"></script>\n\n <script>window.module = 'aot';</script>\n </head>\n\n <body>\n <div class=\"view-container\">\n <div ng-view class=\"view-frame\"></div>\n </div>\n </body>\n <script src=\"/dist/build.js\"></script>\n</html>\n\n\n\n

These files need to be copied together with the polyfills. The files the application\nneeds at runtime, like the .json phone lists and images, also need to be copied.

\n

Install fs-extra via npm install fs-extra --save-dev for better file copying, and change\ncopy-dist-files.js to the following:

\n\nvar fsExtra = require('fs-extra');\nvar resources = [\n // polyfills\n 'node_modules/core-js/client/shim.min.js',\n 'node_modules/zone.js/bundles/zone.umd.min.js',\n // css\n 'app/app.css',\n 'app/app.animations.css',\n // images and json files\n 'app/img/',\n 'app/phones/',\n // app files\n 'app/app.module.ajs.js',\n 'app/app.config.js',\n 'app/app.animations.js',\n 'app/core/core.module.js',\n 'app/core/phone/phone.module.js',\n 'app/phone-list/phone-list.module.js',\n 'app/phone-detail/phone-detail.module.js'\n];\nresources.map(function(sourcePath) {\n // Need to rename zone.umd.min.js to zone.min.js\n var destPath = `aot/${sourcePath}`.replace('.umd.min.js', '.min.js');\n fsExtra.copySync(sourcePath, destPath);\n});\n\n\n\n

And that's all you need to use AOT while upgrading your app!

\n

Adding The Angular Router And Bootstraplink

\n

At this point, you've replaced all AngularJS application components with\ntheir Angular counterparts, even though you're still serving them from the AngularJS router.

\n

Add the Angular routerlink

\n

Angular has an all-new router.

\n

Like all routers, it needs a place in the UI to display routed views.\nFor Angular that's the <router-outlet> and it belongs in a root component\nat the top of the applications component tree.

\n

You don't yet have such a root component, because the app is still managed as an AngularJS app.\nCreate a new app.component.ts file with the following AppComponent class:

\n\nimport { Component } from '@angular/core';\n\n@Component({\n selector: 'phonecat-app',\n template: '<router-outlet></router-outlet>'\n})\nexport class AppComponent { }\n\n\n\n

It has a simple template that only includes the <router-outlet>.\nThis component just renders the contents of the active route and nothing else.

\n

The selector tells Angular to plug this root component into the <phonecat-app>\nelement on the host web page when the application launches.

\n

Add this <phonecat-app> element to the index.html.\nIt replaces the old AngularJS ng-view directive:

\n\n<body>\n <phonecat-app></phonecat-app>\n</body>\n\n\n

Create the Routing Modulelink

\n

A router needs configuration whether it's the AngularJS or Angular or any other router.

\n

The details of Angular router configuration are best left to the Routing documentation\nwhich recommends that you create a NgModule dedicated to router configuration\n(called a Routing Module).

\n\nimport { NgModule } from '@angular/core';\nimport { Routes, RouterModule } from '@angular/router';\nimport { APP_BASE_HREF, HashLocationStrategy, LocationStrategy } from '@angular/common';\n\nimport { PhoneDetailComponent } from './phone-detail/phone-detail.component';\nimport { PhoneListComponent } from './phone-list/phone-list.component';\n\nconst routes: Routes = [\n { path: '', redirectTo: 'phones', pathMatch: 'full' },\n { path: 'phones', component: PhoneListComponent },\n { path: 'phones/:phoneId', component: PhoneDetailComponent }\n];\n\n@NgModule({\n imports: [ RouterModule.forRoot(routes) ],\n exports: [ RouterModule ],\n providers: [\n { provide: APP_BASE_HREF, useValue: '!' },\n { provide: LocationStrategy, useClass: HashLocationStrategy },\n ]\n})\nexport class AppRoutingModule { }\n\n\n\n

This module defines a routes object with two routes to the two phone components\nand a default route for the empty path.\nIt passes the routes to the RouterModule.forRoot method which does the rest.

\n

A couple of extra providers enable routing with \"hash\" URLs such as #!/phones\ninstead of the default \"push state\" strategy.

\n

Now update the AppModule to import this AppRoutingModule and also the\ndeclare the root AppComponent as the bootstrap component.\nThat tells Angular that it should bootstrap the app with the root AppComponent and\ninsert its view into the host web page.

\n

You must also remove the bootstrap of the AngularJS module from ngDoBootstrap() in app.module.ts\nand the UpgradeModule import.

\n\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\nimport { HttpClientModule } from '@angular/common/http';\n\nimport { AppRoutingModule } from './app-routing.module';\nimport { AppComponent } from './app.component';\nimport { CheckmarkPipe } from './core/checkmark/checkmark.pipe';\nimport { Phone } from './core/phone/phone.service';\nimport { PhoneDetailComponent } from './phone-detail/phone-detail.component';\nimport { PhoneListComponent } from './phone-list/phone-list.component';\n\n@NgModule({\n imports: [\n BrowserModule,\n FormsModule,\n HttpClientModule,\n AppRoutingModule\n ],\n declarations: [\n AppComponent,\n PhoneListComponent,\n CheckmarkPipe,\n PhoneDetailComponent\n ],\n providers: [\n Phone\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule {}\n\n\n\n

And since you are routing to PhoneListComponent and PhoneDetailComponent directly rather than\nusing a route template with a <phone-list> or <phone-detail> tag, you can do away with their\nAngular selectors as well.

\n\n

You no longer have to hardcode the links to phone details in the phone list.\nYou can generate data bindings for each phone's id to the routerLink directive\nand let that directive construct the appropriate URL to the PhoneDetailComponent:

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

See the Routing page for details.

\n

\n

Use route parameterslink

\n

The Angular router passes route parameters differently.\nCorrect the PhoneDetail component constructor to expect an injected ActivatedRoute object.\nExtract the phoneId from the ActivatedRoute.snapshot.params and fetch the phone data as before:

\n\nimport { Component } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\n\nimport { Phone, PhoneData } from '../core/phone/phone.service';\n\n@Component({\n selector: 'phone-detail',\n templateUrl: './phone-detail.template.html'\n})\nexport class PhoneDetailComponent {\n phone: PhoneData;\n mainImageUrl: string;\n\n constructor(activatedRoute: ActivatedRoute, phone: Phone) {\n phone.get(activatedRoute.snapshot.paramMap.get('phoneId'))\n .subscribe((p: PhoneData) => {\n this.phone = p;\n this.setImage(p.images[0]);\n });\n }\n\n setImage(imageUrl: string) {\n this.mainImageUrl = imageUrl;\n }\n}\n\n\n\n

You are now running a pure Angular application!

\n

Say Goodbye to AngularJSlink

\n

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

\n

The application is still bootstrapped as a hybrid app.\nThere's no need for that anymore.

\n

Switch the bootstrap method of the application from the UpgradeModule to the Angular way.

\n\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\nimport { AppModule } from './app.module';\n\nplatformBrowserDynamic().bootstrapModule(AppModule);\n\n\n\n

If you haven't already, remove all references to the UpgradeModule from app.module.ts,\nas well as any factory provider\nfor AngularJS services, and the app/ajs-upgraded-providers.ts file.

\n

Also remove any downgradeInjectable() or downgradeComponent() you find,\ntogether with the associated AngularJS factory or directive declarations.\nSince you no longer have downgraded components, you no longer list them\nin entryComponents.

\n\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\nimport { HttpClientModule } from '@angular/common/http';\n\nimport { AppRoutingModule } from './app-routing.module';\nimport { AppComponent } from './app.component';\nimport { CheckmarkPipe } from './core/checkmark/checkmark.pipe';\nimport { Phone } from './core/phone/phone.service';\nimport { PhoneDetailComponent } from './phone-detail/phone-detail.component';\nimport { PhoneListComponent } from './phone-list/phone-list.component';\n\n@NgModule({\n imports: [\n BrowserModule,\n FormsModule,\n HttpClientModule,\n AppRoutingModule\n ],\n declarations: [\n AppComponent,\n PhoneListComponent,\n CheckmarkPipe,\n PhoneDetailComponent\n ],\n providers: [\n Phone\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule {}\n\n\n\n

You may also completely remove the following files. They are AngularJS\nmodule configuration files and not needed in Angular:

\n\n

The external typings for AngularJS may be uninstalled as well. The only ones\nyou still need are for Jasmine and Angular polyfills.\nThe @angular/upgrade package and its mapping in systemjs.config.js can also go.

\n\n npm uninstall @angular/upgrade --save\n npm uninstall @types/angular @types/angular-animate @types/angular-cookies @types/angular-mocks @types/angular-resource @types/angular-route @types/angular-sanitize --save-dev\n\n

Finally, from index.html, remove all references to AngularJS scripts and jQuery.\nWhen you're done, this is what it should look like:

\n\n<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <base href=\"/app/\">\n <title>Google Phone Gallery</title>\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" />\n <link rel=\"stylesheet\" href=\"app.css\" />\n\n <script src=\"/node_modules/core-js/client/shim.min.js\"></script>\n <script src=\"/node_modules/zone.js/bundles/zone.umd.js\"></script>\n <script src=\"/node_modules/systemjs/dist/system.src.js\"></script>\n <script src=\"/systemjs.config.js\"></script>\n <script>\n System.import('/app');\n </script>\n </head>\n <body>\n <phonecat-app></phonecat-app>\n </body>\n</html>\n\n\n

That is the last you'll see of AngularJS! It has served us well but now\nit's time to say goodbye.

\n

Appendix: Upgrading PhoneCat Testslink

\n

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

\n

E2E Testslink

\n

The PhoneCat project has both E2E Protractor tests and some Karma unit tests in it.\nOf these two, E2E tests can be dealt with much more easily: By definition,\nE2E tests access the application from the outside by interacting with\nthe various UI elements the app puts on the screen. E2E tests aren't really that\nconcerned with the internal structure of the application components. That\nalso means that, although you modify the project quite a bit during the upgrade, the E2E\ntest suite should keep passing with just minor modifications. You\ndidn't change how the application behaves from the user's point of view.

\n

During TypeScript conversion, there is nothing to do to keep E2E tests\nworking. But when you change the bootstrap to that of a Hybrid app,\nyou must make a few changes.

\n

Update the protractor-conf.js to sync with hybrid apps:

\n\n ng12Hybrid: true\n\n

When you start to upgrade components and their templates to Angular, you'll make more changes\nbecause the E2E tests have matchers that are specific to AngularJS.\nFor PhoneCat you need to make the following changes in order to make things work with Angular:

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Previous code\n \n New code\n \n Notes\n
\n

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

\n
\n

by.css('.phones .name')

\n
\n

The repeater matcher relies on AngularJS ng-repeat

\n
\n

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

\n
\n

by.css('.phones li')

\n
\n

The repeater matcher relies on AngularJS ng-repeat

\n
\n

by.model('$ctrl.query')

\n
\n

by.css('input')

\n
\n

The model matcher relies on AngularJS ng-model

\n
\n

by.model('$ctrl.orderProp')

\n
\n

by.css('select')

\n
\n

The model matcher relies on AngularJS ng-model

\n
\n

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

\n
\n

by.css('h1')

\n
\n

The binding matcher relies on AngularJS data binding

\n
\n

When the bootstrap method is switched from that of UpgradeModule to\npure Angular, AngularJS ceases to exist on the page completely.\nAt this point, you need to tell Protractor that it should not be looking for\nan AngularJS app anymore, but instead it should find Angular apps from\nthe page.

\n

Replace the ng12Hybrid previously added with the following in protractor-conf.js:

\n\n useAllAngular2AppRoots: true,\n\n

Also, there are a couple of Protractor API calls in the PhoneCat test code that\nare using the AngularJS $location service under the hood. As that\nservice is no longer present after the upgrade, replace those calls with ones\nthat use WebDriver's generic URL APIs instead. The first of these is\nthe redirection spec:

\n\nit('should redirect `index.html` to `index.html#!/phones', async () => {\n await browser.get('index.html');\n await browser.waitForAngular();\n const url = await browser.getCurrentUrl();\n expect(url.endsWith('/phones')).toBe(true);\n});\n\n\n

And the second is the phone links spec:

\n\nit('should render phone specific links', async () => {\n const query = element(by.css('input'));\n await query.sendKeys('nexus');\n await element.all(by.css('.phones li a')).first().click();\n const url = await browser.getCurrentUrl();\n expect(url.endsWith('/phones/nexus-s')).toBe(true);\n});\n\n\n

Unit Testslink

\n

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

\n

During TypeScript conversion no changes are strictly necessary. But it may be\na good idea to convert the unit test code into TypeScript as well.

\n

For instance, in the phone detail component spec, you can use ES2015\nfeatures like arrow functions and block-scoped variables and benefit from the type\ndefinitions of the AngularJS services you're consuming:

\n\ndescribe('phoneDetail', () => {\n\n // Load the module that contains the `phoneDetail` component before each test\n beforeEach(angular.mock.module('phoneDetail'));\n\n // Test the controller\n describe('PhoneDetailController', () => {\n let $httpBackend: angular.IHttpBackendService;\n let ctrl: any;\n const xyzPhoneData = {\n name: 'phone xyz',\n images: ['image/url1.png', 'image/url2.png']\n };\n\n beforeEach(inject(($componentController: any,\n _$httpBackend_: angular.IHttpBackendService,\n $routeParams: angular.route.IRouteParamsService) => {\n $httpBackend = _$httpBackend_;\n $httpBackend.expectGET('phones/xyz.json').respond(xyzPhoneData);\n\n $routeParams.phoneId = 'xyz';\n\n ctrl = $componentController('phoneDetail');\n }));\n\n it('should fetch the phone details', () => {\n jasmine.addCustomEqualityTester(angular.equals);\n\n expect(ctrl.phone).toEqual({});\n\n $httpBackend.flush();\n expect(ctrl.phone).toEqual(xyzPhoneData);\n });\n\n });\n\n});\n\n\n\n

Once you start the upgrade process and bring in SystemJS, configuration changes\nare needed for Karma. You need to let SystemJS load all the new Angular code,\nwhich can be done with the following kind of shim file:

\n\n// /*global jasmine, __karma__, window*/\nError.stackTraceLimit = 0; // \"No stacktrace\"\" is usually best for app testing.\n\n// Uncomment to get full stacktrace output. Sometimes helpful, usually not.\n// Error.stackTraceLimit = Infinity; //\n\njasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;\n\nvar builtPath = '/base/app/';\n\n__karma__.loaded = function () { };\n\nfunction isJsFile(path) {\n return path.slice(-3) == '.js';\n}\n\nfunction isSpecFile(path) {\n return /\\.spec\\.(.*\\.)?js$/.test(path);\n}\n\nfunction isBuiltFile(path) {\n return isJsFile(path) && (path.substr(0, builtPath.length) == builtPath);\n}\n\nvar allSpecFiles = Object.keys(window.__karma__.files)\n .filter(isSpecFile)\n .filter(isBuiltFile);\n\nSystem.config({\n baseURL: '/base',\n // Extend usual application package list with test folder\n packages: { 'testing': { main: 'index.js', defaultExtension: 'js' } },\n\n // Assume npm: is set in `paths` in systemjs.config\n // Map the angular testing umd bundles\n map: {\n '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',\n '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',\n '@angular/common/http/testing': 'npm:@angular/common/bundles/common-http-testing.umd.js',\n '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',\n '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',\n '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',\n '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',\n '@angular/forms/testing': 'npm:@angular/forms/bundles/forms-testing.umd.js',\n },\n});\n\nSystem.import('systemjs.config.js')\n .then(importSystemJsExtras)\n .then(initTestBed)\n .then(initTesting);\n\n/** Optional SystemJS configuration extras. Keep going w/o it */\nfunction importSystemJsExtras(){\n return System.import('systemjs.config.extras.js')\n .catch(function(reason) {\n console.log(\n 'Warning: System.import could not load the optional \"systemjs.config.extras.js\". Did you omit it by accident? Continuing without it.'\n );\n console.log(reason);\n });\n}\n\nfunction initTestBed() {\n return Promise.all([\n System.import('@angular/core/testing'),\n System.import('@angular/platform-browser-dynamic/testing')\n ])\n\n .then(function (providers) {\n var coreTesting = providers[0];\n var browserTesting = providers[1];\n\n coreTesting.TestBed.initTestEnvironment(\n browserTesting.BrowserDynamicTestingModule,\n browserTesting.platformBrowserDynamicTesting());\n })\n}\n\n// Import all spec files and start karma\nfunction initTesting() {\n return Promise.all(\n allSpecFiles.map(function (moduleName) {\n return System.import(moduleName);\n })\n )\n .then(__karma__.start, __karma__.error);\n}\n\n\n\n

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

\n

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

\n\nbasePath: './',\n\n\n

Once done, you can load SystemJS and other dependencies, and also switch the configuration\nfor loading application files so that they are not included to the page by Karma. You'll let\nthe shim and SystemJS load them.

\n\n// System.js for module loading\n'node_modules/systemjs/dist/system.src.js',\n\n// Polyfills\n'node_modules/core-js/client/shim.js',\n\n// zone.js\n'node_modules/zone.js/bundles/zone.umd.js',\n'node_modules/zone.js/bundles/zone-testing.umd.js',\n\n// RxJs.\n{ pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },\n{ pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },\n\n// Angular itself and the testing library\n{pattern: 'node_modules/@angular/**/*.js', included: false, watched: false},\n{pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false},\n\n{pattern: 'systemjs.config.js', included: false, watched: false},\n'karma-test-shim.js',\n\n{pattern: 'app/**/*.module.js', included: false, watched: true},\n{pattern: 'app/*!(.module|.spec).js', included: false, watched: true},\n{pattern: 'app/!(bower_components)/**/*!(.module|.spec).js', included: false, watched: true},\n{pattern: 'app/**/*.spec.js', included: false, watched: true},\n\n{pattern: '**/*.html', included: false, watched: true},\n\n\n

Since the HTML templates of Angular components will be loaded as well, you must help\nKarma out a bit so that it can route them to the right paths:

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

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

\n\nimport { CheckmarkPipe } from './checkmark.pipe';\n\ndescribe('CheckmarkPipe', () => {\n\n it('should convert boolean values to unicode checkmark or cross', () => {\n const checkmarkPipe = new CheckmarkPipe();\n expect(checkmarkPipe.transform(true)).toBe('\\u2713');\n expect(checkmarkPipe.transform(false)).toBe('\\u2718');\n });\n});\n\n\n\n

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

\n\nimport { inject, TestBed } from '@angular/core/testing';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { Phone, PhoneData } from './phone.service';\n\ndescribe('Phone', () => {\n let phone: Phone;\n const phonesData: PhoneData[] = [\n {name: 'Phone X', snippet: '', images: []},\n {name: 'Phone Y', snippet: '', images: []},\n {name: 'Phone Z', snippet: '', images: []}\n ];\n let httpMock: HttpTestingController;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [\n HttpClientTestingModule\n ],\n providers: [\n Phone,\n ]\n });\n });\n\n beforeEach(inject([HttpTestingController, Phone], (_httpMock_: HttpTestingController, _phone_: Phone) => {\n httpMock = _httpMock_;\n phone = _phone_;\n }));\n\n afterEach(() => {\n httpMock.verify();\n });\n\n it('should fetch the phones data from `/phones/phones.json`', () => {\n phone.query().subscribe(result => {\n expect(result).toEqual(phonesData);\n });\n const req = httpMock.expectOne(`/phones/phones.json`);\n req.flush(phonesData);\n });\n\n});\n\n\n\n\n

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

\n\nimport { TestBed, waitForAsync } from '@angular/core/testing';\nimport { ActivatedRoute } from '@angular/router';\nimport { Observable, of } from 'rxjs';\n\nimport { PhoneDetailComponent } from './phone-detail.component';\nimport { Phone, PhoneData } from '../core/phone/phone.service';\nimport { CheckmarkPipe } from '../core/checkmark/checkmark.pipe';\n\nfunction xyzPhoneData(): PhoneData {\n return {name: 'phone xyz', snippet: '', images: ['image/url1.png', 'image/url2.png']};\n}\n\nclass MockPhone {\n get(id: string): Observable<PhoneData> {\n return of(xyzPhoneData());\n }\n}\n\n\nclass ActivatedRouteMock {\n constructor(public snapshot: any) {}\n}\n\n\ndescribe('PhoneDetailComponent', () => {\n\n beforeEach(waitForAsync(() => {\n TestBed.configureTestingModule({\n declarations: [ CheckmarkPipe, PhoneDetailComponent ],\n providers: [\n { provide: Phone, useClass: MockPhone },\n { provide: ActivatedRoute, useValue: new ActivatedRouteMock({ params: { phoneId: 1 } }) }\n ]\n })\n .compileComponents();\n }));\n\n it('should fetch phone detail', () => {\n const fixture = TestBed.createComponent(PhoneDetailComponent);\n fixture.detectChanges();\n const compiled = fixture.debugElement.nativeElement;\n expect(compiled.querySelector('h1').textContent).toContain(xyzPhoneData().name);\n });\n});\n\n\n\n\nimport {SpyLocation} from '@angular/common/testing';\nimport {NO_ERRORS_SCHEMA} from '@angular/core';\nimport {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';\nimport {ActivatedRoute} from '@angular/router';\nimport {Observable, of} from 'rxjs';\n\nimport {Phone, PhoneData} from '../core/phone/phone.service';\n\nimport {PhoneListComponent} from './phone-list.component';\n\nclass ActivatedRouteMock {\n constructor(public snapshot: any) {}\n}\n\nclass MockPhone {\n query(): Observable<PhoneData[]> {\n return of([\n {name: 'Nexus S', snippet: '', images: []}, {name: 'Motorola DROID', snippet: '', images: []}\n ]);\n }\n}\n\nlet fixture: ComponentFixture<PhoneListComponent>;\n\ndescribe('PhoneList', () => {\n beforeEach(waitForAsync(() => {\n TestBed\n .configureTestingModule({\n declarations: [PhoneListComponent],\n providers: [\n {provide: ActivatedRoute, useValue: new ActivatedRouteMock({params: {'phoneId': 1}})},\n {provide: Location, useClass: SpyLocation},\n {provide: Phone, useClass: MockPhone},\n ],\n schemas: [NO_ERRORS_SCHEMA]\n })\n .compileComponents();\n }));\n\n beforeEach(() => {\n fixture = TestBed.createComponent(PhoneListComponent);\n });\n\n it('should create \"phones\" model with 2 phones fetched from xhr', () => {\n fixture.detectChanges();\n let compiled = fixture.debugElement.nativeElement;\n expect(compiled.querySelectorAll('.phone-list-item').length).toBe(2);\n expect(compiled.querySelector('.phone-list-item:nth-child(1)').textContent)\n .toContain('Motorola DROID');\n expect(compiled.querySelector('.phone-list-item:nth-child(2)').textContent)\n .toContain('Nexus S');\n });\n\n xit('should set the default value of orderProp model', () => {\n fixture.detectChanges();\n let compiled = fixture.debugElement.nativeElement;\n expect(compiled.querySelector('select option:last-child').selected).toBe(true);\n });\n});\n\n\n\n

Finally, revisit both of the component tests when you switch to the Angular\nrouter. For the details component, provide a mock of Angular ActivatedRoute object\ninstead of using the AngularJS $routeParams.

\n\nimport { TestBed, waitForAsync } from '@angular/core/testing';\nimport { ActivatedRoute } from '@angular/router';\n/* . . . */\n\nclass ActivatedRouteMock {\n constructor(public snapshot: any) {}\n}\n\n/* . . . */\n\n beforeEach(waitForAsync(() => {\n TestBed.configureTestingModule({\n declarations: [ CheckmarkPipe, PhoneDetailComponent ],\n providers: [\n { provide: Phone, useClass: MockPhone },\n { provide: ActivatedRoute, useValue: new ActivatedRouteMock({ params: { phoneId: 1 } }) }\n ]\n })\n .compileComponents();\n }));\n\n\n

And for the phone list component, a few adjustments to the router make\nthe RouteLink directives work.

\n\nimport {SpyLocation} from '@angular/common/testing';\nimport {NO_ERRORS_SCHEMA} from '@angular/core';\nimport {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';\nimport {ActivatedRoute} from '@angular/router';\nimport {Observable, of} from 'rxjs';\n\nimport {Phone, PhoneData} from '../core/phone/phone.service';\n\nimport {PhoneListComponent} from './phone-list.component';\n\n/* . . . */\n\n beforeEach(waitForAsync(() => {\n TestBed\n .configureTestingModule({\n declarations: [PhoneListComponent],\n providers: [\n {provide: ActivatedRoute, useValue: new ActivatedRouteMock({params: {'phoneId': 1}})},\n {provide: Location, useClass: SpyLocation},\n {provide: Phone, useClass: MockPhone},\n ],\n schemas: [NO_ERRORS_SCHEMA]\n })\n .compileComponents();\n }));\n\n beforeEach(() => {\n fixture = TestBed.createComponent(PhoneListComponent);\n });\n\n\n\n \n
\n\n\n" }