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