43
4/12/17 1 Migration Strategies AngularJS to Angular Migration high-level approaches Rewrite Maintain Migrate

Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

  • Upload
    others

  • View
    11

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

4/12/17

1

MigrationStrategiesAngularJStoAngular

Migrationhigh-levelapproaches

• Rewrite•Maintain•Migrate

Page 2: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

4/12/17

2

ConceptMapping

AngularJS• Controllers• ComponentDirectives• Services• DecoratorDirectives• Filters

Angular• Components• Components• Services• Directives• Pipes

UpgradeAdapter

• @angular/upgrade(module)• UpgradeAdapter (service)• MixandmatchAngularJSandAngularcomponents

Page 3: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

4/12/17

3

Upgrade&DowngradeUpgradeAdapter

• CanUpgrade&Downgrade• Controllers• ComponentDirectives• Services

• CannotUpgrade&Downgrade(rewrite)• Attribute/DecoratorDirectives• Filters• Router

UpgradeAdapterDependencyInjection

Page 4: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

4/12/17

4

MigrationPlan

• Preparation• FollowtheAngularStyleGuide• UsingaModuleLoader• MigratingtoTypeScript• UsingComponentDirectives

• UpgradingwiththeUpgradeAdapter• BootstrapahybridAngularJS+Angular Application• UseAngularComponentsfromAngularJSCode• UseAngularJSComponentDirectivesfromAngularCode• MakeAngularJSDependenciesInjectabletoAngular• MakeAngularDependencies InjectabletoAngularJS

DemoAddTypeScript

Page 5: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

4/12/17

5

DemoUseTypeScript

DemoAddAngular&ModuleLoader

Page 6: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

4/12/17

6

DemoAngularJS&AngularTogether

DemoUpgradingServices

Page 7: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

4/12/17

7

Labs:MigratingPart1SuggestedTime:80minutesLab1:AddTypeScriptLab2:Use TypeScriptLab3:AddAngular&ModuleLoaderLab4:Angular1&Angular2TogetherLab5:UpgradingServices

DemoControllerstoComponents

Page 8: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

4/12/17

8

DemoFiltertoPipe

DemoUpgradeRouter

Page 9: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

4/12/17

9

DemoRemoveAngularJS

Labs:MigratingPart2SuggestedTime:80minutesLab6:ControllerstoComponentsLab7:FiltertoPipeLab8:UpgradeRouterLab9:RemoveAngular1

Page 10: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

Angular MigratingLab Manual

Copyright © 2016-2018

Funny Ant, LLC

All rights reserved.

No part of this book may be reproduced in any form or by any electronic or mechanical means including information storage and retrieval systems, without permission from the author.

©FUNNY ANT, LLC 2.3.0.2 �1

Page 11: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

Table of ContentsAngular Migrating 1

Table of Contents 2

About this Lab Manual 3

Lab 1: Add TypeScript 4

Lab 2: Use TypeScript 7

Lab 3: Add Angular & Module Loader 10

Lab 4: AngularJS & Angular Together 14

Lab 5: Upgrading Services 16

Lab 6: Controllers to Components 20

Lab 7: Filter to Pipe 27

Lab 8: Upgrade Router 29

Lab 9: Remove AngularJS 33

©FUNNY ANT, LLC 2.3.0.2 �2

Page 12: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

About this Lab ManualThis lab manual provides a series of hands-on exercises for learning how to build web applications using Angular.

Conventions

Each hands-on exercise in this manual will consist of a series of steps to accomplish a learning objective. Additional information will be presented using the following symbols.

ℹ General Information

" Where to find more information⚠ Warning

☑ What you’ve accomplished

☞ Tips and tricks

©FUNNY ANT, LLC 2.3.0.2 �3

Page 13: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

Lab 1: Add TypeScriptObjectives• Add TypeScript to an AngularJS project

Steps1. Close the folder in your editor and open the migrating folder.

ℹ This lab uses a copy of the original AngularJS tutorial (PhoneCat) project.

2. If not already running, run the following command to start the web server.

3. In your browser, visit http://localhost:8000 to view the phone catalog application.

⚠ This project does not use a live reloading server so you will need to refresh the browser manually.

