-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.ts
6688 lines (5698 loc) · 181 KB
/
api.ts
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/* tslint:disable:no-console */
import {logging, WebDriver} from 'selenium-webdriver';
declare var browser: WebDriver;
declare var expect: any;
// TODO (juliemr): remove this method once this becomes a protractor plugin
export async function verifyNoBrowserErrors() {
const browserLog = await browser.manage().logs().get('browser');
const collectedErrors: any[] = [];
browserLog.forEach((logEntry) => {
const msg = logEntry.message;
console.log('>> ' + msg, logEntry);
if (logEntry.level.value >= logging.Level.INFO.value) {
collectedErrors.push(msg);
}
});
expect(collectedErrors).toEqual([]);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docplaster
import {
Component,
Directive,
ElementRef,
EventEmitter,
Injectable,
Injector,
Input,
NgModule,
Output,
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {
downgradeComponent,
downgradeInjectable,
UpgradeComponent,
UpgradeModule,
} from '@angular/upgrade/static';
declare var angular: ng.IAngularStatic;
export interface Hero {
name: string;
description: string;
}
// #docregion ng1-text-formatter-service
export class TextFormatter {
titleCase(value: string) {
return value.replace(/((^|\s)[a-z])/g, (_, c) => c.toUpperCase());
}
}
// #enddocregion
// #docregion ng2-heroes
// This Angular component will be "downgraded" to be used in AngularJS
@Component({
selector: 'ng2-heroes',
// This template uses the upgraded `ng1-hero` component
// Note that because its element is compiled by Angular we must use camelCased attribute names
template: `
<header><ng-content selector="h1"></ng-content></header>
<ng-content selector=".extra"></ng-content>
<div *ngFor="let hero of heroes">
<ng1-hero [hero]="hero" (onRemove)="removeHero.emit(hero)">
<strong>Super Hero</strong>
</ng1-hero>
</div>
<button (click)="addHero.emit()">Add Hero</button>
`,
})
export class Ng2HeroesComponent {
@Input() heroes!: Hero[];
@Output() addHero = new EventEmitter();
@Output() removeHero = new EventEmitter();
}
// #enddocregion
// #docregion ng2-heroes-service
// This Angular service will be "downgraded" to be used in AngularJS
@Injectable()
export class HeroesService {
heroes: Hero[] = [
{name: 'superman', description: 'The man of steel'},
{name: 'wonder woman', description: 'Princess of the Amazons'},
{name: 'thor', description: 'The hammer-wielding god'},
];
// #docregion use-ng1-upgraded-service
constructor(textFormatter: TextFormatter) {
// Change all the hero names to title case, using the "upgraded" AngularJS service
this.heroes.forEach((hero: Hero) => (hero.name = textFormatter.titleCase(hero.name)));
}
// #enddocregion
addHero() {
this.heroes = this.heroes.concat([
{name: 'Kamala Khan', description: 'Epic shape-shifting healer'},
]);
}
removeHero(hero: Hero) {
this.heroes = this.heroes.filter((item: Hero) => item !== hero);
}
}
// #enddocregion
// #docregion ng1-hero-wrapper
// This Angular directive will act as an interface to the "upgraded" AngularJS component
@Directive({selector: 'ng1-hero'})
export class Ng1HeroComponentWrapper extends UpgradeComponent {
// The names of the input and output properties here must match the names of the
// `<` and `&` bindings in the AngularJS component that is being wrapped
@Input() hero!: Hero;
@Output() onRemove!: EventEmitter<void>;
constructor(elementRef: ElementRef, injector: Injector) {
// We must pass the name of the directive as used by AngularJS to the super
super('ng1Hero', elementRef, injector);
}
}
// #enddocregion
// #docregion ng2-module
// This NgModule represents the Angular pieces of the application
@NgModule({
declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper],
providers: [
HeroesService,
// #docregion upgrade-ng1-service
// Register an Angular provider whose value is the "upgraded" AngularJS service
{provide: TextFormatter, useFactory: (i: any) => i.get('textFormatter'), deps: ['$injector']},
// #enddocregion
],
// We must import `UpgradeModule` to get access to the AngularJS core services
imports: [BrowserModule, UpgradeModule],
})
// #docregion bootstrap-ng1
export class Ng2AppModule {
// #enddocregion ng2-module
constructor(private upgrade: UpgradeModule) {}
ngDoBootstrap() {
// We bootstrap the AngularJS app.
this.upgrade.bootstrap(document.body, [ng1AppModule.name]);
}
// #docregion ng2-module
}
// #enddocregion bootstrap-ng1
// #enddocregion ng2-module
// This Angular 1 module represents the AngularJS pieces of the application
export const ng1AppModule: ng.IModule = angular.module('ng1AppModule', []);
// #docregion ng1-hero
// This AngularJS component will be "upgraded" to be used in Angular
ng1AppModule.component('ng1Hero', {
bindings: {hero: '<', onRemove: '&'},
transclude: true,
template: `<div class="title" ng-transclude></div>
<h2>{{ $ctrl.hero.name }}</h2>
<p>{{ $ctrl.hero.description }}</p>
<button ng-click="$ctrl.onRemove()">Remove</button>`,
});
// #enddocregion
// #docregion ng1-text-formatter-service
// This AngularJS service will be "upgraded" to be used in Angular
ng1AppModule.service('textFormatter', [TextFormatter]);
// #enddocregion
// #docregion downgrade-ng2-heroes-service
// Register an AngularJS service, whose value is the "downgraded" Angular injectable.
ng1AppModule.factory('heroesService', downgradeInjectable(HeroesService) as any);
// #enddocregion
// #docregion ng2-heroes-wrapper
// This directive will act as the interface to the "downgraded" Angular component
ng1AppModule.directive('ng2Heroes', downgradeComponent({component: Ng2HeroesComponent}));
// #enddocregion
// #docregion example-app
// This is our top level application component
ng1AppModule.component('exampleApp', {
// We inject the "downgraded" HeroesService into this AngularJS component
// (We don't need the `HeroesService` type for AngularJS DI - it just helps with TypeScript
// compilation)
controller: [
'heroesService',
function (heroesService: HeroesService) {
this.heroesService = heroesService;
},
],
// This template makes use of the downgraded `ng2-heroes` component
// Note that because its element is compiled by AngularJS we must use kebab-case attributes
// for inputs and outputs
template: `<link rel="stylesheet" href="./styles.css">
<ng2-heroes [heroes]="$ctrl.heroesService.heroes" (add-hero)="$ctrl.heroesService.addHero()" (remove-hero)="$ctrl.heroesService.removeHero($event)">
<h1>Heroes</h1>
<p class="extra">There are {{ $ctrl.heroesService.heroes.length }} heroes.</p>
</ng2-heroes>`,
});
// #enddocregion
// #docregion bootstrap-ng2
// We bootstrap the Angular module as we would do in a normal Angular app.
// (We are using the dynamic browser platform as this example has not been compiled AOT.)
platformBrowserDynamic().bootstrapModule(Ng2AppModule);
// #enddocregion
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion angular-setup
import {TestBed} from '@angular/core/testing';
import {
createAngularJSTestingModule,
createAngularTestingModule,
} from '@angular/upgrade/static/testing';
import {HeroesService, ng1AppModule, Ng2AppModule} from './module';
const {module, inject} = (window as any).angular.mock;
// #enddocregion angular-setup
describe('HeroesService (from Angular)', () => {
// #docregion angular-setup
beforeEach(() => {
TestBed.configureTestingModule({
imports: [createAngularTestingModule([ng1AppModule.name]), Ng2AppModule],
});
});
// #enddocregion angular-setup
// #docregion angular-spec
it('should have access to the HeroesService', () => {
const heroesService = TestBed.inject(HeroesService);
expect(heroesService).toBeDefined();
});
// #enddocregion angular-spec
});
describe('HeroesService (from AngularJS)', () => {
// #docregion angularjs-setup
beforeEach(module(createAngularJSTestingModule([Ng2AppModule])));
beforeEach(module(ng1AppModule.name));
// #enddocregion angularjs-setup
// #docregion angularjs-spec
it('should have access to the HeroesService', inject((heroesService: HeroesService) => {
expect(heroesService).toBeDefined();
}));
// #enddocregion angularjs-spec
});
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {browser, by, element} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../test-utils';
function loadPage() {
browser.rootEl = 'example-app';
browser.get('/');
}
describe('upgrade/static (full)', () => {
beforeEach(loadPage);
afterEach(verifyNoBrowserErrors);
it('should render the `ng2-heroes` component', () => {
expect(element(by.css('h1')).getText()).toEqual('Heroes');
expect(element.all(by.css('p')).get(0).getText()).toEqual('There are 3 heroes.');
});
it('should render 3 ng1-hero components', () => {
const heroComponents = element.all(by.css('ng1-hero'));
expect(heroComponents.count()).toEqual(3);
});
it('should add a new hero when the "Add Hero" button is pressed', () => {
const addHeroButton = element.all(by.css('button')).last();
expect(addHeroButton.getText()).toEqual('Add Hero');
addHeroButton.click();
const heroComponents = element.all(by.css('ng1-hero'));
expect(heroComponents.last().element(by.css('h2')).getText()).toEqual('Kamala Khan');
});
it('should remove a hero when the "Remove" button is pressed', () => {
let firstHero = element.all(by.css('ng1-hero')).get(0);
expect(firstHero.element(by.css('h2')).getText()).toEqual('Superman');
const removeHeroButton = firstHero.element(by.css('button'));
expect(removeHeroButton.getText()).toEqual('Remove');
removeHeroButton.click();
const heroComponents = element.all(by.css('ng1-hero'));
expect(heroComponents.count()).toEqual(2);
firstHero = element.all(by.css('ng1-hero')).get(0);
expect(firstHero.element(by.css('h2')).getText()).toEqual('Wonder Woman');
});
});
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docplaster
import {
Component,
Directive,
ElementRef,
EventEmitter,
Inject,
Injectable,
Injector,
Input,
NgModule,
Output,
StaticProvider,
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
// #docregion basic-how-to
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
// #enddocregion
/* tslint:disable: no-duplicate-imports */
// #docregion basic-how-to
import {downgradeComponent, downgradeModule, UpgradeComponent} from '@angular/upgrade/static';
// #enddocregion
/* tslint:enable: no-duplicate-imports */
declare var angular: ng.IAngularStatic;
interface Hero {
name: string;
description: string;
}
// This Angular service will use an "upgraded" AngularJS service.
@Injectable()
class HeroesService {
heroes: Hero[] = [
{name: 'superman', description: 'The man of steel'},
{name: 'wonder woman', description: 'Princess of the Amazons'},
{name: 'thor', description: 'The hammer-wielding god'},
];
constructor(@Inject('titleCase') titleCase: (v: string) => string) {
// Change all the hero names to title case, using the "upgraded" AngularJS service.
this.heroes.forEach((hero: Hero) => (hero.name = titleCase(hero.name)));
}
addHero() {
const newHero: Hero = {name: 'Kamala Khan', description: 'Epic shape-shifting healer'};
this.heroes = this.heroes.concat([newHero]);
return newHero;
}
removeHero(hero: Hero) {
this.heroes = this.heroes.filter((item: Hero) => item !== hero);
}
}
// This Angular component will be "downgraded" to be used in AngularJS.
@Component({
selector: 'ng2-heroes',
// This template uses the "upgraded" `ng1-hero` component
// (Note that because its element is compiled by Angular we must use camelCased attribute names.)
template: `
<div class="ng2-heroes">
<header><ng-content selector="h1"></ng-content></header>
<ng-content selector=".extra"></ng-content>
<div *ngFor="let hero of this.heroesService.heroes">
<ng1-hero [hero]="hero" (onRemove)="onRemoveHero(hero)">
<strong>Super Hero</strong>
</ng1-hero>
</div>
<button (click)="onAddHero()">Add Hero</button>
</div>
`,
})
class Ng2HeroesComponent {
@Output() private addHero = new EventEmitter<Hero>();
@Output() private removeHero = new EventEmitter<Hero>();
constructor(
@Inject('$rootScope') private $rootScope: ng.IRootScopeService,
public heroesService: HeroesService,
) {}
onAddHero() {
const newHero = this.heroesService.addHero();
this.addHero.emit(newHero);
// When a new instance of an "upgraded" component - such as `ng1Hero` - is created, we want to
// run a `$digest` to initialize its bindings. Here, the component will be created by `ngFor`
// asynchronously, thus we have to schedule the `$digest` to also happen asynchronously.
this.$rootScope.$applyAsync();
}
onRemoveHero(hero: Hero) {
this.heroesService.removeHero(hero);
this.removeHero.emit(hero);
}
}
// This Angular directive will act as an interface to the "upgraded" AngularJS component.
@Directive({selector: 'ng1-hero'})
class Ng1HeroComponentWrapper extends UpgradeComponent {
// The names of the input and output properties here must match the names of the
// `<` and `&` bindings in the AngularJS component that is being wrapped.
@Input() hero!: Hero;
@Output() onRemove!: EventEmitter<void>;
constructor(elementRef: ElementRef, injector: Injector) {
// We must pass the name of the directive as used by AngularJS to the super.
super('ng1Hero', elementRef, injector);
}
}
// This Angular module represents the Angular pieces of the application.
@NgModule({
imports: [BrowserModule],
declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper],
providers: [
HeroesService,
// Register an Angular provider whose value is the "upgraded" AngularJS service.
{provide: 'titleCase', useFactory: (i: any) => i.get('titleCase'), deps: ['$injector']},
],
// Note that there are no `bootstrap` components, since the "downgraded" component
// will be instantiated by ngUpgrade.
})
class MyLazyAngularModule {
// Empty placeholder method to prevent the `Compiler` from complaining.
ngDoBootstrap() {}
}
// #docregion basic-how-to
// The function that will bootstrap the Angular module (when/if necessary).
// (This would be omitted if we provided an `NgModuleFactory` directly.)
const ng2BootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(MyLazyAngularModule);
// #enddocregion
// (We are using the dynamic browser platform, as this example has not been compiled AOT.)
// #docregion basic-how-to
// This AngularJS module represents the AngularJS pieces of the application.
const myMainAngularJsModule = angular.module('myMainAngularJsModule', [
// We declare a dependency on the "downgraded" Angular module.
downgradeModule(ng2BootstrapFn),
// or
// downgradeModule(MyLazyAngularModuleFactory)
]);
// #enddocregion
// This AngularJS component will be "upgraded" to be used in Angular.
myMainAngularJsModule.component('ng1Hero', {
bindings: {hero: '<', onRemove: '&'},
transclude: true,
template: `
<div class="ng1-hero">
<div class="title" ng-transclude></div>
<h2>{{ $ctrl.hero.name }}</h2>
<p>{{ $ctrl.hero.description }}</p>
<button ng-click="$ctrl.onRemove()">Remove</button>
</div>
`,
});
// This AngularJS service will be "upgraded" to be used in Angular.
myMainAngularJsModule.factory(
'titleCase',
() => (value: string) => value.replace(/(^|\s)[a-z]/g, (m) => m.toUpperCase()),
);
// This directive will act as the interface to the "downgraded" Angular component.
myMainAngularJsModule.directive(
'ng2Heroes',
downgradeComponent({
component: Ng2HeroesComponent,
// Optionally, disable `$digest` propagation to avoid unnecessary change detection.
// (Change detection is still run when the inputs of a "downgraded" component change.)
propagateDigest: false,
}),
);
// This is our top level application component.
myMainAngularJsModule.component('exampleApp', {
// This template makes use of the "downgraded" `ng2-heroes` component,
// but loads it lazily only when/if the user clicks the button.
// (Note that because its element is compiled by AngularJS,
// we must use kebab-case attributes for inputs and outputs.)
template: `
<link rel="stylesheet" href="./styles.css">
<button ng-click="$ctrl.toggleHeroes()">{{ $ctrl.toggleBtnText() }}</button>
<ng2-heroes
ng-if="$ctrl.showHeroes"
(add-hero)="$ctrl.setStatusMessage('Added hero ' + $event.name)"
(remove-hero)="$ctrl.setStatusMessage('Removed hero ' + $event.name)">
<h1>Heroes</h1>
<p class="extra">Status: {{ $ctrl.statusMessage }}</p>
</ng2-heroes>
`,
controller: function () {
this.showHeroes = false;
this.statusMessage = 'Ready';
this.setStatusMessage = (msg: string) => (this.statusMessage = msg);
this.toggleHeroes = () => (this.showHeroes = !this.showHeroes);
this.toggleBtnText = () => `${this.showHeroes ? 'Hide' : 'Show'} heroes`;
},
});
// We bootstrap the Angular module as we would do in a normal Angular app.
angular.bootstrap(document.body, [myMainAngularJsModule.name]);
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {browser, by, element, ElementArrayFinder, ElementFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../test-utils';
import {addCustomMatchers} from './e2e_util';
function loadPage() {
browser.rootEl = 'example-app';
browser.get('/');
}
describe('upgrade/static (lite)', () => {
let showHideBtn: ElementFinder;
let ng2Heroes: ElementFinder;
let ng2HeroesHeader: ElementFinder;
let ng2HeroesExtra: ElementFinder;
let ng2HeroesAddBtn: ElementFinder;
let ng1Heroes: ElementArrayFinder;
const expectHeroes = (isShown: boolean, ng1HeroCount = 3, statusMessage = 'Ready') => {
// Verify the show/hide button text.
expect(showHideBtn.getText()).toBe(isShown ? 'Hide heroes' : 'Show heroes');
// Verify the `<ng2-heroes>` component.
expect(ng2Heroes.isPresent()).toBe(isShown);
if (isShown) {
expect(ng2HeroesHeader.getText()).toBe('Heroes');
expect(ng2HeroesExtra.getText()).toBe(`Status: ${statusMessage}`);
}
// Verify the `<ng1-hero>` components.
expect(ng1Heroes.count()).toBe(isShown ? ng1HeroCount : 0);
if (isShown) {
ng1Heroes.each((ng1Hero) => expect(ng1Hero).toBeAHero());
}
};
beforeEach(() => {
showHideBtn = element(by.binding('toggleBtnText'));
ng2Heroes = element(by.css('.ng2-heroes'));
ng2HeroesHeader = ng2Heroes.element(by.css('h1'));
ng2HeroesExtra = ng2Heroes.element(by.css('.extra'));
ng2HeroesAddBtn = ng2Heroes.element(by.buttonText('Add Hero'));
ng1Heroes = element.all(by.css('.ng1-hero'));
});
beforeEach(addCustomMatchers);
beforeEach(loadPage);
afterEach(verifyNoBrowserErrors);
it('should initially not render the heroes', () => expectHeroes(false));
it('should toggle the heroes when clicking the "show/hide" button', () => {
showHideBtn.click();
expectHeroes(true);
showHideBtn.click();
expectHeroes(false);
});
it('should add a new hero when clicking the "add" button', () => {
showHideBtn.click();
ng2HeroesAddBtn.click();
expectHeroes(true, 4, 'Added hero Kamala Khan');
expect(ng1Heroes.last()).toHaveName('Kamala Khan');
});
it('should remove a hero when clicking its "remove" button', () => {
showHideBtn.click();
const firstHero = ng1Heroes.first();
expect(firstHero).toHaveName('Superman');
const removeBtn = firstHero.element(by.buttonText('Remove'));
removeBtn.click();
expectHeroes(true, 2, 'Removed hero Superman');
expect(ng1Heroes.first()).not.toHaveName('Superman');
});
});
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {by, ElementFinder} from 'protractor';
declare global {
namespace jasmine {
interface Matchers<T> {
toBeAHero(): Promise<void>;
toHaveName(exectedName: string): Promise<void>;
}
}
}
const isTitleCased = (text: string) =>
text.split(/\s+/).every((word) => word[0] === word[0].toUpperCase());
export function addCustomMatchers() {
jasmine.addMatchers({
toBeAHero: () => ({
compare(actualNg1Hero: ElementFinder | undefined) {
const getText = (selector: string) => actualNg1Hero!.element(by.css(selector)).getText();
const result = {
message: 'Expected undefined to be an `ng1Hero` ElementFinder.',
pass:
!!actualNg1Hero &&
Promise.all(['.title', 'h2', 'p'].map(getText) as PromiseLike<string>[]).then(
([actualTitle, actualName, actualDescription]) => {
const pass =
actualTitle === 'Super Hero' &&
isTitleCased(actualName) &&
actualDescription.length > 0;
const actualHero = `Hero(${actualTitle}, ${actualName}, ${actualDescription})`;
result.message = `Expected ${actualHero}'${pass ? ' not' : ''} to be a real hero.`;
return pass;
},
),
};
return result;
},
}),
toHaveName: () => ({
compare(actualNg1Hero: ElementFinder | undefined, expectedName: string) {
const result = {
message: 'Expected undefined to be an `ng1Hero` ElementFinder.',
pass:
!!actualNg1Hero &&
actualNg1Hero
.element(by.css('h2'))
.getText()
.then((actualName) => {
const pass = actualName === expectedName;
result.message = `Expected Hero(${actualName})${
pass ? ' not' : ''
} to have name '${expectedName}'.`;
return pass;
}),
};
return result;
},
}),
} as any);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docplaster
import {
Component,
Directive,
ElementRef,
getPlatform,
Injectable,
Injector,
NgModule,
StaticProvider,
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {
downgradeComponent,
downgradeInjectable,
downgradeModule,
UpgradeComponent,
} from '@angular/upgrade/static';
declare var angular: ng.IAngularStatic;
// An Angular module that declares an Angular service and a component,
// which in turn uses an upgraded AngularJS component.
@Component({
selector: 'ng2A',
template: 'Component A | <ng1A></ng1A>',
})
export class Ng2AComponent {}
@Directive({
selector: 'ng1A',
})
export class Ng1AComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Injectable()
export class Ng2AService {
getValue() {
return 'ng2';
}
}
@NgModule({
imports: [BrowserModule],
providers: [Ng2AService],
declarations: [Ng1AComponentFacade, Ng2AComponent],
})
export class Ng2AModule {
ngDoBootstrap() {}
}
// Another Angular module that declares an Angular component.
@Component({
selector: 'ng2B',
template: 'Component B',
})
export class Ng2BComponent {}
@NgModule({
imports: [BrowserModule],
declarations: [Ng2BComponent],
})
export class Ng2BModule {
ngDoBootstrap() {}
}
// The downgraded Angular modules.
const downgradedNg2AModule = downgradeModule((extraProviders: StaticProvider[]) =>
(getPlatform() || platformBrowserDynamic(extraProviders)).bootstrapModule(Ng2AModule),
);
const downgradedNg2BModule = downgradeModule((extraProviders: StaticProvider[]) =>
(getPlatform() || platformBrowserDynamic(extraProviders)).bootstrapModule(Ng2BModule),
);
// The AngularJS app including downgraded modules, components and injectables.
const appModule = angular
.module('exampleAppModule', [downgradedNg2AModule, downgradedNg2BModule])
.component('exampleApp', {
template: `
<nav>
<button ng-click="$ctrl.page = page" ng-repeat="page in ['A', 'B']">
Page {{ page }}
</button>
</nav>
<hr />
<main ng-switch="$ctrl.page">
<ng2-a ng-switch-when="A"></ng2-a>
<ng2-b ng-switch-when="B"></ng2-b>
</main>
`,
controller: class ExampleAppController {
page = 'A';
},
})
.component('ng1A', {
template: 'ng1({{ $ctrl.value }})',
controller: [
'ng2AService',
class Ng1AController {
value = this.ng2AService.getValue();
constructor(private ng2AService: Ng2AService) {}
},
],
})
.directive(
'ng2A',
downgradeComponent({
component: Ng2AComponent,
// Since there is more than one downgraded Angular module,
// specify which module this component belongs to.
downgradedModule: downgradedNg2AModule,
propagateDigest: false,
}),
)
.directive(
'ng2B',
downgradeComponent({
component: Ng2BComponent,
// Since there is more than one downgraded Angular module,
// specify which module this component belongs to.
downgradedModule: downgradedNg2BModule,
propagateDigest: false,
}),
)
.factory('ng2AService', downgradeInjectable(Ng2AService, downgradedNg2AModule));
// Bootstrap the AngularJS app.
angular.bootstrap(document.body, [appModule.name]);
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {browser, by, element} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../test-utils';
describe('upgrade/static (lite with multiple downgraded modules)', () => {
const navButtons = element.all(by.css('nav button'));
const mainContent = element(by.css('main'));
beforeEach(() => browser.get('/'));
afterEach(verifyNoBrowserErrors);
it('should correctly bootstrap multiple downgraded modules', () => {
navButtons.get(1).click();
expect(mainContent.getText()).toBe('Component B');
navButtons.get(0).click();
expect(mainContent.getText()).toBe('Component A | ng1(ng2)');
});
});
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
Compiler,
Component,
getPlatform,
Injectable,
Injector,
NgModule,
StaticProvider,
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {downgradeComponent, downgradeModule} from '@angular/upgrade/static';
declare var angular: ng.IAngularStatic;
// An Angular service provided in root. Each instance of the service will get a new ID.
@Injectable({providedIn: 'root'})
export class Ng2Service {
static nextId = 1;
id = Ng2Service.nextId++;
}
// An Angular module that will act as "root" for all downgraded modules, so that injectables
// provided in root will be available to all.
@NgModule({
imports: [BrowserModule],
})
export class Ng2RootModule {
ngDoBootstrap() {}
}
// An Angular module that declares an Angular component,
// which in turn uses an Angular service from the root module.
@Component({
selector: 'ng2A',
template: 'Component A (Service ID: {{ service.id }})',
})
export class Ng2AComponent {
constructor(public service: Ng2Service) {}
}
@NgModule({
declarations: [Ng2AComponent],
})
export class Ng2AModule {
ngDoBootstrap() {}
}
// Another Angular module that declares an Angular component, which uses the same service.
@Component({
selector: 'ng2B',
template: 'Component B (Service ID: {{ service.id }})',
})
export class Ng2BComponent {
constructor(public service: Ng2Service) {}
}
@NgModule({
declarations: [Ng2BComponent],
})
export class Ng2BModule {
ngDoBootstrap() {}
}
// A third Angular module that declares an Angular component, which uses the same service.
@Component({
selector: 'ng2C',
template: 'Component C (Service ID: {{ service.id }})',
})
export class Ng2CComponent {
constructor(public service: Ng2Service) {}
}
@NgModule({
imports: [BrowserModule],
declarations: [Ng2CComponent],
})
export class Ng2CModule {
ngDoBootstrap() {}
}
// The downgraded Angular modules. Modules A and B share a common root module. Module C does not.
// #docregion shared-root-module
let rootInjectorPromise: Promise<Injector> | null = null;
const getRootInjector = (extraProviders: StaticProvider[]) => {
if (!rootInjectorPromise) {
rootInjectorPromise = platformBrowserDynamic(extraProviders)
.bootstrapModule(Ng2RootModule)
.then((moduleRef) => moduleRef.injector);
}
return rootInjectorPromise;
};
const downgradedNg2AModule = downgradeModule(async (extraProviders: StaticProvider[]) => {
const rootInjector = await getRootInjector(extraProviders);
const moduleAFactory = await rootInjector.get(Compiler).compileModuleAsync(Ng2AModule);
return moduleAFactory.create(rootInjector);
});
const downgradedNg2BModule = downgradeModule(async (extraProviders: StaticProvider[]) => {
const rootInjector = await getRootInjector(extraProviders);
const moduleBFactory = await rootInjector.get(Compiler).compileModuleAsync(Ng2BModule);
return moduleBFactory.create(rootInjector);
});
// #enddocregion shared-root-module
const downgradedNg2CModule = downgradeModule((extraProviders: StaticProvider[]) =>