This repository was archived by the owner on Dec 4, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 877
/
Copy pathupgrade.jade
1854 lines (1422 loc) · 84.7 KB
/
upgrade.jade
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
include ../_util-fns
:marked
_Angular_ is the name for the Angular of today and tomorrow.
_AngularJS_ is the name for all v1.x versions of Angular.
AngularJS apps are great.
Always consider the business case before moving to Angular.
An important part of that case is the time and effort to get there.
This guide describes the built-in tools for efficiently migrating AngularJS projects over to the
Angular platform, a piece at a time.
Some applications will be easier to upgrade than others, and there are
ways in which we can make it easier for ourselves. It is possible to
prepare and align AngularJS applications with Angular even before beginning
the upgrade process. These preparation steps are all about making the code
more decoupled, more maintainable, and up to speed with modern development
tools. That means the preparation work will not only make the eventual upgrade
easier, but will also generally improve our AngularJS applications.
One of the keys to a successful upgrade is to do it incrementally,
by running the two frameworks side by side in the same application, and
porting AngularJS components to Angular one by one. This makes it possible
to upgrade even large and complex applications without disrupting other
business, because the work can be done collaboratively and spread over
a period of time. The `upgrade` module in Angular has been designed to
make incremental upgrading seamless.
1. [Preparation](#preparation)
1. [Follow the Angular Style Guide](#follow-the-angular-style-guide)
2. [Using a Module Loader](#using-a-module-loader)
3. [Migrating to TypeScript](#migrating-to-typescript)
4. [Using Component Directives](#using-component-directives)
2. [Upgrading with The Upgrade Module](#upgrading-with-the-upgrade-module)
1. [How The Upgrade Module Works](#how-the-upgrade-module-works)
2. [Bootstrapping hybrid](#bootstrapping-hybrid-applications)
3. [Using Angular Components from AngularJS Code](#using-angular-components-from-angularjs-code)
4. [Using AngularJS Component Directives from Angular Code](#using-angularjs-component-directives-from-angular-code)
5. [Projecting AngularJS Content into Angular Components](#projecting-angularjs-content-into-angular-components)
6. [Transcluding Angular Content into AngularJS Component Directives](#transcluding-angular-content-into-angularjs-component-directives)
7. [Making AngularJS Dependencies Injectable to Angular](#making-angularjs-dependencies-injectable-to-angular)
8. [Making Angular Dependencies Injectable to AngularJS](#making-angular-dependencies-injectable-to-angularjs)
9. [Using Ahead-of-time compilation with hybrid apps](#using-ahead-of-time-compilation-with-hybrid-apps)
10. [Dividing routes between Angular and AngularJS](#dividing-routes-between-angular-and-angularjs)
3. [PhoneCat Upgrade Tutorial](#phonecat-upgrade-tutorial)
1. [Switching to TypeScript](#switching-to-typescript)
2. [Installing Angular](#installing-angular)
3. [Bootstrapping a hybrid PhoneCat](#bootstrapping-a-hybrid-phonecat)
4. [Upgrading the Phone service](#upgrading-the-phone-service)
5. [Upgrading Components](#upgrading-components)
6. [AoT compile the hybrid app](#aot-compile-the-hybrid-app)
7. [Adding The Angular Router And Bootstrap](#adding-the-angular-router-and-bootstrap)
8. [Say Goodbye to AngularJS](#say-goodbye-to-angularjs)
3. [Appendix: Upgrading PhoneCat Tests](#appendix-upgrading-phonecat-tests)
.l-main-section
:marked
## Preparation
There are many ways to structure AngularJS applications. When we begin
to upgrade these applications to Angular, some will turn out to be
much more easy to work with than others. There are a few key techniques
and patterns that we can apply to future proof our apps even before we
begin the migration.
### Follow the Angular Style Guide
The [AngularJS Style Guide](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#single-responsibility)
collects patterns and practices that have been proven to result in
cleaner and more maintainable AngularJS applications. It contains a wealth
of information about how to write and organize Angular code - and equally
importantly - how **not** to write and organize Angular code.
Angular is a reimagined version of the best parts of AngularJS. In that
sense, its goals are the same as the Angular Style Guide's: To preserve
the good parts of AngularJS, and to avoid the bad parts. There's a lot
more to Angular than just that of course, but this does mean that
*following the style guide helps make your AngularJS app more closely
aligned with Angular*.
There are a few rules in particular that will make it much easier to do
*an incremental upgrade* using the Angular `upgrade` module:
* The [Rule of 1](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#single-responsibility)
states that there should be one component per file. This not only makes
components easy to navigate and find, but will also allow us to migrate
them between languages and frameworks one at a time. In this example application,
each controller, component, service, and filter is in its own source file.
* The [Folders-by-Feature Structure](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#folders-by-feature-structure)
and [Modularity](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#modularity)
rules define similar principles on a higher level of abstraction: Different parts of the
application should reside in different directories and Angular modules.
When an application is laid out feature per feature in this way, it can also be
migrated one feature at a time. For applications that don't already look like
this, applying the rules in the Angular style guide is a highly recommended
preparation step. And this is not just for the sake of the upgrade - it is just
solid advice in general!
### Using a Module Loader
When we break application code down into one component per file, we often end
up with a project structure with a large number of relatively small files. This is
a much neater way to organize things than a small number of large files, but it
doesn't work that well if you have to load all those files to the HTML page with
<script> tags. Especially when you also have to maintain those tags in the correct
order. That's why it's a good idea to start using a *module loader*.
Using a module loader such as [SystemJS](https://github.com/systemjs/systemjs),
[Webpack](http://webpack.github.io/), or [Browserify](http://browserify.org/)
allows us to use the built-in module systems of the TypeScript or ES2015 languages in our apps.
We can use the `import` and `export` features that explicitly specify what code can
and will be shared between different parts of the application. For ES5 applications
we can use CommonJS style `require` and `module.exports` features. In both cases,
the module loader will then take care of loading all the code the application needs
in the correct order.
When we then take our applications into production, module loaders also make it easier
to package them all up into production bundles with batteries included.
:marked
### Migrating to TypeScript
If part of our Angular upgrade plan is to also take TypeScript into use, it makes
sense to bring in the TypeScript compiler even before the upgrade itself begins.
This means there's one less thing to learn and think about during the actual upgrade.
It also means we can start using TypeScript features in our AngularJS code.
Since TypeScript is a superset of ECMAScript 2015, which in turn is a superset
of ECMAScript 5, "switching" to TypeScript doesn't necessarily require anything
more than installing the TypeScript compiler and switching renaming files from
`*.js` to `*.ts`. But just doing that is not hugely useful or exciting, of course.
Additional steps like the following can give us much more bang for the buck:
* For applications that use a module loader, TypeScript imports and exports
(which are really ECMAScript 2015 imports and exports) can be used to organize
code into modules.
* Type annotations can be gradually added to existing functions and variables
to pin down their types and get benefits like build-time error checking,
great autocompletion support and inline documentation.
* JavaScript features new to ES2015, like arrow functions, `let`s and `const`s,
default function parameters, and destructuring assignments can also be gradually
added to make the code more expressive.
* Services and controllers can be turned into *classes*. That way they'll be a step
closer to becoming Angular service and component classes, which will make our
life easier once we do the upgrade.
### Using Component Directives
In Angular, components are the main primitive from which user interfaces
are built. We define the different parts of our UIs as components, and then
compose the UI by using components in our templates.
You can also do this in AngularJS, using *component directives*. These are
directives that define their own templates, controllers, and input/output bindings -
the same things that Angular components define. Applications built with
component directives are much easier to migrate to Angular than applications
built with lower-level features like `ng-controller`, `ng-include`, and scope
inheritance.
To be Angular compatible, an AngularJS component directive should configure
these attributes:
* `restrict: 'E'`. Components are usually used as elements.
* `scope: {}` - an isolate scope. In Angular, components are always isolated
from their surroundings, and we should do this in AngularJS too.
* `bindToController: {}`. Component inputs and outputs should be bound
to the controller instead of using the `$scope`.
* `controller` and `controllerAs`. Components have their own controllers.
* `template` or `templateUrl`. Components have their own templates.
Component directives may also use the following attributes:
* `transclude: true`, if the component needs to transclude content from elsewhere.
* `require`, if the component needs to communicate with some parent component's
controller.
Component directives **may not** use the following attributes:
* `compile`. This will not be supported in Angular.
* `replace: true`. Angular never replaces a component element with the
component template. This attribute is also deprecated in AngularJS.
* `priority` and `terminal`. While AngularJS components may use these,
they are not used in Angular and it is better not to write code
that relies on them.
An AngularJS component directive that is fully aligned with the Angular
architecture may look something like this:
+makeExample('upgrade-module/ts/src/app/hero-detail.directive.ts')
:marked
AngularJS 1.5 introduces the [component API](https://docs.angularjs.org/api/ng/type/angular.Module)
that makes it easier to define directives like these. It is a good idea to use
this API for component directives for several reasons:
* It requires less boilerplate code.
* It enforces the use of component best practices like `controllerAs`.
* It has good default values for directive attributes like `scope` and `restrict`.
The component directive example from above looks like this when expressed
using the component API:
+makeExample('upgrade-module/ts/src/app/upgrade-io/hero-detail.component.ts')
:marked
Controller lifecycle hook methods `$onInit()`, `$onDestroy()`, and `$onChanges()`
are another convenient feature that AngularJS 1.5 introduces. They all have nearly
exact [equivalents in Angular](lifecycle-hooks.html), so organizing component lifecycle
logic around them will ease the eventual Angular upgrade process.
.l-main-section
:marked
## Upgrading with The Upgrade Module
The `upgrade` module in Angular is a very useful tool for upgrading
anything but the smallest of applications. With it we can mix and match
AngularJS and Angular components in the same application and have them interoperate
seamlessly. That means we don't have to do the upgrade work all at once,
since there's a natural coexistence between the two frameworks during the
transition period.
### How The Upgrade Module Works
The primary tool provided by the upgrade module is called the `UpgradeModule`.
This is a service that can bootstrap and manage hybrid applications that support
both Angular and AngularJS code.
When we use `UpgradeModule`, what we're really doing is *running both versions
of Angular at the same time*. All Angular code is running in the Angular
framework, and AngularJS code in the AngularJS framework. Both of these are the
actual, fully featured versions of the frameworks. There is no emulation going on,
so we can expect to have all the features and natural behavior of both frameworks.
What happens on top of this is that components and services managed by one
framework can interoperate with those from the other framework. This happens
in three main areas: Dependency injection, the DOM, and change detection.
#### Dependency Injection
Dependency injection is front and center in both AngularJS and
Angular, but there are some key differences between the two
frameworks in how it actually works.
table
tr
th AngularJS
th Angular
tr
td
:marked
Dependency injection tokens are always strings
td
:marked
Tokens [can have different types](../guide/dependency-injection.html).
They are often classes. They may also be strings.
tr
td
:marked
There is exactly one injector. Even in multi-module applications,
everything is poured into one big namespace.
td
:marked
There is a [tree hierarchy of injectors](../guide/hierarchical-dependency-injection.html),
with a root injector and an additional injector for each component.
:marked
Even accounting for these differences we can still have dependency injection
interoperability. The `UpgradeModule` resolves the differences and makes
everything work seamlessly:
* We can make AngularJS services available for injection to Angular code
by *upgrading* them. The same singleton instance of each service is shared
between the frameworks. In Angular these services will always be in the
*root injector* and available to all components.
* We can also make Angular services available for injection to AngularJS code
by *downgrading* them. Only services from the Angular root injector can
be downgraded. Again, the same singleton instances are shared between the frameworks.
When we register a downgrade, we explicitly specify a *string token* that we want to
use in AngularJS.
figure.image-display
img(src="/resources/images/devguide/upgrade/injectors.png" alt="The two injectors in a hybrid application" width="700")
:marked
#### Components and the DOM
What we'll find in the DOM of a hybrid application are components and
directives from both AngularJS and Angular. These components
communicate with each other by using the input and output bindings
of their respective frameworks, which the `UpgradeModule` bridges
together. They may also communicate through shared injected dependencies,
as described above.
There are two key things to understand about what happens in the DOM
of a hybrid application:
1. Every element in the DOM is owned by exactly one of the two
frameworks. The other framework ignores it. If an element is
owned by AngularJS, Angular treats it as if it didn't exist,
and vice versa.
2. The root of the application *is always an AngularJS template*.
So a hybrid application begins life as an AngularJS application,
and it is AngularJS that processes its root template. Angular then steps
into the picture when an Angular component is used somewhere in
the application templates. That component's view will then be managed
by Angular, and it may use any number of Angular components and
directives.
Beyond that, we may interleave the two frameworks as much as we need to.
We always cross the boundary between the two frameworks by one of two
ways:
1. By using a component from the other framework: An AngularJS template
using an Angular component, or an Angular template using an
AngularJS component.
2. By transcluding or projecting content from the other framework. The
`UpgradeModule` bridges the related concepts of AngularJS transclusion
and Angular content projection together.
figure.image-display
img(src="/resources/images/devguide/upgrade/dom.png" alt="DOM element ownership in a hybrid application" width="500")
:marked
Whenever we use a component that belongs to the other framework, a
switch between framework boundaries occurs. However, that switch only
happens to the *children* of the component element. Consider a situation
where we use an Angular component from AngularJS like this:
code-example(language="html" escape="html").
<a-component></a-component>
:marked
The DOM element `<a-component>` will remain to be an AngularJS managed
element, because it's defined in an AngularJS template. That also
means you can apply additional AngularJS directives to it, but *not*
Angular directives. It is only in the template of the `<a-component>`
where Angular steps in. This same rule also applies when you
use AngularJS component directives from Angular.
:marked
#### Change Detection
Change detection in AngularJS is all about `scope.$apply()`. After every
event that occurs, `scope.$apply()` gets called. This is done either
automatically by the framework, or in some cases manually by our own
code. It is the point in time when change detection occurs and data
bindings get updated.
In Angular things are different. While change detection still
occurs after every event, no one needs to call `scope.$apply()` for
that to happen. This is because all Angular code runs inside something
called the [Angular zone](../api/core/index/NgZone-class.html). Angular always
knows when the code finishes, so it also knows when it should kick off
change detection. The code itself doesn't have to call `scope.$apply()`
or anything like it.
In the case of hybrid applications, the `UpgradeModule` bridges the
AngularJS and Angular approaches. Here's what happens:
* Everything that happens in the application runs inside the Angular zone.
This is true whether the event originated in AngularJS or Angular code.
The zone triggers Angular change detection after every event.
* The `UpgradeModule` will invoke the AngularJS `$rootScope.$apply()` after
every turn of the Angular zone. This also triggers AngularJS change
detection after every event.
figure.image-display
img(src="/resources/images/devguide/upgrade/change_detection.png" alt="Change detection in a hybrid application" width="600")
:marked
What this means in practice is that we do not need to call `$apply()` in
our code, regardless of whether it is in AngularJS on Angular. The
`UpgradeModule` does it for us. We *can* still call `$apply()` so there
is no need to remove such calls from existing code. Those calls just don't
have any effect in a hybrid application.
:marked
When we downgrade an Angular component and then use it from AngularJS,
the component's inputs will be watched using AngularJS change detection.
When those inputs change, the corresponding properties in the component
are set. We can also hook into the changes by implementing the
[OnChanges](../api/core/index/OnChanges-class.html) interface in the component,
just like we could if it hadn't been downgraded.
Correspondingly, when we upgrade an AngularJS component and use it from Angular,
all the bindings defined for the component directive's `scope` (or `bindToController`)
will be hooked into Angular change detection. They will be treated
as regular Angular inputs and set onto the scope (or controller) when
they change.
### Using UpgradeModule with Angular _NgModules_
Both AngularJS and Angular have their own concept of modules
to help organize an application into cohesive blocks of functionality.
Their details are quite different in architecture and implementation.
In AngularJS, you add Angular assets to the `angular.module` property.
In Angular, you create one or more classes adorned with an `NgModule` decorator
that describes Angular assets in metadata. The differences blossom from there.
In a hybrid application we run both versions of Angular at the same time.
That means that we need at least one module each from both AngularJS and Angular.
We will import `UpgradeModule` inside our Angular module, and then use it for
bootstrapping our AngularJS module. Let's see how.
.l-sub-section
:marked
Learn more about Angular modules at the [NgModule guide](ngmodule.html).
:marked
### Bootstrapping hybrid applications
The first step to upgrading an application using the `UpgradeModule` is
always to bootstrap it as a hybrid that supports both AngularJS and
Angular, but still is an AngularJS app at top level.
Pure AngularJS applications can be bootstrapped in two ways: By using an `ng-app`
directive somewhere on the HTML page, or by calling
[angular.bootstrap](https://docs.angularjs.org/api/ng/function/angular.bootstrap)
from JavaScript. In Angular, only the second method is possible - there is
no `ng-app` in Angular. This is also the case for hybrid applications.
Therefore, it is a good preliminary step to switch AngularJS applications to use the
JavaScript bootstrap method even before switching them to hybrid mode.
Say we have an `ng-app` driven bootstrap such as this one:
+makeExample('upgrade-module/ts/src/index-ng-app.html', null, null, {otl: /(ng-app.*ng-strict-di)/})
:marked
We can remove the `ng-app` and `ng-strict-di` directives from the HTML
and instead switch to calling `angular.bootstrap` from JavaScript, which
will result in the same thing:
+makeExample('upgrade-module/ts/src/app/ajs-bootstrap/app.module.ts', 'bootstrap')
:marked
Now introduce Angular to the project. Inspired by instructions in
[the Setup](setup.html), you can selectively copy in material from the
<a href="https://github.com/angular/quickstart" target="_blank">QuickStart github repository</a>.
Next, create an `app.module.ts` file and add the following `NgModule` class:
+makeExample('upgrade-module/ts/src/app/ajs-a-hybrid-bootstrap/app.module.ts', 'ngmodule')
:marked
This bare minimum `NgModule` imports `BrowserModule`, the module every Angular browser-based app must have.
It also imports `UpgradeModule` from `@angular/upgrade/static`, and adds an override to prevent
Angular from bootstrapping itself in the form of the `ngDoBootstrap` empty class method.
Now we bootstrap `AppModule` using `platformBrowserDynamic`'s `bootstrapModule` method.
Then we use dependency injection to get a hold of the `UpgradeModule` instance in `AppModule`,
and use it to bootstrap our AngularJS app.
The `upgrade.bootstrap` method takes the exact same arguments as [angular.bootstrap](https://docs.angularjs.org/api/ng/function/angular.bootstrap):
+makeExample('upgrade-module/ts/src/app/ajs-a-hybrid-bootstrap/app.module.ts', 'bootstrap')
:marked
We also need to install the `@angular/upgrade` package via `npm install @angular/upgrade --save`
and add a mapping for the `@angular/upgrade/static` package:
+makeExample('upgrade-module/ts/src/systemjs.config.1.js', 'upgrade-static-umd', 'systemjs.config.js (map)')
:marked
Congratulations! You're running a hybrid application! The
existing AngularJS code works as before _and_ you're ready to run Angular code.
:marked
### Using Angular Components from AngularJS Code
figure
img(src="/resources/images/devguide/upgrade/ajs-to-a.png" alt="Using an Angular component from AngularJS code" align="left" style="width:250px; margin-left:-40px;margin-right:10px" )
:marked
Once we're running a hybrid app, we can start the gradual process of upgrading
code. One of the more common patterns for doing that is to use an Angular component
in an AngularJS context. This could be a completely new component or one that was
previously AngularJS but has been rewritten for Angular.
Say we have a simple Angular component that shows information about a hero:
+makeExample('upgrade-module/ts/src/app/downgrade-static/hero-detail.component.ts', null, 'hero-detail.component.ts')
:marked
If we want to use this component from AngularJS, we need to *downgrade* it
using the `downgradeComponent()` method. What we get when we do that is an AngularJS
*directive*, which we can then register into our AngularJS module:
+makeExample('upgrade-module/ts/src/app/downgrade-static/app.module.ts', 'downgradecomponent')
:marked
Because `HeroDetailComponent` is an Angular component, we must also add it to the
`declarations` in the `AppModule`.
And because this component is being used from the AngularJS module, and is an entry point into
our Angular application, we also need to add it to the `entryComponents` for our
Angular module.
+makeExample('upgrade-module/ts/src/app/downgrade-static/app.module.ts', 'ngmodule')
.l-sub-section
:marked
All Angular components, directives and pipes must be declared in an NgModule.
:marked
The net result is an AngularJS directive called `heroDetail`, that we can
use like any other directive in our AngularJS templates.
+makeExample('upgrade-module/ts/src/index-downgrade-static.html', 'usecomponent')
.alert.is-helpful
:marked
Note that this AngularJS is an element directive (`restrict: 'E'`) called `heroDetail`.
An AngularJS element directive is matched based on its _name_.
*The `selector` metadata of the downgraded Angular component is ignored.*
:marked
Most components are not quite this simple, of course. Many of them
have *inputs and outputs* that connect them to the outside world. An
Angular hero detail component with inputs and outputs might look
like this:
+makeExample('upgrade-module/ts/src/app/downgrade-io/hero-detail.component.ts', null, 'hero-detail.component.ts')
:marked
These inputs and outputs can be supplied from the AngularJS template, and the
`downgradeComponent()` method takes care of bridging them over via the `inputs`
and `outputs` arrays:
+makeExample('upgrade-module/ts/src/app/downgrade-io/app.module.ts', 'downgradecomponent')
+makeExample('upgrade-module/ts/src/index-downgrade-io.html', 'usecomponent')
:marked
Note that even though we are in an AngularJS template, **we're using Angular
attribute syntax to bind the inputs and outputs**. This is a requirement for downgraded
components. The expressions themselves are still regular AngularJS expressions.
.callout.is-important
header Use kebab-case for downgraded component attributes
:marked
There's one notable exception to the rule of using Angular attribute syntax
for downgraded components. It has to do with input or output names that consist
of multiple words. In Angular we would bind these attributes using camelCase:
code-example(format="").
[myHero]="hero"
:marked
But when using them from AngularJS templates, we need to use kebab-case:
code-example(format="").
[my-hero]="hero"
:marked
The `$event` variable can be used in outputs to gain access to the
object that was emitted. In this case it will be the `Hero` object, because
that is what was passed to `this.deleted.emit()`.
Since this is an AngularJS template, we can still use other AngularJS
directives on the element, even though it has Angular binding attributes on it.
For example, we can easily make multiple copies of the component using `ng-repeat`:
+makeExample('upgrade-module/ts/src/index-downgrade-io.html', 'userepeatedcomponent')
:marked
### Using AngularJS Component Directives from Angular Code
figure
img(src="/resources/images/devguide/upgrade/a-to-ajs.png" alt="Using an AngularJS component from Angular code" align="left" style="width:250px; margin-left:-40px;margin-right:10px" )
:marked
So, we can write an Angular component and then use it from AngularJS
code. This is very useful when we start our migration from lower-level
components and work our way up. But in some cases it is more convenient
to do things in the opposite order: To start with higher-level components
and work our way down. This too can be done using the `UpgradeModule`.
We can *upgrade* AngularJS component directives and then use them from
Angular.
Not all kinds of AngularJS directives can be upgraded. The directive
really has to be a *component directive*, with the characteristics
[described in the preparation guide above](#using-component-directives).
Our safest bet for ensuring compatibility is using the
[component API](https://docs.angularjs.org/api/ng/type/angular.Module)
introduced in AngularJS 1.5.
A simple example of an upgradable component is one that just has a template
and a controller:
+makeExample('upgrade-module/ts/src/app/upgrade-static/hero-detail.component.ts', 'hero-detail', 'hero-detail.component.ts')
:marked
We can *upgrade* this component to Angular using the `UpgradeComponent` class.
By creating a new Angular **directive** that extends `UpgradeComponent` and doing a `super` call
inside it's constructor, we have a fully upgrade AngularJS component to be used inside Angular.
All that is left is to add it to `AppModule`'s `declarations` array.
+makeExample('upgrade-module/ts/src/app/upgrade-static/hero-detail.component.ts', 'hero-detail-upgrade', 'hero-detail.component.ts')
+makeExample('upgrade-module/ts/src/app/upgrade-static/app.module.ts', 'hero-detail-upgrade', 'hero-detail.component.ts')
.alert.is-helpful
:marked
Upgraded components are Angular **directives**, instead of **components**, because Angular
is unaware that AngularJS will create elements under it. As far as Angular knows, the upgraded
component is just a directive - a tag - and Angular doesn't have to concern itself with
it's children.
:marked
An upgraded component may also have inputs and outputs, as defined by
the scope/controller bindings of the original AngularJS component
directive. When we use the component from an Angular template,
we provide the inputs and outputs using **Angular template syntax**,
with the following rules:
table
tr
th
th Binding definition
th Template syntax
tr
th Attribute binding
td
:marked
`myAttribute: '@myAttribute'`
td
:marked
`<my-component myAttribute="value">`
tr
th Expression binding
td
:marked
`myOutput: '&myOutput'`
td
:marked
`<my-component (myOutput)="action()">`
tr
th One-way binding
td
:marked
`myValue: '<myValue'`
td
:marked
`<my-component [myValue]="anExpression">`
tr
th Two-way binding
td
:marked
`myValue: '=myValue'`
td
:marked
As a two-way binding: `<my-component [(myValue)]="anExpression">`.
Since most AngularJS two-way bindings actually only need a one-way binding
in practice, `<my-component [myValue]="anExpression">` is often enough.
:marked
As an example, say we have a hero detail AngularJS component directive
with one input and one output:
+makeExample('upgrade-module/ts/src/app/upgrade-io/hero-detail.component.ts', 'hero-detail-io', 'hero-detail.component.ts')
:marked
We can upgrade this component to Angular, annotate inputs and outputs in the upgrade directive,
and then provide the input and output using Angular template syntax:
+makeExample('upgrade-module/ts/src/app/upgrade-io/hero-detail.component.ts', 'hero-detail-io-upgrade', 'hero-detail.component.ts')
+makeExample('upgrade-module/ts/src/app/upgrade-io/container.component.ts', null, 'container.component.ts')
:marked
### Projecting AngularJS Content into Angular Components
figure
img(src="/resources/images/devguide/upgrade/ajs-to-a-with-projection.png" alt="Projecting AngularJS content into Angular" align="left" style="width:250px; margin-left:-40px;margin-right:10px" )
:marked
When we are using a downgraded Angular component from an AngularJS
template, the need may arise to *transclude* some content into it. This
is also possible. While there is no such thing as transclusion in Angular,
there is a very similar concept called *content projection*. The `UpgradeModule`
is able to make these two features interoperate.
Angular components that support content projection make use of an `<ng-content>`
tag within them. Here's an example of such a component:
+makeExample('upgrade-module/ts/src/app/ajs-to-a-projection/hero-detail.component.ts', null, 'hero-detail.component.ts')
:marked
When using the component from AngularJS, we can supply contents for it. Just
like they would be transcluded in AngularJS, they get projected to the location
of the `<ng-content>` tag in Angular:
+makeExample('upgrade-module/ts/src/index-ajs-to-a-projection.html', 'usecomponent')
.alert.is-helpful
:marked
When AngularJS content gets projected inside an Angular component, it still
remains in "AngularJS land" and is managed by the AngularJS framework.
:marked
### Transcluding Angular Content into AngularJS Component Directives
figure
img(src="/resources/images/devguide/upgrade/a-to-ajs-with-transclusion.png" alt="Projecting Angular content into AngularJS" align="left" style="width:250px; margin-left:-40px;margin-right:10px" )
:marked
Just like we can project AngularJS content into Angular components,
we can *transclude* Angular content into AngularJS components, whenever
we are using upgraded versions from them.
When an AngularJS component directive supports transclusion, it may use
the `ng-transclude` directive in its template to mark the transclusion
point:
+makeExample('upgrade-module/ts/src/app/a-to-ajs-transclusion/hero-detail.component.ts', null, 'hero-detail.component.ts')
.alert.is-helpful
:marked
The directive also needs to have the `transclude: true` option enabled.
It is on by default for component directives defined with the
1.5 component API.
:marked
If we upgrade this component and use it from Angular, we can populate
the component tag with contents that will then get transcluded:
+makeExample('upgrade-module/ts/src/app/a-to-ajs-transclusion/container.component.ts', null, 'container.component.ts')
:marked
### Making AngularJS Dependencies Injectable to Angular
When running a hybrid app, we may bump into situations where we need to have
some AngularJS dependencies to be injected to Angular code. This may be
because we have some business logic still in AngularJS services, or because
we need some of AngularJS's built-in services like `$location` or `$timeout`.
In these situations, it is possible to *upgrade* an AngularJS provider to
Angular. This makes it possible to then inject it somewhere in Angular
code. For example, we might have a service called `HeroesService` in AngularJS:
+makeExample('upgrade-module/ts/src/app/ajs-to-a-providers/heroes.service.ts', null, 'heroes.service.ts')
:marked
We can upgrade the service using a Angular [Factory provider](./dependency-injection.html#factory-providers)
that requests the service from the AngularJS `$injector`.
We recommend declaring the Factory Provider in a separate `ajs-upgraded-providers.ts` file
so that they are all together, making it easier to reference them, create new ones and
delete them once the upgrade is over.
It's also recommended to export the `heroesServiceFactory` function so that Ahead-of-Time
compilation can pick it up.
+makeExample('upgrade-module/ts/src/app/ajs-to-a-providers/ajs-upgraded-providers.ts', null, 'ajs-upgraded-providers.ts')
+makeExample('upgrade-module/ts/src/app/ajs-to-a-providers/app.module.ts', 'register', 'app.module.ts')
:marked
We can then inject it in Angular using it's class as a type annotation:
+makeExample('upgrade-module/ts/src/app/ajs-to-a-providers/hero-detail.component.ts', null, 'hero-detail.component.ts')
.alert.is-helpful
:marked
In this example we upgraded a service class, which has the added benefit that
we can use a TypeScript type annotation when we inject it. While it doesn't
affect how the dependency is handled, it enables the benefits of static type
checking. This is not required though, and any AngularJS service, factory, or
provider can be upgraded.
:marked
### Making Angular Dependencies Injectable to AngularJS
In addition to upgrading AngularJS dependencies, we can also *downgrade*
Angular dependencies, so that we can use them from AngularJS. This can be
useful when we start migrating services to Angular or creating new services
in Angular while we still have components written in AngularJS.
For example, we might have an Angular service called `Heroes`:
+makeExample('upgrade-module/ts/src/app/a-to-ajs-providers/heroes.ts', null, 'heroes.ts')
:marked
Again, as with Angular components, register the provider with the `NgModule` by adding it to the module's `providers` list.
+makeExample('upgrade-module/ts/src/app/a-to-ajs-providers/app.module.ts', 'ngmodule', 'app.module.ts')
:marked
Now wrap the Angular `Heroes` in an *AngularJS factory function* using `downgradeInjectable()`.
and plug the factory into an AngularJS module.
The name of the AngularJS dependency is up to you:
+makeExample('upgrade-module/ts/src/app/a-to-ajs-providers/app.module.ts', 'register', 'app.module.ts')
:marked
After this, the service is injectable anywhere in our AngularJS code:
+makeExample('upgrade-module/ts/src/app/a-to-ajs-providers/hero-detail.component.ts', null, 'hero-detail.component.ts')
:marked
## Using Ahead-of-time compilation with hybrid apps
We can take advantage of Ahead-of-time (AoT) compilation on hybrid apps just like on any other
Angular application.
The setup for an hybrid app is mostly the same as described in
[the Ahead-of-time Compilation chapter](../cookbook/aot-compiler.html)
save for differences in `index.html` and `main-aot.ts`
Our `index.html` will likely have script tags loading AngularJS files, so the `index.html` we
use for AoT must also load those files.
An easy way to copy them is by adding each to the `copy-dist-files.js` file.
We also need to use `UpgradeModule` to bootstrap a hybrid app after bootstrapping the
Module Factory:
+makeExample('upgrade-phonecat-2-hybrid/ts/app/main-aot.ts', null, 'app/main-aot.ts')
:marked
And that's all we need to get the full benefit of AoT for Angular apps!
.alert.is-helpful
:marked
The AoT metadata collector will not detect lifecycle hook methods on a parent class' prototype,
so in order for upgraded components to work we needs to implement the lifecycle hooks
on the upgraded component class and forward them to the `UpgradeComponent` parent.
:marked
## Dividing routes between Angular and AngularJS
Another important part of upgrading is upgrading routes.
We could upgrade our whole app while still using the AngularJS router and then
migrate all the routes in one fell swoop.
But it would be much better to migrate routes one by one as they become upgraded.
The first step to have a dual router setup is to add an Angular root component containing
one outlet for each router.
AngularJS will use `ng-view`, and Angular will use `router-outlet`.
When one is using it's router, the other outlet will be empty.
+makeExample('upgrade-module/ts/src/app/divide-routes/app.component.ts', null, 'app.component.ts')
:marked
We want to use this component in the body of our `index.html` instead of an AngularJS component:
+makeExample('upgrade-module/ts/src/index-divide-routes.html', 'body', 'app.component.ts (body)')
:marked
Next we declare both AngularJS and Angular routes as normal:
+makeExample('upgrade-module/ts/src/app/divide-routes/app.module.ts', 'ajs-route', 'app.module.ts (AngularJS route)')
+makeExample('upgrade-module/ts/src/app/divide-routes/hero.module.ts', 'a-route', 'hero.module.ts (Angular route)')
:marked
In our `app.module.ts` we need to add `AppComponent` to the declarations and boostrap array.
Next we configure the router itself.
We want to use [hash navigation](./router.html#-hashlocationstrategy-) in Angular
because that's what we're also using in AngularJS.
Lastly, and most importantly, we want to use a custom `UrlHandlingStrategy` that will tell
the Angular router which routes it should render - and only those.
+makeExample('upgrade-module/ts/src/app/divide-routes/app.module.ts', 'router-config', 'app.module.ts (router config)')
:marked
That's it! Now we're running both routers at the same time.
.l-main-section
:marked
## PhoneCat Upgrade Tutorial
In this section and we will look at a complete example of
preparing and upgrading an application using the `upgrade` module. The app
we're going to work on is [Angular PhoneCat](https://github.com/angular/angular-phonecat)
from [the original AngularJS tutorial](https://docs.angularjs.org/tutorial),
which is where many of us began our Angular adventures. Now we'll see how to
bring that application to the brave new world of Angular.
During the process we'll learn how to apply the steps outlined in the
[preparation guide](#preparation) in practice: We'll align the application
with Angular and also take TypeScript into use.
To follow along with the tutorial, clone the
[angular-phonecat](https://github.com/angular/angular-phonecat) repository
and apply the steps as we go.
In terms of project structure, this is where our work begins:
.filetree
.file angular-phonecat
.children
.file bower.json
.file karma.conf.js
.file package.json
.file app
.children
.file core
.children
.file checkmark
.children
.file checkmark.filter.js
.file checkmark.filter.spec.js
.file phone
.children
.file phone.module.js
.file phone.service.js
.file phone.service.spec.js
.file core.module.js
.file phone-detail
.children
.file phone-detail.component.js
.file phone-detail.component.spec.js
.file phone-detail.module.js
.file phone-detail.template.html
.file phone-list
.children
.file phone-list.component.js
.file phone-list.component.spec.js
.file phone-list.module.js
.file phone-list.template.html
.file img
.children
.file ...
.file phones
.children
.file ...
.file app.animations.js
.file app.config.js
.file app.css
.file app.module.js
.file index.html
.file e2e-tests
.children
.file protractor-conf.js
.file scenarios.js
:marked
This is actually a pretty good starting point. The code uses the AngularJS 1.5
component API and the organization follows the
[AngularJS Style Guide](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md),
which is an important [preparation step](#following-the-angular-style-guide) before
a successful upgrade.
* Each component, service, and filter is in its own source file, as per the
[Rule of 1](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#single-responsibility).
* The `core`, `phone-detail`, and `phone-list` modules are each in their
own subdirectory. Those subdirectories contain the JavaScript code as well as
the HTML templates that go with each particular feature. This is in line with the
[Folders-by-Feature Structure](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#style-y152)
and [Modularity](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#modularity)
rules.
* Unit tests are located side-by-side with application code where they are easily
found, as described in the rules for
[Organizing Tests](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#style-y197).
:marked
### Switching to TypeScript
Since we're going to be writing our Angular code in TypeScript, it makes sense to
bring in the TypeScript compiler even before we begin upgrading.
We will also start to gradually phase out the Bower package manager in favor
of NPM. We'll install all new dependencies using NPM, and will eventually be
able to remove Bower from the project.
Let's begin by installing TypeScript to the project.
code-example(format="").
npm i typescript --save-dev
:marked
Let's also add run scripts for the `tsc` TypeScript compiler to `package.json`:
+makeJson('upgrade-phonecat-1-typescript/ts/package.json', {paths: 'scripts.tsc, scripts.tsc:w'}, 'package.json')
:marked
We can now install type definitions for the existing libraries that
we're using but that don't come with prepackaged types: AngularJS and the
Jasmine unit test framework.
code-example(format="").
npm install @types/jasmine @types/angular @types/angular-animate @types/angular-cookies @types/angular-mocks @types/angular-resource @types/angular-route @types/angular-sanitize --save-dev
:marked
We should also configure the TypeScript compiler so that it can understand our
project. We'll add a `tsconfig.json` file to the project directory, just like we do
in the documentation [setup](setup.html). It instructs the TypeScript compiler how
to interpret our source files.
+makeJson('upgrade-phonecat-1-typescript/ts/tsconfig.ajs.json', null, 'tsconfig.json')
:marked
We are telling the TypeScript compiler to turn our TypeScript files to ES5 code
bundled into CommonJS modules.
We can now launch the TypeScript compiler from the command line. It will watch
our `.ts` source files and compile them to JavaScript on the fly. Those compiled
`.js` files are then loaded into the browser by SystemJS. This is a process we'll
want to have continuously running in the background as we go along.
code-example(format="").
npm run tsc:w
:marked
The next thing we'll do is convert our JavaScript files to TypeScript. Since
TypeScript is a superset of ECMAScript 2015, which in turn is a superset
of ECMAScript 5, we can simply switch the file extensions from `.js` to `.ts`