4. Install Typescript by running the following command.

©FUNNY ANT, LLC 2.3.0.2 �4

npm start

npm install [email protected] --save-dev

Page 14: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

5. Create a tsconfig.json file at the root of the project and configure the TypeScript compiler as shown below.

☞ Copy these lines or the entire file from snippets/tsconfig.json to save typing.

6. Add the type definitions for AngularJS and related libraries by copying into the devDependencies section of package.json the contents of type-definitions-install.txt.

7. From a command-prompt/terminal with the working directory set to migrating. Run the following command to install the devDependencies added in the last step.

8. Add these npm scripts to package.json to run the TypeScript compiler.

☞ These scripts should be added to the existing scripts.

©FUNNY ANT, LLC 2.3.0.2 �5

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

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

npm install

Page 15: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

9. Change the file extension on all .js files in the app directory to .ts. This needs to done recursively for all directories under the app directory except bower_components which should be left unchanged.

⚠ Do not change file extensions in bower_components. It can be helpful to temporarily move the

bower_components directory out of the app folder so these changes can more easily be done…just be sure to remember to move bower_components back under app when you complete this step.

⚠ If you are using Visual Studio code and have hidden your .js files you will need to unhide them to

complete this step.

10. Run the TypeScript compiler in watch mode and leave it running for the remainder of this lab.

11. Verify the compiler has no errors.

☑You have successfully completed Lab 1.

©FUNNY ANT, LLC 2.3.0.2 �6

npm run tsc:w

Page 16: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

Lab 2: Use TypeScriptObjectives• Use TypeScript in an AngularJS project

Steps1. Add static typing to app/core/checkmark/checkmark.filter.ts by typing the

input parameter as boolean.

2. Add static typing to core/phone/phone.service.ts by typing the $resource service.

©FUNNY ANT, LLC 2.3.0.2 �7

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

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

Page 17: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

3. Refactor the controller function PhoneListController (phone-list.component.ts) into a class. Replace the current code with the contents of snippets/phone-list.component0.txt.

©FUNNY ANT, LLC 2.3.0.2 �8

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

Page 18: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

4. Refactor the controller function PhoneDetailController (phone-detail.component.ts) into a class. Replace the current code with the contents of snippets/phone-detail.component0.txt.

5. Verify the TypeScript compiler has no errors.

6. Refresh the application in the browser to verify the application is still working.

7. Open the Chrome DevTools to verify there are no errors being logged to the console.

☑You have successfully completed Lab 2.

©FUNNY ANT, LLC 2.3.0.2 �9

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

Page 19: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

Lab 3: Add Angular & Module LoaderObjectives• Install Angular 2 and a module loader (SystemJS) into an AngularJS project

Steps1. Add the following dependencies to package.json. Copy these lines from

snippets/angular-dependencies.json to save typing.

ℹ This lab will use npm to include additional dependencies. Note that there are currently no (production) dependencies because the project is using the bower package manager instead of npm.

2. Add these additional devDependencies in package.json.

©FUNNY ANT, LLC 2.3.0.2 �10

"dependencies": { "@angular/common": "2.1.1", "@angular/compiler": "2.1.1", "@angular/core": "2.1.1", "@angular/forms": "2.1.1", "@angular/http": "2.1.1", "@angular/platform-browser": "2.1.1", "@angular/platform-browser-dynamic": "2.1.1", "@angular/router": "3.1.1", "@angular/upgrade": "2.1.1", "angular-in-memory-web-api": "0.1.13", "bootstrap": "3.3.7", "core-js": "2.4.1", "reflect-metadata": "0.1.8", "rxjs": "5.0.0-beta.12", "systemjs": "0.19.39", "zone.js": "0.6.25"},

"devDependencies": { "@types/core-js": "0.9.34", "@types/node": "6.0.45", }

Page 20: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

3. Run the npm install command to install the new dependencies.

4. In the npm start script in package.json change the directory the web server is serving from ./app to ./ so the web server can access the node_modules folder at the root of the project.

⚠For this change to be recognized, you will need to stop the web server you started with the npm start

