@angular/upgrade 13.0.0-next.8 → 13.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/{esm2015/index.js → esm2020/index.mjs} +0 -0
  2. package/{esm2015/public_api.js → esm2020/public_api.mjs} +0 -0
  3. package/{esm2015/src/common/src/angular1.js → esm2020/src/common/src/angular1.mjs} +2 -2
  4. package/{esm2015/src/common/src/component_info.js → esm2020/src/common/src/component_info.mjs} +0 -0
  5. package/{esm2015/src/common/src/constants.js → esm2020/src/common/src/constants.mjs} +0 -0
  6. package/{esm2015/src/common/src/downgrade_component.js → esm2020/src/common/src/downgrade_component.mjs} +0 -0
  7. package/{esm2015/src/common/src/downgrade_component_adapter.js → esm2020/src/common/src/downgrade_component_adapter.mjs} +0 -0
  8. package/{esm2015/src/common/src/downgrade_injectable.js → esm2020/src/common/src/downgrade_injectable.mjs} +0 -0
  9. package/{esm2015/src/common/src/promise_util.js → esm2020/src/common/src/promise_util.mjs} +0 -0
  10. package/{esm2015/src/common/src/upgrade_helper.js → esm2020/src/common/src/upgrade_helper.mjs} +0 -0
  11. package/{esm2015/src/common/src/util.js → esm2020/src/common/src/util.mjs} +0 -0
  12. package/{esm2015/src/common/src/version.js → esm2020/src/common/src/version.mjs} +1 -1
  13. package/esm2020/src/dynamic/src/upgrade_adapter.mjs +683 -0
  14. package/esm2020/src/dynamic/src/upgrade_ng1_adapter.mjs +223 -0
  15. package/{esm2015/static/index.js → esm2020/static/index.mjs} +0 -0
  16. package/{esm2015/static/public_api.js → esm2020/static/public_api.mjs} +0 -0
  17. package/{esm2015/static/src/angular1_providers.js → esm2020/static/src/angular1_providers.mjs} +0 -0
  18. package/{esm2015/static/src/downgrade_module.js → esm2020/static/src/downgrade_module.mjs} +0 -0
  19. package/esm2020/static/src/upgrade_component.mjs +240 -0
  20. package/esm2020/static/src/upgrade_module.mjs +291 -0
  21. package/{esm2015/static/src/util.js → esm2020/static/src/util.mjs} +0 -0
  22. package/esm2020/static/static.mjs +5 -0
  23. package/{esm2015/static/testing/index.js → esm2020/static/testing/index.mjs} +0 -0
  24. package/{esm2015/static/testing/public_api.js → esm2020/static/testing/public_api.mjs} +0 -0
  25. package/esm2020/static/testing/src/create_angular_testing_module.mjs +101 -0
  26. package/{esm2015/static/testing/src/create_angularjs_testing_module.js → esm2020/static/testing/src/create_angularjs_testing_module.mjs} +0 -0
  27. package/esm2020/static/testing/testing.mjs +5 -0
  28. package/{esm2015/upgrade.js → esm2020/upgrade.mjs} +0 -0
  29. package/fesm2015/static/{testing.js → testing.mjs} +16 -14
  30. package/fesm2015/static/testing.mjs.map +1 -0
  31. package/fesm2015/{static.js → static.mjs} +23 -26
  32. package/fesm2015/static.mjs.map +1 -0
  33. package/fesm2015/upgrade.mjs +2061 -0
  34. package/fesm2015/upgrade.mjs.map +1 -0
  35. package/fesm2020/static/testing.mjs +325 -0
  36. package/fesm2020/static/testing.mjs.map +1 -0
  37. package/fesm2020/static.mjs +1931 -0
  38. package/fesm2020/static.mjs.map +1 -0
  39. package/{fesm2015/upgrade.js → fesm2020/upgrade.mjs} +32 -48
  40. package/fesm2020/upgrade.mjs.map +1 -0
  41. package/package.json +41 -11
  42. package/static/package.json +5 -5
  43. package/static/static.d.ts +7 -20
  44. package/static/testing/package.json +5 -5
  45. package/static/testing/testing.d.ts +1 -133
  46. package/upgrade.d.ts +1 -1
  47. package/bundles/upgrade-static-testing.umd.js +0 -335
  48. package/bundles/upgrade-static-testing.umd.js.map +0 -1
  49. package/bundles/upgrade-static.umd.js +0 -2303
  50. package/bundles/upgrade-static.umd.js.map +0 -1
  51. package/bundles/upgrade.umd.js +0 -2423
  52. package/bundles/upgrade.umd.js.map +0 -1
  53. package/esm2015/src/common/common.externs.js +0 -0
  54. package/esm2015/src/dynamic/src/upgrade_adapter.js +0 -682
  55. package/esm2015/src/dynamic/src/upgrade_ng1_adapter.js +0 -231
  56. package/esm2015/static/src/upgrade_component.js +0 -242
  57. package/esm2015/static/src/upgrade_module.js +0 -291
  58. package/esm2015/static/static.externs.js +0 -6
  59. package/esm2015/static/static.js +0 -6
  60. package/esm2015/static/testing/src/create_angular_testing_module.js +0 -99
  61. package/esm2015/static/testing/testing.externs.js +0 -6
  62. package/esm2015/static/testing/testing.js +0 -7
  63. package/esm2015/upgrade.externs.js +0 -6
  64. package/fesm2015/static/testing.js.map +0 -1
  65. package/fesm2015/static.js.map +0 -1
  66. package/fesm2015/upgrade.js.map +0 -1
  67. package/static/static.metadata.json +0 -1
  68. package/static/testing/testing.metadata.json +0 -1
  69. package/static/testing.d.ts +0 -7
  70. package/static/testing.metadata.json +0 -1
  71. package/static.d.ts +0 -7
  72. package/static.metadata.json +0 -1
  73. package/upgrade.metadata.json +0 -1