command using Ctrl+C. Restart it by issuing the command npm start. If you refresh the browser at this point in the lab you will see a directory listing. We will get the application working again in the next steps.

5. Move index.html up one level from the app directory to the migrating directory.

6. Add a base tag to index.html at the top of the head section which will cause relative URLs to be resolved back to the /app directory.

7. In index.html, include the script tags for Angular 2 polyfills and SystemJS configuration (which we will create in the next step) at the end of the <head> section. Also load the application by calling System.import. You can copy the scripts from snippets/angular2scripts.txt.

©FUNNY ANT, LLC 2.3.0.2 �11

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

<base href="/app/">

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

Page 21: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

8. Create a systemjs.config.js at the root of the project and configure Angular 2 to use a module loader by copying the code from snippets/systemjs.config.js.

ℹ This configuration is the same as the Angular quick start project but the paths to the npm modules and the app have been adjusted to begin with a slash (/). Also the @angular/upgrade bundle has been included.

9. Rename app.module.ts to app.module.ng1.ts.

10. Update the script tag in index.html to point to app.module.ng1.js instead of app.module.js.

11. Create a new app/app.module.ts file with the code for an Angular 2 AppModule.

☞ The auto importing in your editor or IDE may not work at this point so just type out the imports.

12. Create a new app/main.ts file. Leave the file empty for now.

☞ SystemJS is looking for this file as an entry point to the application.

13. Update the links in phone-list.template.html to begin with a /.

©FUNNY ANT, LLC 2.3.0.2 �12

import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; @NgModule({ imports: [ BrowserModule ]}) export class AppModule{}

<a href="/#!/phones/{{phone.id}}" class="thumb"> <img ng-src="{{phone.imageUrl}}" alt="{{phone.name}}" /> </a> <a href="/#!/phones/{{phone.id}}">{{phone.name}}</a>

Page 22: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

14. Verify the AngularJS application loads and works with Angular 2 and SystemJS installed.

☑You have successfully completed Lab 3.

©FUNNY ANT, LLC 2.3.0.2 �13

Page 23: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

Lab 4: AngularJS & Angular TogetherObjectives• Get AngularJS and Angular working in the same project

Steps1. In main.ts

a. Declare angular as any type.

b. Import the UpgradeAdapter.

c. Instantiate an instance of the class.

d. Bootstrap the application using the UpgradeAdapter.

2. In index.html remove the ng-app attribute because we are now bootstrapping our AngularJS application in code.

©FUNNY ANT, LLC 2.3.0.2 �14

declare var angular: any; import { UpgradeAdapter } from '@angular/upgrade'; import { AppModule } from './app.module'; let upgradeAdapter = new UpgradeAdapter(AppModule);upgradeAdapter.bootstrap(document.documentElement,['phonecatApp']);

<html lang="en" ng-app="phonecatApp">

Page 24: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

3. Refresh the application in the browser to verify the application is still working. Open the Chrome DevTools to verify there are no errors being logged to the console.

☑You have successfully completed lab 4.

©FUNNY ANT, LLC 2.3.0.2 �15

Page 25: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

Lab 5: Upgrading ServicesObjectives• Upgrade an AngularJS service to Angular

Steps1. Import the HttpModule and include it in the AppModule’s

(app.module.ts) imports.

☞ If the import for the HttpModule isn’t being auto-completed you may need to close the project and

reopen it. If you do close the project be sure to restart the web server and the TypeScript compiler in watch mode (npm start, npm run tsc:w).

©FUNNY ANT, LLC 2.3.0.2 �16

import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {HttpModule} from "@angular/http"; @NgModule({ imports: [ BrowserModule, HttpModule ]}) export class AppModule{}

Page 26: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

2. Replace the contents of phone.service.ts with the code below. Copy the code from snippets/phone.service.ts.txt and replace the code currently in the file including the “use strict” at the top of the file.

☞ Note the PhoneData interface has been added to strongly type data being returned.

3. Since it is now an Angular 2 service, in app.module.ts: import the phone.service and add it to the providers array.

©FUNNY ANT, LLC 2.3.0.2 �17

import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; export interface PhoneData { name: string; snippet: string; images: string[];} @Injectable()export class Phone { constructor(private http: Http) { } query(): Observable<PhoneData[]> { return this.http.get(`phones/phones.json`) .map((res: Response) => res.json()); } get(id: string): Observable<PhoneData> { return this.http.get(`phones/${id}.json`) .map((res: Response) => res.json()); }}

import {Phone} from "./core/phone/phone.service"; @NgModule({ imports: [ BrowserModule, HttpModule ], providers: [Phone] }) export class AppModule{}

Page 27: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

4. In index.html, remove the <script> tag for the service since it is now being loaded by the Module loader.

5. In main.ts, register the Angular Phone service as an AngularJS service by calling the downgradeNg2Provider method on the UpgradeService.

⚠ This needs to be done before you bootstrap the application.

6. Update phone-list.component.ts to use Observables and request the dependency as lower-case phone as we defined it in the last step. Copy the code below from snippets/phone-list.component1.txt into phone-list.component.ts.

©FUNNY ANT, LLC 2.3.0.2 �18

angular.module('core.phone') .factory('phone', upgradeAdapter.downgradeNg2Provider(Phone));upgradeAdapter.bootstrap(document.documentElement, ['phonecatApp']);

import { Phone, PhoneData } from '../core/phone/phone.service'; declare var angular: any; class PhoneListController { phones: PhoneData[]; orderProp: string; static $inject = ['phone']; constructor(phone: Phone) { phone.query().subscribe(phones => { this.phones = phones; }); this.orderProp = 'age'; }} angular. module('phoneList').component('phoneList', { templateUrl: '/app/phone-list/phone-list.template.html', controller: PhoneListController});

Page 28: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

7. Update phone-detail.component.ts to use Observables and request the dependency as lower-case phone. Copy the code below from snippets/phone-detail.component1.txt into phone-detail.component.ts.

8. Refresh the application in the browser to verify the application is still working. Open the Chrome DevTools to verify there are no errors being logged to the console.

☑You have successfully completed Lab 5.

©FUNNY ANT, LLC 2.3.0.2 �19

import { Phone, PhoneData } from '../core/phone/phone.service'; declare var angular: any; class PhoneDetailController { phone: PhoneData; mainImageUrl: string; static $inject = ['$routeParams', 'phone']; constructor($routeParams: angular.route.IRouteParamsService, phone: Phone) { let phoneId = $routeParams['phoneId']; phone.get(phoneId).subscribe(data => { this.phone = data; this.setImage(data.images[0]); }); } setImage(imageUrl: string) { this.mainImageUrl = imageUrl; }} angular.module('phoneDetail').component('phoneDetail', { templateUrl: 'phone-detail/phone-detail.template.html', controller: PhoneDetailController});

Page 29: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

Lab 6: Controllers to ComponentsObjectives• Upgrade AngularJS controllers to Angular components

Steps1. Update the AngularJS controller code in phone-list.component.ts to Angular

component code. Copy the code from snippets/phone-list.component2.txt into phone-list.component.ts.• Move the component call up in the file to become a class decorator.• Remove inject property• Implement the filtering and sorting in the component code instead of as a

filter in the view.

©FUNNY ANT, LLC 2.3.0.2 �20

Page 30: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

2. Update phone-list.template.html to become an Angular 2 template. Copy the contents of snippets/phone-list.template.html into phone-list.template.html (overwrite the current code). The changes are:

• Finding and replacing $ctrl with nothing.

• Finding and replacing ng-model with [(ngModel)]• Changing ng-repeat to ngFor.

• Calling getPhones to do filtering and sorting.

• Updating ng-src to [src] and alt= {{value}} to [alt]= value. Note the double-curly braces are no longer needed on the right side.

• Add / to beginning of detail paths. Be sure to do on anchor links.

©FUNNY ANT, LLC 2.3.0.2 �21

Page 31: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

3. Declare the new PhoneListComponent in app.module.ts by adding to the declarations array. Also add the FormsModule to the AppModule imports because ngModel is being used in the template.

©FUNNY ANT, LLC 2.3.0.2 �22

import {FormsModule} from “@angular/forms“; import {PhoneListComponent} from "./phone-list/phone-list.component"; @NgModule({ imports: [ ... FormsModule ], declarations: [ ... PhoneListComponent ], providers: [Phone]}) export class AppModule{}