@@ -1,2423 +0,0 @@
1
- /**
2
- * @license Angular v13.0.0-next.8
3
- * (c) 2010-2021 Google LLC. https://angular.io/
4
- * License: MIT
5
- */
6
-
7
- (function (global, factory) {
8
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/platform-browser-dynamic')) :
9
- typeof define === 'function' && define.amd ? define('@angular/upgrade', ['exports', '@angular/core', '@angular/platform-browser-dynamic'], factory) :
10
- (global = global || self, factory((global.ng = global.ng || {}, global.ng.upgrade = {}), global.ng.core, global.ng.platformBrowserDynamic));
11
- }(this, (function (exports, core, platformBrowserDynamic) { 'use strict';
12
-
13
- /**
14
- * @license
15
- * Copyright Google LLC All Rights Reserved.
16
- *
17
- * Use of this source code is governed by an MIT-style license that can be
18
- * found in the LICENSE file at https://angular.io/license
19
- */
20
- /**
21
- * @publicApi
22
- */
23
- var VERSION = new core.Version('13.0.0-next.8');
24
-
25
- /*! *****************************************************************************
26
- Copyright (c) Microsoft Corporation.
27
-
28
- Permission to use, copy, modify, and/or distribute this software for any
29
- purpose with or without fee is hereby granted.
30
-
31
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
32
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
33
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
34
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
35
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
36
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
37
- PERFORMANCE OF THIS SOFTWARE.
38
- ***************************************************************************** */
39
- /* global Reflect, Promise */
40
- var extendStatics = function (d, b) {
41
- extendStatics = Object.setPrototypeOf ||
42
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
43
- function (d, b) { for (var p in b)
44
- if (Object.prototype.hasOwnProperty.call(b, p))
45
- d[p] = b[p]; };
46
- return extendStatics(d, b);
47
- };
48
- function __extends(d, b) {
49
- if (typeof b !== "function" && b !== null)
50
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
51
- extendStatics(d, b);
52
- function __() { this.constructor = d; }
53
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
54
- }
55
- var __assign = function () {
56
- __assign = Object.assign || function __assign(t) {
57
- for (var s, i = 1, n = arguments.length; i < n; i++) {
58
- s = arguments[i];
59
- for (var p in s)
60
- if (Object.prototype.hasOwnProperty.call(s, p))
61
- t[p] = s[p];
62
- }
63
- return t;
64
- };
65
- return __assign.apply(this, arguments);
66
- };
67
- function __rest(s, e) {
68
- var t = {};
69
- for (var p in s)
70
- if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
71
- t[p] = s[p];
72
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
73
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
74
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
75
- t[p[i]] = s[p[i]];
76
- }
77
- return t;
78
- }
79
- function __decorate(decorators, target, key, desc) {
80
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
81
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
82
- r = Reflect.decorate(decorators, target, key, desc);
83
- else
84
- for (var i = decorators.length - 1; i >= 0; i--)
85
- if (d = decorators[i])
86
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
87
- return c > 3 && r && Object.defineProperty(target, key, r), r;
88
- }
89
- function __param(paramIndex, decorator) {
90
- return function (target, key) { decorator(target, key, paramIndex); };
91
- }
92
- function __metadata(metadataKey, metadataValue) {
93
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
94
- return Reflect.metadata(metadataKey, metadataValue);
95
- }
96
- function __awaiter(thisArg, _arguments, P, generator) {
97
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
98
- return new (P || (P = Promise))(function (resolve, reject) {
99
- function fulfilled(value) { try {
100
- step(generator.next(value));
101
- }
102
- catch (e) {
103
- reject(e);
104
- } }
105
- function rejected(value) { try {
106
- step(generator["throw"](value));
107
- }
108
- catch (e) {
109
- reject(e);
110
- } }
111
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
112
- step((generator = generator.apply(thisArg, _arguments || [])).next());
113
- });
114
- }
115
- function __generator(thisArg, body) {
116
- var _ = { label: 0, sent: function () { if (t[0] & 1)
117
- throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
118
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
119
- function verb(n) { return function (v) { return step([n, v]); }; }
120
- function step(op) {
121
- if (f)
122
- throw new TypeError("Generator is already executing.");
123
- while (_)
124
- try {
125
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
126
- return t;
127
- if (y = 0, t)
128
- op = [op[0] & 2, t.value];
129
- switch (op[0]) {
130
- case 0:
131
- case 1:
132
- t = op;
133
- break;
134
- case 4:
135
- _.label++;
136
- return { value: op[1], done: false };
137
- case 5:
138
- _.label++;
139
- y = op[1];
140
- op = [0];
141
- continue;
142
- case 7:
143
- op = _.ops.pop();
144
- _.trys.pop();
145
- continue;
146
- default:
147
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
148
- _ = 0;
149
- continue;
150
- }
151
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
152
- _.label = op[1];
153
- break;
154
- }
155
- if (op[0] === 6 && _.label < t[1]) {
156
- _.label = t[1];
157
- t = op;
158
- break;
159
- }
160
- if (t && _.label < t[2]) {
161
- _.label = t[2];
162
- _.ops.push(op);
163
- break;
164
- }
165
- if (t[2])
166
- _.ops.pop();
167
- _.trys.pop();
168
- continue;
169
- }
170
- op = body.call(thisArg, _);
171
- }
172
- catch (e) {
173
- op = [6, e];
174
- y = 0;
175
- }
176
- finally {
177
- f = t = 0;
178
- }
179
- if (op[0] & 5)
180
- throw op[1];
181
- return { value: op[0] ? op[1] : void 0, done: true };
182
- }
183
- }
184
- var __createBinding = Object.create ? (function (o, m, k, k2) {
185
- if (k2 === undefined)
186
- k2 = k;
187
- Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
188
- }) : (function (o, m, k, k2) {
189
- if (k2 === undefined)
190
- k2 = k;
191
- o[k2] = m[k];
192
- });
193
- function __exportStar(m, o) {
194
- for (var p in m)
195
- if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
196
- __createBinding(o, m, p);
197
- }
198
- function __values(o) {
199
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
200
- if (m)
201
- return m.call(o);
202
- if (o && typeof o.length === "number")
203
- return {
204
- next: function () {
205
- if (o && i >= o.length)
206
- o = void 0;
207
- return { value: o && o[i++], done: !o };
208
- }
209
- };
210
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
211
- }
212
- function __read(o, n) {
213
- var m = typeof Symbol === "function" && o[Symbol.iterator];
214
- if (!m)
215
- return o;
216
- var i = m.call(o), r, ar = [], e;
217
- try {
218
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
219
- ar.push(r.value);
220
- }
221
- catch (error) {
222
- e = { error: error };
223
- }
224
- finally {
225
- try {
226
- if (r && !r.done && (m = i["return"]))
227
- m.call(i);
228
- }
229
- finally {
230
- if (e)
231
- throw e.error;
232
- }
233
- }
234
- return ar;
235
- }
236
- /** @deprecated */
237
- function __spread() {
238
- for (var ar = [], i = 0; i < arguments.length; i++)
239
- ar = ar.concat(__read(arguments[i]));
240
- return ar;
241
- }
242
- /** @deprecated */
243
- function __spreadArrays() {
244
- for (var s = 0, i = 0, il = arguments.length; i < il; i++)
245
- s += arguments[i].length;
246
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
247
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
248
- r[k] = a[j];
249
- return r;
250
- }
251
- function __spreadArray(to, from, pack) {
252
- if (pack || arguments.length === 2)
253
- for (var i = 0, l = from.length, ar; i < l; i++) {
254
- if (ar || !(i in from)) {
255
- if (!ar)
256
- ar = Array.prototype.slice.call(from, 0, i);
257
- ar[i] = from[i];
258
- }
259
- }
260
- return to.concat(ar || Array.prototype.slice.call(from));
261
- }
262
- function __await(v) {
263
- return this instanceof __await ? (this.v = v, this) : new __await(v);
264
- }
265
- function __asyncGenerator(thisArg, _arguments, generator) {
266
- if (!Symbol.asyncIterator)
267
- throw new TypeError("Symbol.asyncIterator is not defined.");
268
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
269
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
270
- function verb(n) { if (g[n])
271
- i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
272
- function resume(n, v) { try {
273
- step(g[n](v));
274
- }
275
- catch (e) {
276
- settle(q[0][3], e);
277
- } }
278
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
279
- function fulfill(value) { resume("next", value); }
280
- function reject(value) { resume("throw", value); }
281
- function settle(f, v) { if (f(v), q.shift(), q.length)
282
- resume(q[0][0], q[0][1]); }
283
- }
284
- function __asyncDelegator(o) {
285
- var i, p;
286
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
287
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
288
- }
289
- function __asyncValues(o) {
290
- if (!Symbol.asyncIterator)
291
- throw new TypeError("Symbol.asyncIterator is not defined.");
292
- var m = o[Symbol.asyncIterator], i;
293
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
294
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
295
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
296
- }
297
- function __makeTemplateObject(cooked, raw) {
298
- if (Object.defineProperty) {
299
- Object.defineProperty(cooked, "raw", { value: raw });
300
- }
301
- else {
302
- cooked.raw = raw;
303
- }
304
- return cooked;
305
- }
306
- ;
307
- var __setModuleDefault = Object.create ? (function (o, v) {
308
- Object.defineProperty(o, "default", { enumerable: true, value: v });
309
- }) : function (o, v) {
310
- o["default"] = v;
311
- };
312
- function __importStar(mod) {
313
- if (mod && mod.__esModule)
314
- return mod;
315
- var result = {};
316
- if (mod != null)
317
- for (var k in mod)
318
- if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
319
- __createBinding(result, mod, k);
320
- __setModuleDefault(result, mod);
321
- return result;
322
- }
323
- function __importDefault(mod) {
324
- return (mod && mod.__esModule) ? mod : { default: mod };
325
- }
326
- function __classPrivateFieldGet(receiver, state, kind, f) {
327
- if (kind === "a" && !f)
328
- throw new TypeError("Private accessor was defined without a getter");
329
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
330
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
331
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
332
- }
333
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
334
- if (kind === "m")
335
- throw new TypeError("Private method is not writable");
336
- if (kind === "a" && !f)
337
- throw new TypeError("Private accessor was defined without a setter");
338
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
339
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
340
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
341
- }
342
-
343
- /**
344
- * @license
345
- * Copyright Google LLC All Rights Reserved.
346
- *
347
- * Use of this source code is governed by an MIT-style license that can be
348
- * found in the LICENSE file at https://angular.io/license
349
- */
350
- function noNg() {
351
- throw new Error('AngularJS v1.x is not loaded!');
352
- }
353
- var noNgElement = (function () { return noNg(); });
354
- noNgElement.cleanData = noNg;
355
- var angular = {
356
- bootstrap: noNg,
357
- module: noNg,
358
- element: noNgElement,
359
- injector: noNg,
360
- version: undefined,
361
- resumeBootstrap: noNg,
362
- getTestability: noNg
363
- };
364
- try {
365
- if (window.hasOwnProperty('angular')) {
366
- angular = window.angular;
367
- }
368
- }
369
- catch (_a) {
370
- // ignore in CJS mode.
371
- }
372
- /**
373
- * @deprecated Use `setAngularJSGlobal` instead.
374
- *
375
- * @publicApi
376
- */
377
- function setAngularLib(ng) {
378
- setAngularJSGlobal(ng);
379
- }
380
- /**
381
- * @deprecated Use `getAngularJSGlobal` instead.
382
- *
383
- * @publicApi
384
- */
385
- function getAngularLib() {
386
- return getAngularJSGlobal();
387
- }
388
- /**
389
- * Resets the AngularJS global.
390
- *
391
- * Used when AngularJS is loaded lazily, and not available on `window`.
392
- *
393
- * @publicApi
394
- */
395
- function setAngularJSGlobal(ng) {
396
- angular = ng;
397
- }
398
- /**
399
- * Returns the current AngularJS global.
400
- *
401
- * @publicApi
402
- */
403
- function getAngularJSGlobal() {
404
- return angular;
405
- }
406
- var bootstrap = function (e, modules, config) { return angular.bootstrap(e, modules, config); };
407
- // Do not declare as `module` to avoid webpack bug
408
- // (see https://github.com/angular/angular/issues/30050).
409
- var module_ = function (prefix, dependencies) { return angular.module(prefix, dependencies); };
410
- var element = (function (e) { return angular.element(e); });
411
- element.cleanData = function (nodes) { return angular.element.cleanData(nodes); };
412
- var injector = function (modules, strictDi) { return angular.injector(modules, strictDi); };
413
- var resumeBootstrap = function () { return angular.resumeBootstrap(); };
414
- var getTestability = function (e) { return angular.getTestability(e); };
415
-
416
- /**
417
- * @license
418
- * Copyright Google LLC All Rights Reserved.
419
- *
420
- * Use of this source code is governed by an MIT-style license that can be
421
- * found in the LICENSE file at https://angular.io/license
422
- */
423
- var $COMPILE = '$compile';
424
- var $CONTROLLER = '$controller';
425
- var $DELEGATE = '$delegate';
426
- var $EXCEPTION_HANDLER = '$exceptionHandler';
427
- var $HTTP_BACKEND = '$httpBackend';
428
- var $INJECTOR = '$injector';
429
- var $INTERVAL = '$interval';
430
- var $PARSE = '$parse';
431
- var $PROVIDE = '$provide';
432
- var $ROOT_ELEMENT = '$rootElement';
433
- var $ROOT_SCOPE = '$rootScope';
434
- var $SCOPE = '$scope';
435
- var $TEMPLATE_CACHE = '$templateCache';
436
- var $TEMPLATE_REQUEST = '$templateRequest';
437
- var $$TESTABILITY = '$$testability';
438
- var COMPILER_KEY = '$$angularCompiler';
439
- var DOWNGRADED_MODULE_COUNT_KEY = '$$angularDowngradedModuleCount';
440
- var GROUP_PROJECTABLE_NODES_KEY = '$$angularGroupProjectableNodes';
441
- var INJECTOR_KEY = '$$angularInjector';
442
- var LAZY_MODULE_REF = '$$angularLazyModuleRef';
443
- var NG_ZONE_KEY = '$$angularNgZone';
444
- var UPGRADE_APP_TYPE_KEY = '$$angularUpgradeAppType';
445
- var REQUIRE_INJECTOR = '?^^' + INJECTOR_KEY;
446
- var REQUIRE_NG_MODEL = '?ngModel';
447
- var UPGRADE_MODULE_NAME = '$$UpgradeModule';
448
-
449
- /**
450
- * @license
451
- * Copyright Google LLC All Rights Reserved.
452
- *
453
- * Use of this source code is governed by an MIT-style license that can be
454
- * found in the LICENSE file at https://angular.io/license
455
- */
456
- /**
457
- * A `PropertyBinding` represents a mapping between a property name
458
- * and an attribute name. It is parsed from a string of the form
459
- * `"prop: attr"`; or simply `"propAndAttr" where the property
460
- * and attribute have the same identifier.
461
- */
462
- var PropertyBinding = /** @class */ (function () {
463
- function PropertyBinding(prop, attr) {
464
- this.prop = prop;
465
- this.attr = attr;
466
- this.parseBinding();
467
- }
468
- PropertyBinding.prototype.parseBinding = function () {
469
- this.bracketAttr = "[" + this.attr + "]";
470
- this.parenAttr = "(" + this.attr + ")";
471
- this.bracketParenAttr = "[(" + this.attr + ")]";
472
- var capitalAttr = this.attr.charAt(0).toUpperCase() + this.attr.substr(1);
473
- this.onAttr = "on" + capitalAttr;
474
- this.bindAttr = "bind" + capitalAttr;
475
- this.bindonAttr = "bindon" + capitalAttr;
476
- };
477
- return PropertyBinding;
478
- }());
479
-
480
- /**
481
- * @license
482
- * Copyright Google LLC All Rights Reserved.
483
- *
484
- * Use of this source code is governed by an MIT-style license that can be
485
- * found in the LICENSE file at https://angular.io/license
486
- */
487
- var DIRECTIVE_PREFIX_REGEXP = /^(?:x|data)[:\-_]/i;
488
- var DIRECTIVE_SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
489
- function onError(e) {
490
- // TODO: (misko): We seem to not have a stack trace here!
491
- if (console.error) {
492
- console.error(e, e.stack);
493
- }
494
- else {
495
- // tslint:disable-next-line:no-console
496
- console.log(e, e.stack);
497
- }
498
- throw e;
499
- }
500
- /**
501
- * Clean the jqLite/jQuery data on the element and all its descendants.
502
- * Equivalent to how jqLite/jQuery invoke `cleanData()` on an Element when removed:
503
- * https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/jqLite.js#L349-L355
504
- * https://github.com/jquery/jquery/blob/6984d1747623dbc5e87fd6c261a5b6b1628c107c/src/manipulation.js#L182
505
- *
506
- * NOTE:
507
- * `cleanData()` will also invoke the AngularJS `$destroy` DOM event on the element:
508
- * https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/Angular.js#L1932-L1945
509
- *
510
- * @param node The DOM node whose data needs to be cleaned.
511
- */
512
- function cleanData(node) {
513
- element.cleanData([node]);
514
- if (isParentNode(node)) {
515
- element.cleanData(node.querySelectorAll('*'));
516
- }
517
- }
518
- function controllerKey(name) {
519
- return '$' + name + 'Controller';
520
- }
521
- /**
522
- * Destroy an AngularJS app given the app `$injector`.
523
- *
524
- * NOTE: Destroying an app is not officially supported by AngularJS, but try to do our best by
525
- * destroying `$rootScope` and clean the jqLite/jQuery data on `$rootElement` and all
526
- * descendants.
527
- *
528
- * @param $injector The `$injector` of the AngularJS app to destroy.
529
- */
530
- function destroyApp($injector) {
531
- var $rootElement = $injector.get($ROOT_ELEMENT);
532
- var $rootScope = $injector.get($ROOT_SCOPE);
533
- $rootScope.$destroy();
534
- cleanData($rootElement[0]);
535
- }
536
- function directiveNormalize(name) {
537
- return name.replace(DIRECTIVE_PREFIX_REGEXP, '')
538
- .replace(DIRECTIVE_SPECIAL_CHARS_REGEXP, function (_, letter) { return letter.toUpperCase(); });
539
- }
540
- function getTypeName(type) {
541
- // Return the name of the type or the first line of its stringified version.
542
- return type.overriddenName || type.name || type.toString().split('\n')[0];
543
- }
544
- function getDowngradedModuleCount($injector) {
545
- return $injector.has(DOWNGRADED_MODULE_COUNT_KEY) ? $injector.get(DOWNGRADED_MODULE_COUNT_KEY) :
546
- 0;
547
- }
548
- function getUpgradeAppType($injector) {
549
- return $injector.has(UPGRADE_APP_TYPE_KEY) ? $injector.get(UPGRADE_APP_TYPE_KEY) :
550
- 0 /* None */;
551
- }
552
- function isFunction(value) {
553
- return typeof value === 'function';
554
- }
555
- function isParentNode(node) {
556
- return isFunction(node.querySelectorAll);
557
- }
558
- function validateInjectionKey($injector, downgradedModule, injectionKey, attemptedAction) {
559
- var upgradeAppType = getUpgradeAppType($injector);
560
- var downgradedModuleCount = getDowngradedModuleCount($injector);
561
- // Check for common errors.
562
- switch (upgradeAppType) {
563
- case 1 /* Dynamic */:
564
- case 2 /* Static */:
565
- if (downgradedModule) {
566
- throw new Error("Error while " + attemptedAction + ": 'downgradedModule' unexpectedly specified.\n" +
567
- 'You should not specify a value for \'downgradedModule\', unless you are downgrading ' +
568
- 'more than one Angular module (via \'downgradeModule()\').');
569
- }
570
- break;
571
- case 3 /* Lite */:
572
- if (!downgradedModule && (downgradedModuleCount >= 2)) {
573
- throw new Error("Error while " + attemptedAction + ": 'downgradedModule' not specified.\n" +
574
- 'This application contains more than one downgraded Angular module, thus you need to ' +
575
- 'always specify \'downgradedModule\' when downgrading components and injectables.');
576
- }
577
- if (!$injector.has(injectionKey)) {
578
- throw new Error("Error while " + attemptedAction + ": Unable to find the specified downgraded module.\n" +
579
- 'Did you forget to downgrade an Angular module or include it in the AngularJS ' +
580
- 'application?');
581
- }
582
- break;
583
- default:
584
- throw new Error("Error while " + attemptedAction + ": Not a valid '@angular/upgrade' application.\n" +
585
- 'Did you forget to downgrade an Angular module or include it in the AngularJS ' +
586
- 'application?');
587
- }
588
- }
589
- var Deferred = /** @class */ (function () {
590
- function Deferred() {
591
- var _this = this;
592
- this.promise = new Promise(function (res, rej) {
593
- _this.resolve = res;
594
- _this.reject = rej;
595
- });
596
- }
597
- return Deferred;
598
- }());
599
- /**
600
- * @return Whether the passed-in component implements the subset of the
601
- * `ControlValueAccessor` interface needed for AngularJS `ng-model`
602
- * compatibility.
603
- */
604
- function supportsNgModel(component) {
605
- return typeof component.writeValue === 'function' &&
606
- typeof component.registerOnChange === 'function';
607
- }
608
- /**
609
- * Glue the AngularJS `NgModelController` (if it exists) to the component
610
- * (if it implements the needed subset of the `ControlValueAccessor` interface).
611
- */
612
- function hookupNgModel(ngModel, component) {
613
- if (ngModel && supportsNgModel(component)) {
614
- ngModel.$render = function () {
615
- component.writeValue(ngModel.$viewValue);
616
- };
617
- component.registerOnChange(ngModel.$setViewValue.bind(ngModel));
618
- if (typeof component.registerOnTouched === 'function') {
619
- component.registerOnTouched(ngModel.$setTouched.bind(ngModel));
620
- }
621
- }
622
- }
623
- /**
624
- * Test two values for strict equality, accounting for the fact that `NaN !== NaN`.
625
- */
626
- function strictEquals(val1, val2) {
627
- return val1 === val2 || (val1 !== val1 && val2 !== val2);
628
- }
629
-
630
- /**
631
- * @license
632
- * Copyright Google LLC All Rights Reserved.
633
- *
634
- * Use of this source code is governed by an MIT-style license that can be
635
- * found in the LICENSE file at https://angular.io/license
636
- */
637
- var INITIAL_VALUE = {
638
- __UNINITIALIZED__: true
639
- };
640
- var DowngradeComponentAdapter = /** @class */ (function () {
641
- function DowngradeComponentAdapter(element, attrs, scope, ngModel, parentInjector, $compile, $parse, componentFactory, wrapCallback) {
642
- this.element = element;
643
- this.attrs = attrs;
644
- this.scope = scope;
645
- this.ngModel = ngModel;
646
- this.parentInjector = parentInjector;
647
- this.$compile = $compile;
648
- this.$parse = $parse;
649
- this.componentFactory = componentFactory;
650
- this.wrapCallback = wrapCallback;
651
- this.implementsOnChanges = false;
652
- this.inputChangeCount = 0;
653
- this.inputChanges = {};
654
- this.componentScope = scope.$new();
655
- }
656
- DowngradeComponentAdapter.prototype.compileContents = function () {
657
- var _this = this;
658
- var compiledProjectableNodes = [];
659
- var projectableNodes = this.groupProjectableNodes();
660
- var linkFns = projectableNodes.map(function (nodes) { return _this.$compile(nodes); });
661
- this.element.empty();
662
- linkFns.forEach(function (linkFn) {
663
- linkFn(_this.scope, function (clone) {
664
- compiledProjectableNodes.push(clone);
665
- _this.element.append(clone);
666
- });
667
- });
668
- return compiledProjectableNodes;
669
- };
670
- DowngradeComponentAdapter.prototype.createComponent = function (projectableNodes) {
671
- var providers = [{ provide: $SCOPE, useValue: this.componentScope }];
672
- var childInjector = core.Injector.create({ providers: providers, parent: this.parentInjector, name: 'DowngradeComponentAdapter' });
673
- this.componentRef =
674
- this.componentFactory.create(childInjector, projectableNodes, this.element[0]);
675
- this.viewChangeDetector = this.componentRef.injector.get(core.ChangeDetectorRef);
676
- this.changeDetector = this.componentRef.changeDetectorRef;
677
- this.component = this.componentRef.instance;
678
- // testability hook is commonly added during component bootstrap in
679
- // packages/core/src/application_ref.bootstrap()
680
- // in downgraded application, component creation will take place here as well as adding the
681
- // testability hook.
682
- var testability = this.componentRef.injector.get(core.Testability, null);
683
- if (testability) {
684
- this.componentRef.injector.get(core.TestabilityRegistry)
685
- .registerApplication(this.componentRef.location.nativeElement, testability);
686
- }
687
- hookupNgModel(this.ngModel, this.component);
688
- };
689
- DowngradeComponentAdapter.prototype.setupInputs = function (manuallyAttachView, propagateDigest) {
690
- var _this = this;
691
- if (propagateDigest === void 0) { propagateDigest = true; }
692
- var attrs = this.attrs;
693
- var inputs = this.componentFactory.inputs || [];
694
- var _loop_1 = function (i) {
695
- var input = new PropertyBinding(inputs[i].propName, inputs[i].templateName);
696
- var expr = null;
697
- if (attrs.hasOwnProperty(input.attr)) {
698
- var observeFn_1 = (function (prop) {
699
- var prevValue = INITIAL_VALUE;
700
- return function (currValue) {
701
- // Initially, both `$observe()` and `$watch()` will call this function.
702
- if (!strictEquals(prevValue, currValue)) {
703
- if (prevValue === INITIAL_VALUE) {
704
- prevValue = currValue;
705
- }
706
- _this.updateInput(prop, prevValue, currValue);
707
- prevValue = currValue;
708
- }
709
- };
710
- })(input.prop);
711
- attrs.$observe(input.attr, observeFn_1);
712
- // Use `$watch()` (in addition to `$observe()`) in order to initialize the input in time
713
- // for `ngOnChanges()`. This is necessary if we are already in a `$digest`, which means that
714
- // `ngOnChanges()` (which is called by a watcher) will run before the `$observe()` callback.
715
- var unwatch_1 = this_1.componentScope.$watch(function () {
716
- unwatch_1();
717
- unwatch_1 = null;
718
- observeFn_1(attrs[input.attr]);
719
- });
720
- }
721
- else if (attrs.hasOwnProperty(input.bindAttr)) {
722
- expr = attrs[input.bindAttr];
723
- }
724
- else if (attrs.hasOwnProperty(input.bracketAttr)) {
725
- expr = attrs[input.bracketAttr];
726
- }
727
- else if (attrs.hasOwnProperty(input.bindonAttr)) {
728
- expr = attrs[input.bindonAttr];
729
- }
730
- else if (attrs.hasOwnProperty(input.bracketParenAttr)) {
731
- expr = attrs[input.bracketParenAttr];
732
- }
733
- if (expr != null) {
734
- var watchFn = (function (prop) { return function (currValue, prevValue) { return _this.updateInput(prop, prevValue, currValue); }; })(input.prop);
735
- this_1.componentScope.$watch(expr, watchFn);
736
- }
737
- };
738
- var this_1 = this;
739
- for (var i = 0; i < inputs.length; i++) {
740
- _loop_1(i);
741
- }
742
- // Invoke `ngOnChanges()` and Change Detection (when necessary)
743
- var detectChanges = function () { return _this.changeDetector.detectChanges(); };
744
- var prototype = this.componentFactory.componentType.prototype;
745
- this.implementsOnChanges = !!(prototype && prototype.ngOnChanges);
746
- this.componentScope.$watch(function () { return _this.inputChangeCount; }, this.wrapCallback(function () {
747
- // Invoke `ngOnChanges()`
748
- if (_this.implementsOnChanges) {
749
- var inputChanges = _this.inputChanges;
750
- _this.inputChanges = {};
751
- _this.component.ngOnChanges(inputChanges);
752
- }
753
- _this.viewChangeDetector.markForCheck();
754
- // If opted out of propagating digests, invoke change detection when inputs change.
755
- if (!propagateDigest) {
756
- detectChanges();
757
- }
758
- }));
759
- // If not opted out of propagating digests, invoke change detection on every digest
760
- if (propagateDigest) {
761
- this.componentScope.$watch(this.wrapCallback(detectChanges));
762
- }
763
- // If necessary, attach the view so that it will be dirty-checked.
764
- // (Allow time for the initial input values to be set and `ngOnChanges()` to be called.)
765
- if (manuallyAttachView || !propagateDigest) {
766
- var unwatch_2 = this.componentScope.$watch(function () {
767
- unwatch_2();
768
- unwatch_2 = null;
769
- var appRef = _this.parentInjector.get(core.ApplicationRef);
770
- appRef.attachView(_this.componentRef.hostView);
771
- });
772
- }
773
- };
774
- DowngradeComponentAdapter.prototype.setupOutputs = function () {
775
- var attrs = this.attrs;
776
- var outputs = this.componentFactory.outputs || [];
777
- for (var j = 0; j < outputs.length; j++) {
778
- var output = new PropertyBinding(outputs[j].propName, outputs[j].templateName);
779
- var bindonAttr = output.bindonAttr.substring(0, output.bindonAttr.length - 6);
780
- var bracketParenAttr = "[(" + output.bracketParenAttr.substring(2, output.bracketParenAttr.length - 8) + ")]";
781
- // order below is important - first update bindings then evaluate expressions
782
- if (attrs.hasOwnProperty(bindonAttr)) {
783
- this.subscribeToOutput(output, attrs[bindonAttr], true);
784
- }
785
- if (attrs.hasOwnProperty(bracketParenAttr)) {
786
- this.subscribeToOutput(output, attrs[bracketParenAttr], true);
787
- }
788
- if (attrs.hasOwnProperty(output.onAttr)) {
789
- this.subscribeToOutput(output, attrs[output.onAttr]);
790
- }
791
- if (attrs.hasOwnProperty(output.parenAttr)) {
792
- this.subscribeToOutput(output, attrs[output.parenAttr]);
793
- }
794
- }
795
- };
796
- DowngradeComponentAdapter.prototype.subscribeToOutput = function (output, expr, isAssignment) {
797
- var _this = this;
798
- if (isAssignment === void 0) { isAssignment = false; }
799
- var getter = this.$parse(expr);
800
- var setter = getter.assign;
801
- if (isAssignment && !setter) {
802
- throw new Error("Expression '" + expr + "' is not assignable!");
803
- }
804
- var emitter = this.component[output.prop];
805
- if (emitter) {
806
- emitter.subscribe({
807
- next: isAssignment ? function (v) { return setter(_this.scope, v); } :
808
- function (v) { return getter(_this.scope, { '$event': v }); }
809
- });
810
- }
811
- else {
812
- throw new Error("Missing emitter '" + output.prop + "' on component '" + getTypeName(this.componentFactory.componentType) + "'!");
813
- }
814
- };
815
- DowngradeComponentAdapter.prototype.registerCleanup = function () {
816
- var _this = this;
817
- var testabilityRegistry = this.componentRef.injector.get(core.TestabilityRegistry);
818
- var destroyComponentRef = this.wrapCallback(function () { return _this.componentRef.destroy(); });
819
- var destroyed = false;
820
- this.element.on('$destroy', function () {
821
- // The `$destroy` event may have been triggered by the `cleanData()` call in the
822
- // `componentScope` `$destroy` handler below. In that case, we don't want to call
823
- // `componentScope.$destroy()` again.
824
- if (!destroyed)
825
- _this.componentScope.$destroy();
826
- });
827
- this.componentScope.$on('$destroy', function () {
828
- if (!destroyed) {
829
- destroyed = true;
830
- testabilityRegistry.unregisterApplication(_this.componentRef.location.nativeElement);
831
- // The `componentScope` might be getting destroyed, because an ancestor element is being
832
- // removed/destroyed. If that is the case, jqLite/jQuery would normally invoke `cleanData()`
833
- // on the removed element and all descendants.
834
- // https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/jqLite.js#L349-L355
835
- // https://github.com/jquery/jquery/blob/6984d1747623dbc5e87fd6c261a5b6b1628c107c/src/manipulation.js#L182
836
- //
837
- // Here, however, `destroyComponentRef()` may under some circumstances remove the element
838
- // from the DOM and therefore it will no longer be a descendant of the removed element when
839
- // `cleanData()` is called. This would result in a memory leak, because the element's data
840
- // and event handlers (and all objects directly or indirectly referenced by them) would be
841
- // retained.
842
- //
843
- // To ensure the element is always properly cleaned up, we manually call `cleanData()` on
844
- // this element and its descendants before destroying the `ComponentRef`.
845
- cleanData(_this.element[0]);
846
- destroyComponentRef();
847
- }
848
- });
849
- };
850
- DowngradeComponentAdapter.prototype.getInjector = function () {
851
- return this.componentRef.injector;
852
- };
853
- DowngradeComponentAdapter.prototype.updateInput = function (prop, prevValue, currValue) {
854
- if (this.implementsOnChanges) {
855
- this.inputChanges[prop] = new core.SimpleChange(prevValue, currValue, prevValue === currValue);
856
- }
857
- this.inputChangeCount++;
858
- this.component[prop] = currValue;
859
- };
860
- DowngradeComponentAdapter.prototype.groupProjectableNodes = function () {
861
- var ngContentSelectors = this.componentFactory.ngContentSelectors;
862
- return groupNodesBySelector(ngContentSelectors, this.element.contents());
863
- };
864
- return DowngradeComponentAdapter;
865
- }());
866
- /**
867
- * Group a set of DOM nodes into `ngContent` groups, based on the given content selectors.
868
- */
869
- function groupNodesBySelector(ngContentSelectors, nodes) {
870
- var projectableNodes = [];
871
- for (var i = 0, ii = ngContentSelectors.length; i < ii; ++i) {
872
- projectableNodes[i] = [];
873
- }
874
- for (var j = 0, jj = nodes.length; j < jj; ++j) {
875
- var node = nodes[j];
876
- var ngContentIndex = findMatchingNgContentIndex(node, ngContentSelectors);
877
- if (ngContentIndex != null) {
878
- projectableNodes[ngContentIndex].push(node);
879
- }
880
- }
881
- return projectableNodes;
882
- }
883
- function findMatchingNgContentIndex(element, ngContentSelectors) {
884
- var ngContentIndices = [];
885
- var wildcardNgContentIndex = -1;
886
- for (var i = 0; i < ngContentSelectors.length; i++) {
887
- var selector = ngContentSelectors[i];
888
- if (selector === '*') {
889
- wildcardNgContentIndex = i;
890
- }
891
- else {
892
- if (matchesSelector(element, selector)) {
893
- ngContentIndices.push(i);
894
- }
895
- }
896
- }
897
- ngContentIndices.sort();
898
- if (wildcardNgContentIndex !== -1) {
899
- ngContentIndices.push(wildcardNgContentIndex);
900
- }
901
- return ngContentIndices.length ? ngContentIndices[0] : null;
902
- }
903
- var _matches;
904
- function matchesSelector(el, selector) {
905
- if (!_matches) {
906
- var elProto = Element.prototype;
907
- _matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector ||
908
- elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector;
909
- }
910
- return el.nodeType === Node.ELEMENT_NODE ? _matches.call(el, selector) : false;
911
- }
912
-
913
- /**
914
- * @license
915
- * Copyright Google LLC All Rights Reserved.
916
- *
917
- * Use of this source code is governed by an MIT-style license that can be
918
- * found in the LICENSE file at https://angular.io/license
919
- */
920
- function isThenable(obj) {
921
- return !!obj && isFunction(obj.then);
922
- }
923
- /**
924
- * Synchronous, promise-like object.
925
- */
926
- var SyncPromise = /** @class */ (function () {
927
- function SyncPromise() {
928
- this.resolved = false;
929
- this.callbacks = [];
930
- }
931
- SyncPromise.all = function (valuesOrPromises) {
932
- var aggrPromise = new SyncPromise();
933
- var resolvedCount = 0;
934
- var results = [];
935
- var resolve = function (idx, value) {
936
- results[idx] = value;
937
- if (++resolvedCount === valuesOrPromises.length)
938
- aggrPromise.resolve(results);
939
- };
940
- valuesOrPromises.forEach(function (p, idx) {
941
- if (isThenable(p)) {
942
- p.then(function (v) { return resolve(idx, v); });
943
- }
944
- else {
945
- resolve(idx, p);
946
- }
947
- });
948
- return aggrPromise;
949
- };
950
- SyncPromise.prototype.resolve = function (value) {
951
- // Do nothing, if already resolved.
952
- if (this.resolved)
953
- return;
954
- this.value = value;
955
- this.resolved = true;
956
- // Run the queued callbacks.
957
- this.callbacks.forEach(function (callback) { return callback(value); });
958
- this.callbacks.length = 0;
959
- };
960
- SyncPromise.prototype.then = function (callback) {
961
- if (this.resolved) {
962
- callback(this.value);
963
- }
964
- else {
965
- this.callbacks.push(callback);
966
- }
967
- };
968
- return SyncPromise;
969
- }());
970
-
971
- /**
972
- * @description
973
- *
974
- * A helper function that allows an Angular component to be used from AngularJS.
975
- *
976
- * *Part of the [upgrade/static](api?query=upgrade%2Fstatic)
977
- * library for hybrid upgrade apps that support AOT compilation*
978
- *
979
- * This helper function returns a factory function to be used for registering
980
- * an AngularJS wrapper directive for "downgrading" an Angular component.
981
- *
982
- * @usageNotes
983
- * ### Examples
984
- *
985
- * Let's assume that you have an Angular component called `ng2Heroes` that needs
986
- * to be made available in AngularJS templates.
987
- *
988
- * {@example upgrade/static/ts/full/module.ts region="ng2-heroes"}
989
- *
990
- * We must create an AngularJS [directive](https://docs.angularjs.org/guide/directive)
991
- * that will make this Angular component available inside AngularJS templates.
992
- * The `downgradeComponent()` function returns a factory function that we
993
- * can use to define the AngularJS directive that wraps the "downgraded" component.
994
- *
995
- * {@example upgrade/static/ts/full/module.ts region="ng2-heroes-wrapper"}
996
- *
997
- * For more details and examples on downgrading Angular components to AngularJS components please
998
- * visit the [Upgrade guide](guide/upgrade#using-angular-components-from-angularjs-code).
999
- *
1000
- * @param info contains information about the Component that is being downgraded:
1001
- *
1002
- * - `component: Type<any>`: The type of the Component that will be downgraded
1003
- * - `downgradedModule?: string`: The name of the downgraded module (if any) that the component
1004
- * "belongs to", as returned by a call to `downgradeModule()`. It is the module, whose
1005
- * corresponding Angular module will be bootstrapped, when the component needs to be instantiated.
1006
- * <br />
1007
- * (This option is only necessary when using `downgradeModule()` to downgrade more than one
1008
- * Angular module.)
1009
- * - `propagateDigest?: boolean`: Whether to perform {@link ChangeDetectorRef#detectChanges
1010
- * change detection} on the component on every
1011
- * [$digest](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest). If set to `false`,
1012
- * change detection will still be performed when any of the component's inputs changes.
1013
- * (Default: true)
1014
- *
1015
- * @returns a factory function that can be used to register the component in an
1016
- * AngularJS module.
1017
- *
1018
- * @publicApi
1019
- */
1020
- function downgradeComponent(info) {
1021
- var directiveFactory = function ($compile, $injector, $parse) {
1022
- // When using `downgradeModule()`, we need to handle certain things specially. For example:
1023
- // - We always need to attach the component view to the `ApplicationRef` for it to be
1024
- // dirty-checked.
1025
- // - We need to ensure callbacks to Angular APIs (e.g. change detection) are run inside the
1026
- // Angular zone.
1027
- // NOTE: This is not needed, when using `UpgradeModule`, because `$digest()` will be run
1028
- // inside the Angular zone (except if explicitly escaped, in which case we shouldn't
1029
- // force it back in).
1030
- var isNgUpgradeLite = getUpgradeAppType($injector) === 3 /* Lite */;
1031
- var wrapCallback = !isNgUpgradeLite ? function (cb) { return cb; } : function (cb) { return function () { return core.NgZone.isInAngularZone() ? cb() : ngZone.run(cb); }; };
1032
- var ngZone;
1033
- // When downgrading multiple modules, special handling is needed wrt injectors.
1034
- var hasMultipleDowngradedModules = isNgUpgradeLite && (getDowngradedModuleCount($injector) > 1);
1035
- return {
1036
- restrict: 'E',
1037
- terminal: true,
1038
- require: [REQUIRE_INJECTOR, REQUIRE_NG_MODEL],
1039
- link: function (scope, element, attrs, required) {
1040
- // We might have to compile the contents asynchronously, because this might have been
1041
- // triggered by `UpgradeNg1ComponentAdapterBuilder`, before the Angular templates have
1042
- // been compiled.
1043
- var ngModel = required[1];
1044
- var parentInjector = required[0];
1045
- var moduleInjector = undefined;
1046
- var ranAsync = false;
1047
- if (!parentInjector || hasMultipleDowngradedModules) {
1048
- var downgradedModule = info.downgradedModule || '';
1049
- var lazyModuleRefKey = "" + LAZY_MODULE_REF + downgradedModule;
1050
- var attemptedAction = "instantiating component '" + getTypeName(info.component) + "'";
1051
- validateInjectionKey($injector, downgradedModule, lazyModuleRefKey, attemptedAction);
1052
- var lazyModuleRef = $injector.get(lazyModuleRefKey);
1053
- moduleInjector = lazyModuleRef.injector || lazyModuleRef.promise;
1054
- }
1055
- // Notes:
1056
- //
1057
- // There are two injectors: `finalModuleInjector` and `finalParentInjector` (they might be
1058
- // the same instance, but that is irrelevant):
1059
- // - `finalModuleInjector` is used to retrieve `ComponentFactoryResolver`, thus it must be
1060
- // on the same tree as the `NgModule` that declares this downgraded component.
1061
- // - `finalParentInjector` is used for all other injection purposes.
1062
- // (Note that Angular knows to only traverse the component-tree part of that injector,
1063
- // when looking for an injectable and then switch to the module injector.)
1064
- //
1065
- // There are basically three cases:
1066
- // - If there is no parent component (thus no `parentInjector`), we bootstrap the downgraded
1067
- // `NgModule` and use its injector as both `finalModuleInjector` and
1068
- // `finalParentInjector`.
1069
- // - If there is a parent component (and thus a `parentInjector`) and we are sure that it
1070
- // belongs to the same `NgModule` as this downgraded component (e.g. because there is only
1071
- // one downgraded module, we use that `parentInjector` as both `finalModuleInjector` and
1072
- // `finalParentInjector`.
1073
- // - If there is a parent component, but it may belong to a different `NgModule`, then we
1074
- // use the `parentInjector` as `finalParentInjector` and this downgraded component's
1075
- // declaring `NgModule`'s injector as `finalModuleInjector`.
1076
- // Note 1: If the `NgModule` is already bootstrapped, we just get its injector (we don't
1077
- // bootstrap again).
1078
- // Note 2: It is possible that (while there are multiple downgraded modules) this
1079
- // downgraded component and its parent component both belong to the same NgModule.
1080
- // In that case, we could have used the `parentInjector` as both
1081
- // `finalModuleInjector` and `finalParentInjector`, but (for simplicity) we are
1082
- // treating this case as if they belong to different `NgModule`s. That doesn't
1083
- // really affect anything, since `parentInjector` has `moduleInjector` as ancestor
1084
- // and trying to resolve `ComponentFactoryResolver` from either one will return
1085
- // the same instance.
1086
- // If there is a parent component, use its injector as parent injector.
1087
- // If this is a "top-level" Angular component, use the module injector.
1088
- var finalParentInjector = parentInjector || moduleInjector;
1089
- // If this is a "top-level" Angular component or the parent component may belong to a
1090
- // different `NgModule`, use the module injector for module-specific dependencies.
1091
- // If there is a parent component that belongs to the same `NgModule`, use its injector.
1092
- var finalModuleInjector = moduleInjector || parentInjector;
1093
- var doDowngrade = function (injector, moduleInjector) {
1094
- // Retrieve `ComponentFactoryResolver` from the injector tied to the `NgModule` this
1095
- // component belongs to.
1096
- var componentFactoryResolver = moduleInjector.get(core.ComponentFactoryResolver);
1097
- var componentFactory = componentFactoryResolver.resolveComponentFactory(info.component);
1098
- if (!componentFactory) {
1099
- throw new Error("Expecting ComponentFactory for: " + getTypeName(info.component));
1100
- }
1101
- var injectorPromise = new ParentInjectorPromise(element);
1102
- var facade = new DowngradeComponentAdapter(element, attrs, scope, ngModel, injector, $compile, $parse, componentFactory, wrapCallback);
1103
- var projectableNodes = facade.compileContents();
1104
- facade.createComponent(projectableNodes);
1105
- facade.setupInputs(isNgUpgradeLite, info.propagateDigest);
1106
- facade.setupOutputs();
1107
- facade.registerCleanup();
1108
- injectorPromise.resolve(facade.getInjector());
1109
- if (ranAsync) {
1110
- // If this is run async, it is possible that it is not run inside a
1111
- // digest and initial input values will not be detected.
1112
- scope.$evalAsync(function () { });
1113
- }
1114
- };
1115
- var downgradeFn = !isNgUpgradeLite ? doDowngrade : function (pInjector, mInjector) {
1116
- if (!ngZone) {
1117
- ngZone = pInjector.get(core.NgZone);
1118
- }
1119
- wrapCallback(function () { return doDowngrade(pInjector, mInjector); })();
1120
- };
1121
- // NOTE:
1122
- // Not using `ParentInjectorPromise.all()` (which is inherited from `SyncPromise`), because
1123
- // Closure Compiler (or some related tool) complains:
1124
- // `TypeError: ...$src$downgrade_component_ParentInjectorPromise.all is not a function`
1125
- SyncPromise.all([finalParentInjector, finalModuleInjector])
1126
- .then(function (_a) {
1127
- var _b = __read(_a, 2), pInjector = _b[0], mInjector = _b[1];
1128
- return downgradeFn(pInjector, mInjector);
1129
- });
1130
- ranAsync = true;
1131
- }
1132
- };
1133
- };
1134
- // bracket-notation because of closure - see #14441
1135
- directiveFactory['$inject'] = [$COMPILE, $INJECTOR, $PARSE];
1136
- return directiveFactory;
1137
- }
1138
- /**
1139
- * Synchronous promise-like object to wrap parent injectors,
1140
- * to preserve the synchronous nature of AngularJS's `$compile`.
1141
- */
1142
- var ParentInjectorPromise = /** @class */ (function (_super) {
1143
- __extends(ParentInjectorPromise, _super);
1144
- function ParentInjectorPromise(element) {
1145
- var _this = _super.call(this) || this;
1146
- _this.element = element;
1147
- _this.injectorKey = controllerKey(INJECTOR_KEY);
1148
- // Store the promise on the element.
1149
- element.data(_this.injectorKey, _this);
1150
- return _this;
1151
- }
1152
- ParentInjectorPromise.prototype.resolve = function (injector) {
1153
- // Store the real injector on the element.
1154
- this.element.data(this.injectorKey, injector);
1155
- // Release the element to prevent memory leaks.
1156
- this.element = null;
1157
- // Resolve the promise.
1158
- _super.prototype.resolve.call(this, injector);
1159
- };
1160
- return ParentInjectorPromise;
1161
- }(SyncPromise));
1162
-
1163
- /**
1164
- * @license
1165
- * Copyright Google LLC All Rights Reserved.
1166
- *
1167
- * Use of this source code is governed by an MIT-style license that can be
1168
- * found in the LICENSE file at https://angular.io/license
1169
- */
1170
- /**
1171
- * @description
1172
- *
1173
- * A helper function to allow an Angular service to be accessible from AngularJS.
1174
- *
1175
- * *Part of the [upgrade/static](api?query=upgrade%2Fstatic)
1176
- * library for hybrid upgrade apps that support AOT compilation*
1177
- *
1178
- * This helper function returns a factory function that provides access to the Angular
1179
- * service identified by the `token` parameter.
1180
- *
1181
- * @usageNotes
1182
- * ### Examples
1183
- *
1184
- * First ensure that the service to be downgraded is provided in an `NgModule`
1185
- * that will be part of the upgrade application. For example, let's assume we have
1186
- * defined `HeroesService`
1187
- *
1188
- * {@example upgrade/static/ts/full/module.ts region="ng2-heroes-service"}
1189
- *
1190
- * and that we have included this in our upgrade app `NgModule`
1191
- *
1192
- * {@example upgrade/static/ts/full/module.ts region="ng2-module"}
1193
- *
1194
- * Now we can register the `downgradeInjectable` factory function for the service
1195
- * on an AngularJS module.
1196
- *
1197
- * {@example upgrade/static/ts/full/module.ts region="downgrade-ng2-heroes-service"}
1198
- *
1199
- * Inside an AngularJS component's controller we can get hold of the
1200
- * downgraded service via the name we gave when downgrading.
1201
- *
1202
- * {@example upgrade/static/ts/full/module.ts region="example-app"}
1203
- *
1204
- * <div class="alert is-important">
1205
- *
1206
- * When using `downgradeModule()`, downgraded injectables will not be available until the Angular
1207
- * module that provides them is instantiated. In order to be safe, you need to ensure that the
1208
- * downgraded injectables are not used anywhere _outside_ the part of the app where it is
1209
- * guaranteed that their module has been instantiated.
1210
- *
1211
- * For example, it is _OK_ to use a downgraded service in an upgraded component that is only used
1212
- * from a downgraded Angular component provided by the same Angular module as the injectable, but
1213
- * it is _not OK_ to use it in an AngularJS component that may be used independently of Angular or
1214
- * use it in a downgraded Angular component from a different module.
1215
- *
1216
- * </div>
1217
- *
1218
- * @param token an `InjectionToken` that identifies a service provided from Angular.
1219
- * @param downgradedModule the name of the downgraded module (if any) that the injectable
1220
- * "belongs to", as returned by a call to `downgradeModule()`. It is the module, whose injector will
1221
- * be used for instantiating the injectable.<br />
1222
- * (This option is only necessary when using `downgradeModule()` to downgrade more than one Angular
1223
- * module.)
1224
- *
1225
- * @returns a [factory function](https://docs.angularjs.org/guide/di) that can be
1226
- * used to register the service on an AngularJS module.
1227
- *
1228
- * @publicApi
1229
- */
1230
- function downgradeInjectable(token, downgradedModule) {
1231
- if (downgradedModule === void 0) { downgradedModule = ''; }
1232
- var factory = function ($injector) {
1233
- var injectorKey = "" + INJECTOR_KEY + downgradedModule;
1234
- var injectableName = isFunction(token) ? getTypeName(token) : String(token);
1235
- var attemptedAction = "instantiating injectable '" + injectableName + "'";
1236
- validateInjectionKey($injector, downgradedModule, injectorKey, attemptedAction);
1237
- try {
1238
- var injector = $injector.get(injectorKey);
1239
- return injector.get(token);
1240
- }
1241
- catch (err) {
1242
- throw new Error("Error while " + attemptedAction + ": " + (err.message || err));
1243
- }
1244
- };
1245
- factory['$inject'] = [$INJECTOR];
1246
- return factory;
1247
- }
1248
-
1249
- // Constants
1250
- var REQUIRE_PREFIX_RE = /^(\^\^?)?(\?)?(\^\^?)?/;
1251
- // Classes
1252
- var UpgradeHelper = /** @class */ (function () {
1253
- function UpgradeHelper(injector, name, elementRef, directive) {
1254
- this.name = name;
1255
- this.$injector = injector.get($INJECTOR);
1256
- this.$compile = this.$injector.get($COMPILE);
1257
- this.$controller = this.$injector.get($CONTROLLER);
1258
- this.element = elementRef.nativeElement;
1259
- this.$element = element(this.element);
1260
- this.directive = directive || UpgradeHelper.getDirective(this.$injector, name);
1261
- }
1262
- UpgradeHelper.getDirective = function ($injector, name) {
1263
- var directives = $injector.get(name + 'Directive');
1264
- if (directives.length > 1) {
1265
- throw new Error("Only support single directive definition for: " + name);
1266
- }
1267
- var directive = directives[0];
1268
- // AngularJS will transform `link: xyz` to `compile: () => xyz`. So we can only tell there was a
1269
- // user-defined `compile` if there is no `link`. In other cases, we will just ignore `compile`.
1270
- if (directive.compile && !directive.link)
1271
- notSupported(name, 'compile');
1272
- if (directive.replace)
1273
- notSupported(name, 'replace');
1274
- if (directive.terminal)
1275
- notSupported(name, 'terminal');
1276
- return directive;
1277
- };
1278
- UpgradeHelper.getTemplate = function ($injector, directive, fetchRemoteTemplate, $element) {
1279
- if (fetchRemoteTemplate === void 0) { fetchRemoteTemplate = false; }
1280
- if (directive.template !== undefined) {
1281
- return getOrCall(directive.template, $element);
1282
- }
1283
- else if (directive.templateUrl) {
1284
- var $templateCache_1 = $injector.get($TEMPLATE_CACHE);
1285
- var url_1 = getOrCall(directive.templateUrl, $element);
1286
- var template = $templateCache_1.get(url_1);
1287
- if (template !== undefined) {
1288
- return template;
1289
- }
1290
- else if (!fetchRemoteTemplate) {
1291
- throw new Error('loading directive templates asynchronously is not supported');
1292
- }
1293
- return new Promise(function (resolve, reject) {
1294
- var $httpBackend = $injector.get($HTTP_BACKEND);
1295
- $httpBackend('GET', url_1, null, function (status, response) {
1296
- if (status === 200) {
1297
- resolve($templateCache_1.put(url_1, response));
1298
- }
1299
- else {
1300
- reject("GET component template from '" + url_1 + "' returned '" + status + ": " + response + "'");
1301
- }
1302
- });
1303
- });
1304
- }
1305
- else {
1306
- throw new Error("Directive '" + directive.name + "' is not a component, it is missing template.");
1307
- }
1308
- };
1309
- UpgradeHelper.prototype.buildController = function (controllerType, $scope) {
1310
- // TODO: Document that we do not pre-assign bindings on the controller instance.
1311
- // Quoted properties below so that this code can be optimized with Closure Compiler.
1312
- var locals = { '$scope': $scope, '$element': this.$element };
1313
- var controller = this.$controller(controllerType, locals, null, this.directive.controllerAs);
1314
- this.$element.data(controllerKey(this.directive.name), controller);
1315
- return controller;
1316
- };
1317
- UpgradeHelper.prototype.compileTemplate = function (template) {
1318
- if (template === undefined) {
1319
- template =
1320
- UpgradeHelper.getTemplate(this.$injector, this.directive, false, this.$element);
1321
- }
1322
- return this.compileHtml(template);
1323
- };
1324
- UpgradeHelper.prototype.onDestroy = function ($scope, controllerInstance) {
1325
- if (controllerInstance && isFunction(controllerInstance.$onDestroy)) {
1326
- controllerInstance.$onDestroy();
1327
- }
1328
- $scope.$destroy();
1329
- cleanData(this.element);
1330
- };
1331
- UpgradeHelper.prototype.prepareTransclusion = function () {
1332
- var _this = this;
1333
- var transclude = this.directive.transclude;
1334
- var contentChildNodes = this.extractChildNodes();
1335
- var attachChildrenFn = function (scope, cloneAttachFn) {
1336
- // Since AngularJS v1.5.8, `cloneAttachFn` will try to destroy the transclusion scope if
1337
- // `$template` is empty. Since the transcluded content comes from Angular, not AngularJS,
1338
- // there will be no transclusion scope here.
1339
- // Provide a dummy `scope.$destroy()` method to prevent `cloneAttachFn` from throwing.
1340
- scope = scope || { $destroy: function () { return undefined; } };
1341
- return cloneAttachFn($template, scope);
1342
- };
1343
- var $template = contentChildNodes;
1344
- if (transclude) {
1345
- var slots_1 = Object.create(null);
1346
- if (typeof transclude === 'object') {
1347
- $template = [];
1348
- var slotMap_1 = Object.create(null);
1349
- var filledSlots_1 = Object.create(null);
1350
- // Parse the element selectors.
1351
- Object.keys(transclude).forEach(function (slotName) {
1352
- var selector = transclude[slotName];
1353
- var optional = selector.charAt(0) === '?';
1354
- selector = optional ? selector.substring(1) : selector;
1355
- slotMap_1[selector] = slotName;
1356
- slots_1[slotName] = null; // `null`: Defined but not yet filled.
1357
- filledSlots_1[slotName] = optional; // Consider optional slots as filled.
1358
- });
1359
- // Add the matching elements into their slot.
1360
- contentChildNodes.forEach(function (node) {
1361
- var slotName = slotMap_1[directiveNormalize(node.nodeName.toLowerCase())];
1362
- if (slotName) {
1363
- filledSlots_1[slotName] = true;
1364
- slots_1[slotName] = slots_1[slotName] || [];
1365
- slots_1[slotName].push(node);
1366
- }
1367
- else {
1368
- $template.push(node);
1369
- }
1370
- });
1371
- // Check for required slots that were not filled.
1372
- Object.keys(filledSlots_1).forEach(function (slotName) {
1373
- if (!filledSlots_1[slotName]) {
1374
- throw new Error("Required transclusion slot '" + slotName + "' on directive: " + _this.name);
1375
- }
1376
- });
1377
- Object.keys(slots_1).filter(function (slotName) { return slots_1[slotName]; }).forEach(function (slotName) {
1378
- var nodes = slots_1[slotName];
1379
- slots_1[slotName] = function (scope, cloneAttach) {
1380
- return cloneAttach(nodes, scope);
1381
- };
1382
- });
1383
- }
1384
- // Attach `$$slots` to default slot transclude fn.
1385
- attachChildrenFn.$$slots = slots_1;
1386
- // AngularJS v1.6+ ignores empty or whitespace-only transcluded text nodes. But Angular
1387
- // removes all text content after the first interpolation and updates it later, after
1388
- // evaluating the expressions. This would result in AngularJS failing to recognize text
1389
- // nodes that start with an interpolation as transcluded content and use the fallback
1390
- // content instead.
1391
- // To avoid this issue, we add a
1392
- // [zero-width non-joiner character](https://en.wikipedia.org/wiki/Zero-width_non-joiner)
1393
- // to empty text nodes (which can only be a result of Angular removing their initial content).
1394
- // NOTE: Transcluded text content that starts with whitespace followed by an interpolation
1395
- // will still fail to be detected by AngularJS v1.6+
1396
- $template.forEach(function (node) {
1397
- if (node.nodeType === Node.TEXT_NODE && !node.nodeValue) {
1398
- node.nodeValue = '\u200C';
1399
- }
1400
- });
1401
- }
1402
- return attachChildrenFn;
1403
- };
1404
- UpgradeHelper.prototype.resolveAndBindRequiredControllers = function (controllerInstance) {
1405
- var directiveRequire = this.getDirectiveRequire();
1406
- var requiredControllers = this.resolveRequire(directiveRequire);
1407
- if (controllerInstance && this.directive.bindToController && isMap(directiveRequire)) {
1408
- var requiredControllersMap_1 = requiredControllers;
1409
- Object.keys(requiredControllersMap_1).forEach(function (key) {
1410
- controllerInstance[key] = requiredControllersMap_1[key];
1411
- });
1412
- }
1413
- return requiredControllers;
1414
- };
1415
- UpgradeHelper.prototype.compileHtml = function (html) {
1416
- this.element.innerHTML = html;
1417
- return this.$compile(this.element.childNodes);
1418
- };
1419
- UpgradeHelper.prototype.extractChildNodes = function () {
1420
- var childNodes = [];
1421
- var childNode;
1422
- while (childNode = this.element.firstChild) {
1423
- this.element.removeChild(childNode);
1424
- childNodes.push(childNode);
1425
- }
1426
- return childNodes;
1427
- };
1428
- UpgradeHelper.prototype.getDirectiveRequire = function () {
1429
- var require = this.directive.require || (this.directive.controller && this.directive.name);
1430
- if (isMap(require)) {
1431
- Object.keys(require).forEach(function (key) {
1432
- var value = require[key];
1433
- var match = value.match(REQUIRE_PREFIX_RE);
1434
- var name = value.substring(match[0].length);
1435
- if (!name) {
1436
- require[key] = match[0] + key;
1437
- }
1438
- });
1439
- }
1440
- return require;
1441
- };
1442
- UpgradeHelper.prototype.resolveRequire = function (require, controllerInstance) {
1443
- var _this = this;
1444
- if (!require) {
1445
- return null;
1446
- }
1447
- else if (Array.isArray(require)) {
1448
- return require.map(function (req) { return _this.resolveRequire(req); });
1449
- }
1450
- else if (typeof require === 'object') {
1451
- var value_1 = {};
1452
- Object.keys(require).forEach(function (key) { return value_1[key] = _this.resolveRequire(require[key]); });
1453
- return value_1;
1454
- }
1455
- else if (typeof require === 'string') {
1456
- var match = require.match(REQUIRE_PREFIX_RE);
1457
- var inheritType = match[1] || match[3];
1458
- var name = require.substring(match[0].length);
1459
- var isOptional = !!match[2];
1460
- var searchParents = !!inheritType;
1461
- var startOnParent = inheritType === '^^';
1462
- var ctrlKey = controllerKey(name);
1463
- var elem = startOnParent ? this.$element.parent() : this.$element;
1464
- var value = searchParents ? elem.inheritedData(ctrlKey) : elem.data(ctrlKey);
1465
- if (!value && !isOptional) {
1466
- throw new Error("Unable to find required '" + require + "' in upgraded directive '" + this.name + "'.");
1467
- }
1468
- return value;
1469
- }
1470
- else {
1471
- throw new Error("Unrecognized 'require' syntax on upgraded directive '" + this.name + "': " + require);
1472
- }
1473
- };
1474
- return UpgradeHelper;
1475
- }());
1476
- function getOrCall(property) {
1477
- var args = [];
1478
- for (var _i = 1; _i < arguments.length; _i++) {
1479
- args[_i - 1] = arguments[_i];
1480
- }
1481
- return isFunction(property) ? property.apply(void 0, __spreadArray([], __read(args), false)) : property;
1482
- }
1483
- // NOTE: Only works for `typeof T !== 'object'`.
1484
- function isMap(value) {
1485
- return value && !Array.isArray(value) && typeof value === 'object';
1486
- }
1487
- function notSupported(name, feature) {
1488
- throw new Error("Upgraded directive '" + name + "' contains unsupported feature: '" + feature + "'.");
1489
- }
1490
-
1491
- var CAMEL_CASE = /([A-Z])/g;
1492
- var INITIAL_VALUE$1 = {
1493
- __UNINITIALIZED__: true
1494
- };
1495
- var NOT_SUPPORTED = 'NOT_SUPPORTED';
1496
- var UpgradeNg1ComponentAdapterBuilder = /** @class */ (function () {
1497
- function UpgradeNg1ComponentAdapterBuilder(name) {
1498
- this.name = name;
1499
- this.inputs = [];
1500
- this.inputsRename = [];
1501
- this.outputs = [];
1502
- this.outputsRename = [];
1503
- this.propertyOutputs = [];
1504
- this.checkProperties = [];
1505
- this.propertyMap = {};
1506
- this.directive = null;
1507
- var selector = name.replace(CAMEL_CASE, function (all, next) { return '-' + next.toLowerCase(); });
1508
- var self = this;
1509
- // Note: There is a bug in TS 2.4 that prevents us from
1510
- // inlining this into @Directive
1511
- // TODO(tbosch): find or file a bug against TypeScript for this.
1512
- var directive = { selector: selector, inputs: this.inputsRename, outputs: this.outputsRename };
1513
- var MyClass = /** @class */ (function (_super) {
1514
- __extends(MyClass, _super);
1515
- function MyClass(scope, injector, elementRef) {
1516
- return _super.call(this, new UpgradeHelper(injector, name, elementRef, self.directive || undefined), scope, self.template, self.inputs, self.outputs, self.propertyOutputs, self.checkProperties, self.propertyMap) || this;
1517
- }
1518
- return MyClass;
1519
- }(UpgradeNg1ComponentAdapter));
1520
- MyClass.decorators = [
1521
- { type: core.Directive, args: [Object.assign({ jit: true }, directive),] }
1522
- ];
1523
- MyClass.ctorParameters = function () { return [
1524
- { type: undefined, decorators: [{ type: core.Inject, args: [$SCOPE,] }] },
1525
- { type: core.Injector },
1526
- { type: core.ElementRef }
1527
- ]; };
1528
- this.type = MyClass;
1529
- }
1530
- UpgradeNg1ComponentAdapterBuilder.prototype.extractBindings = function () {
1531
- var _this = this;
1532
- var btcIsObject = typeof this.directive.bindToController === 'object';
1533
- if (btcIsObject && Object.keys(this.directive.scope).length) {
1534
- throw new Error("Binding definitions on scope and controller at the same time are not supported.");
1535
- }
1536
- var context = (btcIsObject) ? this.directive.bindToController : this.directive.scope;
1537
- if (typeof context == 'object') {
1538
- Object.keys(context).forEach(function (propName) {
1539
- var definition = context[propName];
1540
- var bindingType = definition.charAt(0);
1541
- var bindingOptions = definition.charAt(1);
1542
- var attrName = definition.substring(bindingOptions === '?' ? 2 : 1) || propName;
1543
- // QUESTION: What about `=*`? Ignore? Throw? Support?
1544
- var inputName = "input_" + attrName;
1545
- var inputNameRename = inputName + ": " + attrName;
1546
- var outputName = "output_" + attrName;
1547
- var outputNameRename = outputName + ": " + attrName;
1548
- var outputNameRenameChange = outputNameRename + "Change";
1549
- switch (bindingType) {
1550
- case '@':
1551
- case '<':
1552
- _this.inputs.push(inputName);
1553
- _this.inputsRename.push(inputNameRename);
1554
- _this.propertyMap[inputName] = propName;
1555
- break;
1556
- case '=':
1557
- _this.inputs.push(inputName);
1558
- _this.inputsRename.push(inputNameRename);
1559
- _this.propertyMap[inputName] = propName;
1560
- _this.outputs.push(outputName);
1561
- _this.outputsRename.push(outputNameRenameChange);
1562
- _this.propertyMap[outputName] = propName;
1563
- _this.checkProperties.push(propName);
1564
- _this.propertyOutputs.push(outputName);
1565
- break;
1566
- case '&':
1567
- _this.outputs.push(outputName);
1568
- _this.outputsRename.push(outputNameRename);
1569
- _this.propertyMap[outputName] = propName;
1570
- break;
1571
- default:
1572
- var json = JSON.stringify(context);
1573
- throw new Error("Unexpected mapping '" + bindingType + "' in '" + json + "' in '" + _this.name + "' directive.");
1574
- }
1575
- });
1576
- }
1577
- };
1578
- /**
1579
- * Upgrade ng1 components into Angular.
1580
- */
1581
- UpgradeNg1ComponentAdapterBuilder.resolve = function (exportedComponents, $injector) {
1582
- var promises = Object.keys(exportedComponents).map(function (name) {
1583
- var exportedComponent = exportedComponents[name];
1584
- exportedComponent.directive = UpgradeHelper.getDirective($injector, name);
1585
- exportedComponent.extractBindings();
1586
- return Promise
1587
- .resolve(UpgradeHelper.getTemplate($injector, exportedComponent.directive, true))
1588
- .then(function (template) { return exportedComponent.template = template; });
1589
- });
1590
- return Promise.all(promises);
1591
- };
1592
- return UpgradeNg1ComponentAdapterBuilder;
1593
- }());
1594
- var UpgradeNg1ComponentAdapter = /** @class */ (function () {
1595
- function UpgradeNg1ComponentAdapter(helper, scope, template, inputs, outputs, propOuts, checkProperties, propertyMap) {
1596
- this.helper = helper;
1597
- this.template = template;
1598
- this.inputs = inputs;
1599
- this.outputs = outputs;
1600
- this.propOuts = propOuts;
1601
- this.checkProperties = checkProperties;
1602
- this.propertyMap = propertyMap;
1603
- this.controllerInstance = null;
1604
- this.destinationObj = null;
1605
- this.checkLastValues = [];
1606
- this.$element = null;
1607
- this.directive = helper.directive;
1608
- this.element = helper.element;
1609
- this.$element = helper.$element;
1610
- this.componentScope = scope.$new(!!this.directive.scope);
1611
- var controllerType = this.directive.controller;
1612
- if (this.directive.bindToController && controllerType) {
1613
- this.controllerInstance = this.helper.buildController(controllerType, this.componentScope);
1614
- this.destinationObj = this.controllerInstance;
1615
- }
1616
- else {
1617
- this.destinationObj = this.componentScope;
1618
- }
1619
- for (var i = 0; i < inputs.length; i++) {
1620
- this[inputs[i]] = null;
1621
- }
1622
- for (var j = 0; j < outputs.length; j++) {
1623
- var emitter = this[outputs[j]] = new core.EventEmitter();
1624
- if (this.propOuts.indexOf(outputs[j]) === -1) {
1625
- this.setComponentProperty(outputs[j], (function (emitter) { return function (value) { return emitter.emit(value); }; })(emitter));
1626
- }
1627
- }
1628
- for (var k = 0; k < propOuts.length; k++) {
1629
- this.checkLastValues.push(INITIAL_VALUE$1);
1630
- }
1631
- }
1632
- UpgradeNg1ComponentAdapter.prototype.ngOnInit = function () {
1633
- // Collect contents, insert and compile template
1634
- var attachChildNodes = this.helper.prepareTransclusion();
1635
- var linkFn = this.helper.compileTemplate(this.template);
1636
- // Instantiate controller (if not already done so)
1637
- var controllerType = this.directive.controller;
1638
- var bindToController = this.directive.bindToController;
1639
- if (controllerType && !bindToController) {
1640
- this.controllerInstance = this.helper.buildController(controllerType, this.componentScope);
1641
- }
1642
- // Require other controllers
1643
- var requiredControllers = this.helper.resolveAndBindRequiredControllers(this.controllerInstance);
1644
- // Hook: $onInit
1645
- if (this.controllerInstance && isFunction(this.controllerInstance.$onInit)) {
1646
- this.controllerInstance.$onInit();
1647
- }
1648
- // Linking
1649
- var link = this.directive.link;
1650
- var preLink = typeof link == 'object' && link.pre;
1651
- var postLink = typeof link == 'object' ? link.post : link;
1652
- var attrs = NOT_SUPPORTED;
1653
- var transcludeFn = NOT_SUPPORTED;
1654
- if (preLink) {
1655
- preLink(this.componentScope, this.$element, attrs, requiredControllers, transcludeFn);
1656
- }
1657
- linkFn(this.componentScope, null, { parentBoundTranscludeFn: attachChildNodes });
1658
- if (postLink) {
1659
- postLink(this.componentScope, this.$element, attrs, requiredControllers, transcludeFn);
1660
- }
1661
- // Hook: $postLink
1662
- if (this.controllerInstance && isFunction(this.controllerInstance.$postLink)) {
1663
- this.controllerInstance.$postLink();
1664
- }
1665
- };
1666
- UpgradeNg1ComponentAdapter.prototype.ngOnChanges = function (changes) {
1667
- var _this = this;
1668
- var ng1Changes = {};
1669
- Object.keys(changes).forEach(function (name) {
1670
- var change = changes[name];
1671
- _this.setComponentProperty(name, change.currentValue);
1672
- ng1Changes[_this.propertyMap[name]] = change;
1673
- });
1674
- if (isFunction(this.destinationObj.$onChanges)) {
1675
- this.destinationObj.$onChanges(ng1Changes);
1676
- }
1677
- };
1678
- UpgradeNg1ComponentAdapter.prototype.ngDoCheck = function () {
1679
- var _this = this;
1680
- var destinationObj = this.destinationObj;
1681
- var lastValues = this.checkLastValues;
1682
- var checkProperties = this.checkProperties;
1683
- var propOuts = this.propOuts;
1684
- checkProperties.forEach(function (propName, i) {
1685
- var value = destinationObj[propName];
1686
- var last = lastValues[i];
1687
- if (!strictEquals(last, value)) {
1688
- var eventEmitter = _this[propOuts[i]];
1689
- eventEmitter.emit(lastValues[i] = value);
1690
- }
1691
- });
1692
- if (this.controllerInstance && isFunction(this.controllerInstance.$doCheck)) {
1693
- this.controllerInstance.$doCheck();
1694
- }
1695
- };
1696
- UpgradeNg1ComponentAdapter.prototype.ngOnDestroy = function () {
1697
- this.helper.onDestroy(this.componentScope, this.controllerInstance);
1698
- };
1699
- UpgradeNg1ComponentAdapter.prototype.setComponentProperty = function (name, value) {
1700
- this.destinationObj[this.propertyMap[name]] = value;
1701
- };
1702
- return UpgradeNg1ComponentAdapter;
1703
- }());
1704
- UpgradeNg1ComponentAdapter.decorators = [
1705
- { type: core.Directive }
1706
- ];
1707
- UpgradeNg1ComponentAdapter.ctorParameters = function () { return [
1708
- { type: UpgradeHelper },
1709
- { type: undefined },
1710
- { type: String },
1711
- { type: Array },
1712
- { type: Array },
1713
- { type: Array },
1714
- { type: Array },
1715
- { type: undefined }
1716
- ]; };
1717
-
1718
- var upgradeCount = 0;
1719
- /**
1720
- * Use `UpgradeAdapter` to allow AngularJS and Angular to coexist in a single application.
1721
- *
1722
- * The `UpgradeAdapter` allows:
1723
- * 1. creation of Angular component from AngularJS component directive
1724
- * (See [UpgradeAdapter#upgradeNg1Component()])
1725
- * 2. creation of AngularJS directive from Angular component.
1726
- * (See [UpgradeAdapter#downgradeNg2Component()])
1727
- * 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks
1728
- * coexisting in a single application.
1729
- *
1730
- * @usageNotes
1731
- * ### Mental Model
1732
- *
1733
- * When reasoning about how a hybrid application works it is useful to have a mental model which
1734
- * describes what is happening and explains what is happening at the lowest level.
1735
- *
1736
- * 1. There are two independent frameworks running in a single application, each framework treats
1737
- * the other as a black box.
1738
- * 2. Each DOM element on the page is owned exactly by one framework. Whichever framework
1739
- * instantiated the element is the owner. Each framework only updates/interacts with its own
1740
- * DOM elements and ignores others.
1741
- * 3. AngularJS directives always execute inside AngularJS framework codebase regardless of
1742
- * where they are instantiated.
1743
- * 4. Angular components always execute inside Angular framework codebase regardless of
1744
- * where they are instantiated.
1745
- * 5. An AngularJS component can be upgraded to an Angular component. This creates an
1746
- * Angular directive, which bootstraps the AngularJS component directive in that location.
1747
- * 6. An Angular component can be downgraded to an AngularJS component directive. This creates
1748
- * an AngularJS directive, which bootstraps the Angular component in that location.
1749
- * 7. Whenever an adapter component is instantiated the host element is owned by the framework
1750
- * doing the instantiation. The other framework then instantiates and owns the view for that
1751
- * component. This implies that component bindings will always follow the semantics of the
1752
- * instantiation framework. The syntax is always that of Angular syntax.
1753
- * 8. AngularJS is always bootstrapped first and owns the bottom most view.
1754
- * 9. The new application is running in Angular zone, and therefore it no longer needs calls to
1755
- * `$apply()`.
1756
- *
1757
- * ### Example
1758
- *
1759
- * ```
1760
- * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module), myCompilerOptions);
1761
- * const module = angular.module('myExample', []);
1762
- * module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component));
1763
- *
1764
- * module.directive('ng1Hello', function() {
1765
- * return {
1766
- * scope: { title: '=' },
1767
- * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
1768
- * };
1769
- * });
1770
- *
1771
- *
1772
- * @Component({
1773
- * selector: 'ng2-comp',
1774
- * inputs: ['name'],
1775
- * template: 'ng2[<ng1-hello [title]="name">transclude</ng1-hello>](<ng-content></ng-content>)',
1776
- * directives:
1777
- * })
1778
- * class Ng2Component {
1779
- * }
1780
- *
1781
- * @NgModule({
1782
- * declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')],
1783
- * imports: [BrowserModule]
1784
- * })
1785
- * class MyNg2Module {}
1786
- *
1787
- *
1788
- * document.body.innerHTML = '<ng2-comp name="World">project</ng2-comp>';
1789
- *
1790
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
1791
- * expect(document.body.textContent).toEqual(
1792
- * "ng2[ng1[Hello World!](transclude)](project)");
1793
- * });
1794
- *
1795
- * ```
1796
- *
1797
- * @deprecated Deprecated since v5. Use `upgrade/static` instead, which also supports
1798
- * [Ahead-of-Time compilation](guide/aot-compiler).
1799
- * @publicApi
1800
- */
1801
- var UpgradeAdapter = /** @class */ (function () {
1802
- function UpgradeAdapter(ng2AppModule, compilerOptions) {
1803
- this.ng2AppModule = ng2AppModule;
1804
- this.compilerOptions = compilerOptions;
1805
- this.idPrefix = "NG2_UPGRADE_" + upgradeCount++ + "_";
1806
- this.downgradedComponents = [];
1807
- /**
1808
- * An internal map of ng1 components which need to up upgraded to ng2.
1809
- *
1810
- * We can't upgrade until injector is instantiated and we can retrieve the component metadata.
1811
- * For this reason we keep a list of components to upgrade until ng1 injector is bootstrapped.
1812
- *
1813
- * @internal
1814
- */
1815
- this.ng1ComponentsToBeUpgraded = {};
1816
- this.upgradedProviders = [];
1817
- this.moduleRef = null;
1818
- if (!ng2AppModule) {
1819
- throw new Error('UpgradeAdapter cannot be instantiated without an NgModule of the Angular app.');
1820
- }
1821
- }
1822
- /**
1823
- * Allows Angular Component to be used from AngularJS.
1824
- *
1825
- * Use `downgradeNg2Component` to create an AngularJS Directive Definition Factory from
1826
- * Angular Component. The adapter will bootstrap Angular component from within the
1827
- * AngularJS template.
1828
- *
1829
- * @usageNotes
1830
- * ### Mental Model
1831
- *
1832
- * 1. The component is instantiated by being listed in AngularJS template. This means that the
1833
- * host element is controlled by AngularJS, but the component's view will be controlled by
1834
- * Angular.
1835
- * 2. Even thought the component is instantiated in AngularJS, it will be using Angular
1836
- * syntax. This has to be done, this way because we must follow Angular components do not
1837
- * declare how the attributes should be interpreted.
1838
- * 3. `ng-model` is controlled by AngularJS and communicates with the downgraded Angular component
1839
- * by way of the `ControlValueAccessor` interface from @angular/forms. Only components that
1840
- * implement this interface are eligible.
1841
- *
1842
- * ### Supported Features
1843
- *
1844
- * - Bindings:
1845
- * - Attribute: `<comp name="World">`
1846
- * - Interpolation: `<comp greeting="Hello {{name}}!">`
1847
- * - Expression: `<comp [name]="username">`
1848
- * - Event: `<comp (close)="doSomething()">`
1849
- * - ng-model: `<comp ng-model="name">`
1850
- * - Content projection: yes
1851
- *
1852
- * ### Example
1853
- *
1854
- * ```
1855
- * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
1856
- * const module = angular.module('myExample', []);
1857
- * module.directive('greet', adapter.downgradeNg2Component(Greeter));
1858
- *
1859
- * @Component({
1860
- * selector: 'greet',
1861
- * template: '{{salutation}} {{name}}! - <ng-content></ng-content>'
1862
- * })
1863
- * class Greeter {
1864
- * @Input() salutation: string;
1865
- * @Input() name: string;
1866
- * }
1867
- *
1868
- * @NgModule({
1869
- * declarations: [Greeter],
1870
- * imports: [BrowserModule]
1871
- * })
1872
- * class MyNg2Module {}
1873
- *
1874
- * document.body.innerHTML =
1875
- * 'ng1 template: <greet salutation="Hello" [name]="world">text</greet>';
1876
- *
1877
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
1878
- * expect(document.body.textContent).toEqual("ng1 template: Hello world! - text");
1879
- * });
1880
- * ```
1881
- */
1882
- UpgradeAdapter.prototype.downgradeNg2Component = function (component) {
1883
- this.downgradedComponents.push(component);
1884
- return downgradeComponent({ component: component });
1885
- };
1886
- /**
1887
- * Allows AngularJS Component to be used from Angular.
1888
- *
1889
- * Use `upgradeNg1Component` to create an Angular component from AngularJS Component
1890
- * directive. The adapter will bootstrap AngularJS component from within the Angular
1891
- * template.
1892
- *
1893
- * @usageNotes
1894
- * ### Mental Model
1895
- *
1896
- * 1. The component is instantiated by being listed in Angular template. This means that the
1897
- * host element is controlled by Angular, but the component's view will be controlled by
1898
- * AngularJS.
1899
- *
1900
- * ### Supported Features
1901
- *
1902
- * - Bindings:
1903
- * - Attribute: `<comp name="World">`
1904
- * - Interpolation: `<comp greeting="Hello {{name}}!">`
1905
- * - Expression: `<comp [name]="username">`
1906
- * - Event: `<comp (close)="doSomething()">`
1907
- * - Transclusion: yes
1908
- * - Only some of the features of
1909
- * [Directive Definition Object](https://docs.angularjs.org/api/ng/service/$compile) are
1910
- * supported:
1911
- * - `compile`: not supported because the host element is owned by Angular, which does
1912
- * not allow modifying DOM structure during compilation.
1913
- * - `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.)
1914
- * - `controllerAs`: supported.
1915
- * - `bindToController`: supported.
1916
- * - `link`: supported. (NOTE: only pre-link function is supported.)
1917
- * - `name`: supported.
1918
- * - `priority`: ignored.
1919
- * - `replace`: not supported.
1920
- * - `require`: supported.
1921
- * - `restrict`: must be set to 'E'.
1922
- * - `scope`: supported.
1923
- * - `template`: supported.
1924
- * - `templateUrl`: supported.
1925
- * - `terminal`: ignored.
1926
- * - `transclude`: supported.
1927
- *
1928
- *
1929
- * ### Example
1930
- *
1931
- * ```
1932
- * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
1933
- * const module = angular.module('myExample', []);
1934
- *
1935
- * module.directive('greet', function() {
1936
- * return {
1937
- * scope: {salutation: '=', name: '=' },
1938
- * template: '{{salutation}} {{name}}! - <span ng-transclude></span>'
1939
- * };
1940
- * });
1941
- *
1942
- * module.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
1943
- *
1944
- * @Component({
1945
- * selector: 'ng2',
1946
- * template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>'
1947
- * })
1948
- * class Ng2Component {
1949
- * }
1950
- *
1951
- * @NgModule({
1952
- * declarations: [Ng2Component, adapter.upgradeNg1Component('greet')],
1953
- * imports: [BrowserModule]
1954
- * })
1955
- * class MyNg2Module {}
1956
- *
1957
- * document.body.innerHTML = '<ng2></ng2>';
1958
- *
1959
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
1960
- * expect(document.body.textContent).toEqual("ng2 template: Hello world! - text");
1961
- * });
1962
- * ```
1963
- */
1964
- UpgradeAdapter.prototype.upgradeNg1Component = function (name) {
1965
- if (this.ng1ComponentsToBeUpgraded.hasOwnProperty(name)) {
1966
- return this.ng1ComponentsToBeUpgraded[name].type;
1967
- }
1968
- else {
1969
- return (this.ng1ComponentsToBeUpgraded[name] = new UpgradeNg1ComponentAdapterBuilder(name))
1970
- .type;
1971
- }
1972
- };
1973
- /**
1974
- * Registers the adapter's AngularJS upgrade module for unit testing in AngularJS.
1975
- * Use this instead of `angular.mock.module()` to load the upgrade module into
1976
- * the AngularJS testing injector.
1977
- *
1978
- * @usageNotes
1979
- * ### Example
1980
- *
1981
- * ```
1982
- * const upgradeAdapter = new UpgradeAdapter(MyNg2Module);
1983
- *
1984
- * // configure the adapter with upgrade/downgrade components and services
1985
- * upgradeAdapter.downgradeNg2Component(MyComponent);
1986
- *
1987
- * let upgradeAdapterRef: UpgradeAdapterRef;
1988
- * let $compile, $rootScope;
1989
- *
1990
- * // We must register the adapter before any calls to `inject()`
1991
- * beforeEach(() => {
1992
- * upgradeAdapterRef = upgradeAdapter.registerForNg1Tests(['heroApp']);
1993
- * });
1994
- *
1995
- * beforeEach(inject((_$compile_, _$rootScope_) => {
1996
- * $compile = _$compile_;
1997
- * $rootScope = _$rootScope_;
1998
- * }));
1999
- *
2000
- * it("says hello", (done) => {
2001
- * upgradeAdapterRef.ready(() => {
2002
- * const element = $compile("<my-component></my-component>")($rootScope);
2003
- * $rootScope.$apply();
2004
- * expect(element.html()).toContain("Hello World");
2005
- * done();
2006
- * })
2007
- * });
2008
- *
2009
- * ```
2010
- *
2011
- * @param modules any AngularJS modules that the upgrade module should depend upon
2012
- * @returns an `UpgradeAdapterRef`, which lets you register a `ready()` callback to
2013
- * run assertions once the Angular components are ready to test through AngularJS.
2014
- */
2015
- UpgradeAdapter.prototype.registerForNg1Tests = function (modules) {
2016
- var _this = this;
2017
- var windowNgMock = window['angular'].mock;
2018
- if (!windowNgMock || !windowNgMock.module) {
2019
- throw new Error('Failed to find \'angular.mock.module\'.');
2020
- }
2021
- this.declareNg1Module(modules);
2022
- windowNgMock.module(this.ng1Module.name);
2023
- var upgrade = new UpgradeAdapterRef();
2024
- this.ng2BootstrapDeferred.promise.then(function (ng1Injector) {
2025
- upgrade._bootstrapDone(_this.moduleRef, ng1Injector);
2026
- }, onError);
2027
- return upgrade;
2028
- };
2029
- /**
2030
- * Bootstrap a hybrid AngularJS / Angular application.
2031
- *
2032
- * This `bootstrap` method is a direct replacement (takes same arguments) for AngularJS
2033
- * [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike
2034
- * AngularJS, this bootstrap is asynchronous.
2035
- *
2036
- * @usageNotes
2037
- * ### Example
2038
- *
2039
- * ```
2040
- * const adapter = new UpgradeAdapter(MyNg2Module);
2041
- * const module = angular.module('myExample', []);
2042
- * module.directive('ng2', adapter.downgradeNg2Component(Ng2));
2043
- *
2044
- * module.directive('ng1', function() {
2045
- * return {
2046
- * scope: { title: '=' },
2047
- * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
2048
- * };
2049
- * });
2050
- *
2051
- *
2052
- * @Component({
2053
- * selector: 'ng2',
2054
- * inputs: ['name'],
2055
- * template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)'
2056
- * })
2057
- * class Ng2 {
2058
- * }
2059
- *
2060
- * @NgModule({
2061
- * declarations: [Ng2, adapter.upgradeNg1Component('ng1')],
2062
- * imports: [BrowserModule]
2063
- * })
2064
- * class MyNg2Module {}
2065
- *
2066
- * document.body.innerHTML = '<ng2 name="World">project</ng2>';
2067
- *
2068
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
2069
- * expect(document.body.textContent).toEqual(
2070
- * "ng2[ng1[Hello World!](transclude)](project)");
2071
- * });
2072
- * ```
2073
- */
2074
- UpgradeAdapter.prototype.bootstrap = function (element$1, modules, config) {
2075
- var _this = this;
2076
- this.declareNg1Module(modules);
2077
- var upgrade = new UpgradeAdapterRef();
2078
- // Make sure resumeBootstrap() only exists if the current bootstrap is deferred
2079
- var windowAngular = window /** TODO #???? */['angular'];
2080
- windowAngular.resumeBootstrap = undefined;
2081
- this.ngZone.run(function () {
2082
- bootstrap(element$1, [_this.ng1Module.name], config);
2083
- });
2084
- var ng1BootstrapPromise = new Promise(function (resolve) {
2085
- if (windowAngular.resumeBootstrap) {
2086
- var originalResumeBootstrap_1 = windowAngular.resumeBootstrap;
2087
- windowAngular.resumeBootstrap = function () {
2088
- windowAngular.resumeBootstrap = originalResumeBootstrap_1;
2089
- var r = windowAngular.resumeBootstrap.apply(this, arguments);
2090
- resolve();
2091
- return r;
2092
- };
2093
- }
2094
- else {
2095
- resolve();
2096
- }
2097
- });
2098
- Promise.all([this.ng2BootstrapDeferred.promise, ng1BootstrapPromise]).then(function (_a) {
2099
- var _b = __read(_a, 1), ng1Injector = _b[0];
2100
- element(element$1).data(controllerKey(INJECTOR_KEY), _this.moduleRef.injector);
2101
- _this.moduleRef.injector.get(core.NgZone).run(function () {
2102
- upgrade._bootstrapDone(_this.moduleRef, ng1Injector);
2103
- });
2104
- }, onError);
2105
- return upgrade;
2106
- };
2107
- /**
2108
- * Allows AngularJS service to be accessible from Angular.
2109
- *
2110
- * @usageNotes
2111
- * ### Example
2112
- *
2113
- * ```
2114
- * class Login { ... }
2115
- * class Server { ... }
2116
- *
2117
- * @Injectable()
2118
- * class Example {
2119
- * constructor(@Inject('server') server, login: Login) {
2120
- * ...
2121
- * }
2122
- * }
2123
- *
2124
- * const module = angular.module('myExample', []);
2125
- * module.service('server', Server);
2126
- * module.service('login', Login);
2127
- *
2128
- * const adapter = new UpgradeAdapter(MyNg2Module);
2129
- * adapter.upgradeNg1Provider('server');
2130
- * adapter.upgradeNg1Provider('login', {asToken: Login});
2131
- *
2132
- * adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
2133
- * const example: Example = ref.ng2Injector.get(Example);
2134
- * });
2135
- *
2136
- * ```
2137
- */
2138
- UpgradeAdapter.prototype.upgradeNg1Provider = function (name, options) {
2139
- var token = options && options.asToken || name;
2140
- this.upgradedProviders.push({
2141
- provide: token,
2142
- useFactory: function ($injector) { return $injector.get(name); },
2143
- deps: [$INJECTOR]
2144
- });
2145
- };
2146
- /**
2147
- * Allows Angular service to be accessible from AngularJS.
2148
- *
2149
- * @usageNotes
2150
- * ### Example
2151
- *
2152
- * ```
2153
- * class Example {
2154
- * }
2155
- *
2156
- * const adapter = new UpgradeAdapter(MyNg2Module);
2157
- *
2158
- * const module = angular.module('myExample', []);
2159
- * module.factory('example', adapter.downgradeNg2Provider(Example));
2160
- *
2161
- * adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
2162
- * const example: Example = ref.ng1Injector.get('example');
2163
- * });
2164
- *
2165
- * ```
2166
- */
2167
- UpgradeAdapter.prototype.downgradeNg2Provider = function (token) {
2168
- return downgradeInjectable(token);
2169
- };
2170
- /**
2171
- * Declare the AngularJS upgrade module for this adapter without bootstrapping the whole
2172
- * hybrid application.
2173
- *
2174
- * This method is automatically called by `bootstrap()` and `registerForNg1Tests()`.
2175
- *
2176
- * @param modules The AngularJS modules that this upgrade module should depend upon.
2177
- * @returns The AngularJS upgrade module that is declared by this method
2178
- *
2179
- * @usageNotes
2180
- * ### Example
2181
- *
2182
- * ```
2183
- * const upgradeAdapter = new UpgradeAdapter(MyNg2Module);
2184
- * upgradeAdapter.declareNg1Module(['heroApp']);
2185
- * ```
2186
- */
2187
- UpgradeAdapter.prototype.declareNg1Module = function (modules) {
2188
- var _this = this;
2189
- if (modules === void 0) { modules = []; }
2190
- var delayApplyExps = [];
2191
- var original$applyFn;
2192
- var rootScopePrototype;
2193
- var upgradeAdapter = this;
2194
- var ng1Module = this.ng1Module = module_(this.idPrefix, modules);
2195
- var platformRef = platformBrowserDynamic.platformBrowserDynamic();
2196
- this.ngZone = new core.NgZone({ enableLongStackTrace: Zone.hasOwnProperty('longStackTraceZoneSpec') });
2197
- this.ng2BootstrapDeferred = new Deferred();
2198
- ng1Module.constant(UPGRADE_APP_TYPE_KEY, 1 /* Dynamic */)
2199
- .factory(INJECTOR_KEY, function () { return _this.moduleRef.injector.get(core.Injector); })
2200
- .factory(LAZY_MODULE_REF, [INJECTOR_KEY, function (injector) { return ({ injector: injector }); }])
2201
- .constant(NG_ZONE_KEY, this.ngZone)
2202
- .factory(COMPILER_KEY, function () { return _this.moduleRef.injector.get(core.Compiler); })
2203
- .config([
2204
- '$provide', '$injector',
2205
- function (provide, ng1Injector) {
2206
- provide.decorator($ROOT_SCOPE, [
2207
- '$delegate',
2208
- function (rootScopeDelegate) {
2209
- // Capture the root apply so that we can delay first call to $apply until we
2210
- // bootstrap Angular and then we replay and restore the $apply.
2211
- rootScopePrototype = rootScopeDelegate.constructor.prototype;
2212
- if (rootScopePrototype.hasOwnProperty('$apply')) {
2213
- original$applyFn = rootScopePrototype.$apply;
2214
- rootScopePrototype.$apply = function (exp) { return delayApplyExps.push(exp); };
2215
- }
2216
- else {
2217
- throw new Error('Failed to find \'$apply\' on \'$rootScope\'!');
2218
- }
2219
- return rootScopeDelegate;
2220
- }
2221
- ]);
2222
- if (ng1Injector.has($$TESTABILITY)) {
2223
- provide.decorator($$TESTABILITY, [
2224
- '$delegate',
2225
- function (testabilityDelegate) {
2226
- var originalWhenStable = testabilityDelegate.whenStable;
2227
- // Cannot use arrow function below because we need the context
2228
- var newWhenStable = function (callback) {
2229
- originalWhenStable.call(this, function () {
2230
- var ng2Testability = upgradeAdapter.moduleRef.injector.get(core.Testability);
2231
- if (ng2Testability.isStable()) {
2232
- callback.apply(this, arguments);
2233
- }
2234
- else {
2235
- ng2Testability.whenStable(newWhenStable.bind(this, callback));
2236
- }
2237
- });
2238
- };
2239
- testabilityDelegate.whenStable = newWhenStable;
2240
- return testabilityDelegate;
2241
- }
2242
- ]);
2243
- }
2244
- }
2245
- ]);
2246
- ng1Module.run([
2247
- '$injector', '$rootScope',
2248
- function (ng1Injector, rootScope) {
2249
- UpgradeNg1ComponentAdapterBuilder.resolve(_this.ng1ComponentsToBeUpgraded, ng1Injector)
2250
- .then(function () {
2251
- // Note: There is a bug in TS 2.4 that prevents us from
2252
- // inlining this into @NgModule
2253
- // TODO(tbosch): find or file a bug against TypeScript for this.
2254
- var ngModule = {
2255
- providers: [
2256
- { provide: $INJECTOR, useFactory: function () { return ng1Injector; } },
2257
- { provide: $COMPILE, useFactory: function () { return ng1Injector.get($COMPILE); } },
2258
- _this.upgradedProviders
2259
- ],
2260
- imports: [core.resolveForwardRef(_this.ng2AppModule)],
2261
- entryComponents: _this.downgradedComponents
2262
- };
2263
- // At this point we have ng1 injector and we have prepared
2264
- // ng1 components to be upgraded, we now can bootstrap ng2.
2265
- var DynamicNgUpgradeModule = /** @class */ (function () {
2266
- function DynamicNgUpgradeModule() {
2267
- }
2268
- DynamicNgUpgradeModule.prototype.ngDoBootstrap = function () { };
2269
- return DynamicNgUpgradeModule;
2270
- }());
2271
- DynamicNgUpgradeModule.decorators = [
2272
- { type: core.NgModule, args: [Object.assign({ jit: true }, ngModule),] }
2273
- ];
2274
- DynamicNgUpgradeModule.ctorParameters = function () { return []; };
2275
- platformRef
2276
- .bootstrapModule(DynamicNgUpgradeModule, [_this.compilerOptions, { ngZone: _this.ngZone }])
2277
- .then(function (ref) {
2278
- _this.moduleRef = ref;
2279
- _this.ngZone.run(function () {
2280
- if (rootScopePrototype) {
2281
- rootScopePrototype.$apply = original$applyFn; // restore original $apply
2282
- while (delayApplyExps.length) {
2283
- rootScope.$apply(delayApplyExps.shift());
2284
- }
2285
- rootScopePrototype = null;
2286
- }
2287
- });
2288
- })
2289
- .then(function () { return _this.ng2BootstrapDeferred.resolve(ng1Injector); }, onError)
2290
- .then(function () {
2291
- var subscription = _this.ngZone.onMicrotaskEmpty.subscribe({
2292
- next: function () {
2293
- if (rootScope.$$phase) {
2294
- if (core.isDevMode()) {
2295
- console.warn('A digest was triggered while one was already in progress. This may mean that something is triggering digests outside the Angular zone.');
2296
- }
2297
- return rootScope.$evalAsync(function () { });
2298
- }
2299
- return rootScope.$digest();
2300
- }
2301
- });
2302
- rootScope.$on('$destroy', function () {
2303
- subscription.unsubscribe();
2304
- });
2305
- // Destroy the AngularJS app once the Angular `PlatformRef` is destroyed.
2306
- // This does not happen in a typical SPA scenario, but it might be useful for
2307
- // other use-cases where disposing of an Angular/AngularJS app is necessary
2308
- // (such as Hot Module Replacement (HMR)).
2309
- // See https://github.com/angular/angular/issues/39935.
2310
- platformRef.onDestroy(function () { return destroyApp(ng1Injector); });
2311
- });
2312
- })
2313
- .catch(function (e) { return _this.ng2BootstrapDeferred.reject(e); });
2314
- }
2315
- ]);
2316
- return ng1Module;
2317
- };
2318
- return UpgradeAdapter;
2319
- }());
2320
- /**
2321
- * Synchronous promise-like object to wrap parent injectors,
2322
- * to preserve the synchronous nature of AngularJS's $compile.
2323
- */
2324
- var ParentInjectorPromise$1 = /** @class */ (function () {
2325
- function ParentInjectorPromise(element) {
2326
- this.element = element;
2327
- this.callbacks = [];
2328
- // store the promise on the element
2329
- element.data(controllerKey(INJECTOR_KEY), this);
2330
- }
2331
- ParentInjectorPromise.prototype.then = function (callback) {
2332
- if (this.injector) {
2333
- callback(this.injector);
2334
- }
2335
- else {
2336
- this.callbacks.push(callback);
2337
- }
2338
- };
2339
- ParentInjectorPromise.prototype.resolve = function (injector) {
2340
- this.injector = injector;
2341
- // reset the element data to point to the real injector
2342
- this.element.data(controllerKey(INJECTOR_KEY), injector);
2343
- // clean out the element to prevent memory leaks
2344
- this.element = null;
2345
- // run all the queued callbacks
2346
- this.callbacks.forEach(function (callback) { return callback(injector); });
2347
- this.callbacks.length = 0;
2348
- };
2349
- return ParentInjectorPromise;
2350
- }());
2351
- /**
2352
- * Use `UpgradeAdapterRef` to control a hybrid AngularJS / Angular application.
2353
- *
2354
- * @deprecated Deprecated since v5. Use `upgrade/static` instead, which also supports
2355
- * [Ahead-of-Time compilation](guide/aot-compiler).
2356
- * @publicApi
2357
- */
2358
- var UpgradeAdapterRef = /** @class */ (function () {
2359
- function UpgradeAdapterRef() {
2360
- /* @internal */
2361
- this._readyFn = null;
2362
- this.ng1RootScope = null;
2363
- this.ng1Injector = null;
2364
- this.ng2ModuleRef = null;
2365
- this.ng2Injector = null;
2366
- }
2367
- /* @internal */
2368
- UpgradeAdapterRef.prototype._bootstrapDone = function (ngModuleRef, ng1Injector) {
2369
- this.ng2ModuleRef = ngModuleRef;
2370
- this.ng2Injector = ngModuleRef.injector;
2371
- this.ng1Injector = ng1Injector;
2372
- this.ng1RootScope = ng1Injector.get($ROOT_SCOPE);
2373
- this._readyFn && this._readyFn(this);
2374
- };
2375
- /**
2376
- * Register a callback function which is notified upon successful hybrid AngularJS / Angular
2377
- * application has been bootstrapped.
2378
- *
2379
- * The `ready` callback function is invoked inside the Angular zone, therefore it does not
2380
- * require a call to `$apply()`.
2381
- */
2382
- UpgradeAdapterRef.prototype.ready = function (fn) {
2383
- this._readyFn = fn;
2384
- };
2385
- /**
2386
- * Dispose of running hybrid AngularJS / Angular application.
2387
- */
2388
- UpgradeAdapterRef.prototype.dispose = function () {
2389
- this.ng1Injector.get($ROOT_SCOPE).$destroy();
2390
- this.ng2ModuleRef.destroy();
2391
- };
2392
- return UpgradeAdapterRef;
2393
- }());
2394
-
2395
- /**
2396
- * @license
2397
- * Copyright Google LLC All Rights Reserved.
2398
- *
2399
- * Use of this source code is governed by an MIT-style license that can be
2400
- * found in the LICENSE file at https://angular.io/license
2401
- */
2402
- // This file only re-exports content of the `src` folder. Keep it that way.
2403
-
2404
- /**
2405
- * @license
2406
- * Copyright Google LLC All Rights Reserved.
2407
- *
2408
- * Use of this source code is governed by an MIT-style license that can be
2409
- * found in the LICENSE file at https://angular.io/license
2410
- */
2411
-
2412
- /**
2413
- * Generated bundle index. Do not edit.
2414
- */
2415
-
2416
- exports.UpgradeAdapter = UpgradeAdapter;
2417
- exports.UpgradeAdapterRef = UpgradeAdapterRef;
2418
- exports.VERSION = VERSION;
2419
-
2420
- Object.defineProperty(exports, '__esModule', { value: true });
2421
-
2422
- })));
2423
- //# sourceMappingURL=upgrade.umd.js.map