Page 32: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

4. Register the Angular component with an AngularJS module as a directive. Call downgradeNg2Component so it can be used in AngularJS.

⚠ Be sure to do this before the application is bootstrapped.

☞ Note that when you upgrade a component in Angular 2 you downgrade it to work in your AngularJS

application.

5. In index.html remove the script tag for the phone-list.component.js.

6. Refresh the application in the browser to verify the application is still working. Open the Chrome DevTools to verify there are no errors being logged to the console.

7. Update the AngularJS controller code in phone-detail.component.ts to Angular 2 component code. Copy the code from snippets/phone-detail.component2.txt into phone-detail.component.ts.

©FUNNY ANT, LLC 2.3.0.2 �23

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

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

angular.module('phoneList') .directive( 'phoneList', upgradeAdapter.downgradeNg2Component(PhoneListComponent) as angular.IDirectiveFactory );upgradeAdapter.bootstrap(document.documentElement, ['phonecatApp'], {strictDi: true});

<!--<script src="phone-list/phone-list.component.js"></script>-->

Page 33: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

8. Update phone-detail.template.html to become an Angular 2 template. Copy the contents of snippets/phone-detail.template.html into phone-detail.template.html (overwrite the current code). The changes include.

• Find and replace $ctrl with nothing.

• Replace ng-class with [ngClass].

• Replace ng-repeat with *ngFor. Be sure to use “of” instead of “in” and add a let before the local template variable phone.

• Replace ng-src with [src].

©FUNNY ANT, LLC 2.3.0.2 �24

Page 34: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

9. Declare the new PhoneDetailComponent in app.module.ts by adding it to the declarations array.

1. In app/main.ts, register the Angular 2 component with an AngularJS module as a directive. Call downgradeNg2Component so it can be used in AngularJS.

⚠ Be sure this code happens before the application is bootstrapped.

2. In index.html remove the script tag for the project-detail.component.js.

©FUNNY ANT, LLC 2.3.0.2 �25

import {PhoneDetailComponent} from "./phone-detail/phone-detail.component"; @NgModule({ imports: [ BrowserModule, HttpModule, FormsModule ], declarations: [ PhoneListComponent, PhoneDetailComponent ], providers: [Phone]}) export class AppModule{}

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

//bootstrap app

<!--<script src="phone-detail/phone-detail.component.js"></script>-->

Page 35: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

ℹ PhoneDetailComponent is now an Angular 2 component but has a dependency on the AngularJS $routeParams service.

3. In main.ts, upgrade this AngularJS service to work as an Angular service in the Angular component (running in an AngularJS app).

⚠ Do not register this upgraded service with the Angular 2 module (app.module.ts) in the providers

array.

4. Refresh the application in the browser and the phones will not load. Open the Chrome DevTools and you should see this error being logged to the console.

ℹ We will rewrite the filter to an Angular 2 pipe to correct this error in the next section.

☑You have successfully completed Lab 6.

©FUNNY ANT, LLC 2.3.0.2 �26

upgradeAdapter.upgradeNg1Provider(‘$routeParams');

//bootstrap app

Page 36: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

Lab 7: Filter to PipeObjectives• Rewrite AngularJS filter to Angular pipe.

Steps1. Rename checkmark.filter.ts to checkmark.pipe.ts.

2. Replace the contents of checkmark.pipe.ts with an Angular 2 pipe that has a transform method with the same implementation as the original filter. You can copy the code from snippets/checkmark.pipe.txt and replace all the current code in the file.

3. In app.module.ts add CheckmarkPipe to the declarations array.

©FUNNY ANT, LLC 2.3.0.2 �27

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

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

declarations: [ PhoneListComponent, PhoneDetailComponent, CheckmarkPipe],

Page 37: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

4. Remove the script tag from index.html with a src of checkmark.filter.ts. It is no longer needed because the CheckmarkPipe is loaded by the module loader.

5. Refresh the application in the browser to verify the application is still working including the checkmarks on the details page. Open the Chrome DevTools to verify there are no errors being logged to the console.

☑You have successfully completed Lab 7.

©FUNNY ANT, LLC 2.3.0.2 �28

<!--<script src="core/checkmark/checkmark.filter.js"></script>-->

Page 38: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

Lab 8: Upgrade RouterObjectives• Upgrade the router and bootstrap to Angular 2

Steps1. Create a new file app/app.component.ts and add the following code to

create an AppComponent.

2. Replace the ng-view directive in index.html with the <phonecat-app></phonecat-app> tag.

©FUNNY ANT, LLC 2.3.0.2 �29

import { Component } from '@angular/core'; @Component({ selector: 'phonecat-app', template: `<router-outlet></router-outlet> ̀}) export class AppComponent {}

<div class="view-container"> <phonecat-app></phonecat-app> </div>

Page 39: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

3. Create the AppRoutingModule (app/app-routing.module.ts) with the following code. Copy the code from snippets/app-routing.module.ts.txt.

4. Update AppModule to:

a. Import AppRoutingModule.b. Declare and bootstrap AppComponent.

©FUNNY ANT, LLC 2.3.0.2 �30

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

import {AppRoutingModule} from "./app.routing.module"; import {AppComponent} from "./app.component"; @NgModule({ imports: [ ... FormsModule, AppRoutingModule ], declarations: [ ..., AppComponent ], providers: [Phone], bootstrap: [AppComponent] }) export class AppModule{}

Page 40: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

5. Update the ProjectDetailComponent to use the Angular 2 service ActivatedRoute instead of $routeParams. You can copy the code from snippets/project-detail.component3.txt.

©FUNNY ANT, LLC 2.3.0.2 �31

Page 41: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

6. Update project-list.template.html to use Angular 2 routerLink directives.

7. In main.ts, change the application bootstrap from using UpgradeAdapter to using platformBrowserDynamic.

8. Refresh the application in the browser to verify the application is still working. Open the Chrome DevTools to verify there are no errors being logged to the console.

☞ If you are getting errors or the application is not working be sure the typescript compiler is still running in watch mode and successfully compiled your code.

☑You have successfully completed Lab 8.

©FUNNY ANT, LLC 2.3.0.2 �32

import {platformBrowserDynamic} from "@angular/platform-browser-dynamic";

//bootstrap app// upgradeAdapter.bootstrap(document.documentElement,// ['phonecatApp'],// {strictDi: true});platformBrowserDynamic().bootstrapModule(AppModule);

Page 42: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

Lab 9: Remove AngularJSObjectives• Remove AngularJS from the project

Steps1. Remove all references to UpgradeAdapter from main.ts. Also remove the

declaration of angular as any. The following code is all that should remain.

2. Delete all the AngularJS specific files listed below as well as any .js files with the same name that were generated by the compiler.

• app/app.module.ng1.ts

• app/app.config.ts

• app/app.animations.ts

• app/core/core.module.ts

• app/core/phone/phone.module.ts

• app/phone-detail/phone-detail.module.ts

• app/phone-list/phone-list.module.ts

©FUNNY ANT, LLC 2.3.0.2 �33

import { AppModule } from './app.module'; import {platformBrowserDynamic} from "@angular/platform-browser-dynamic"; platformBrowserDynamic().bootstrapModule(AppModule);

Page 43: Migration Strategies - zitiso.com · Migration Strategies AngularJS to Angular Migration high-level approaches •Rewrite •Maintain •Migrate. 4/12/17 2 ... • Using a Module

ANGULAR 2 LAB MANUAL

3. Remove all the AngularJS script references in index.html to the files deleted in the last step. When you are done it should look as follows. You can copy this code from snippets/index.html.

4. Copy the command below from snippets/type-definitions-uninstall.txt. Uninstall the AngularJS typings by running the command from the migrating directory.

5. Refresh the application in the browser to verify the application is still working. Open the Chrome DevTools to verify there are no errors being logged to the console.

☑You have successfully completed Lab 9.

©FUNNY ANT, LLC 2.3.0.2 �34

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

npm uninstall @types/jasmine @types/angular @types/angular-animate @types/angular-cookies @types/angular-mocks @types/angular-resource @types/angular-route @types/angular-sanitize --save-dev