_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts_0_1765 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export const STATUS = {
CONTINUE: 100,
SWITCHING_PROTOCOLS: 101,
OK: 200,
CREATED: 201,
ACCEPTED: 202,
NON_AUTHORITATIVE_INFORMATION: 203,
NO_CONTENT: 204,
RESET_CONTENT: 205,
PARTIAL_CONTENT: 206,
MULTIPLE_CHOICES: 300,
MOVED_PERMANTENTLY: 301,
FOUND: 302,
SEE_OTHER: 303,
NOT_MODIFIED: 304,
USE_PROXY: 305,
TEMPORARY_REDIRECT: 307,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
PAYMENT_REQUIRED: 402,
FORBIDDEN: 403,
NOT_FOUND: 404,
METHOD_NOT_ALLOWED: 405,
NOT_ACCEPTABLE: 406,
PROXY_AUTHENTICATION_REQUIRED: 407,
REQUEST_TIMEOUT: 408,
CONFLICT: 409,
GONE: 410,
LENGTH_REQUIRED: 411,
PRECONDITION_FAILED: 412,
PAYLOAD_TO_LARGE: 413,
URI_TOO_LONG: 414,
UNSUPPORTED_MEDIA_TYPE: 415,
RANGE_NOT_SATISFIABLE: 416,
EXPECTATION_FAILED: 417,
IM_A_TEAPOT: 418,
UPGRADE_REQUIRED: 426,
INTERNAL_SERVER_ERROR: 500,
NOT_IMPLEMENTED: 501,
BAD_GATEWAY: 502,
SERVICE_UNAVAILABLE: 503,
GATEWAY_TIMEOUT: 504,
HTTP_VERSION_NOT_SUPPORTED: 505,
PROCESSING: 102,
MULTI_STATUS: 207,
IM_USED: 226,
PERMANENT_REDIRECT: 308,
UNPROCESSABLE_ENTRY: 422,
LOCKED: 423,
FAILED_DEPENDENCY: 424,
PRECONDITION_REQUIRED: 428,
TOO_MANY_REQUESTS: 429,
REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
UNAVAILABLE_FOR_LEGAL_REASONS: 451,
VARIANT_ALSO_NEGOTIATES: 506,
INSUFFICIENT_STORAGE: 507,
NETWORK_AUTHENTICATION_REQUIRED: 511,
};
export const STATUS_CODE_INFO: {
[key: string]: {
code: number;
text: string;
description: string;
spec_title: string;
spec_href: string;
};
} = | {
"end_byte": 1765,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts_1766_8526 | {
'100': {
'code': 100,
'text': 'Continue',
'description':
'"The initial part of a request has been received and has not yet been rejected by the server."',
'spec_title': 'RFC7231#6.2.1',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.2.1',
},
'101': {
'code': 101,
'text': 'Switching Protocols',
'description':
'"The server understands and is willing to comply with the client\'s request, via the Upgrade header field, for a change in the application protocol being used on this connection."',
'spec_title': 'RFC7231#6.2.2',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.2.2',
},
'200': {
'code': 200,
'text': 'OK',
'description': '"The request has succeeded."',
'spec_title': 'RFC7231#6.3.1',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.1',
},
'201': {
'code': 201,
'text': 'Created',
'description':
'"The request has been fulfilled and has resulted in one or more new resources being created."',
'spec_title': 'RFC7231#6.3.2',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.2',
},
'202': {
'code': 202,
'text': 'Accepted',
'description':
'"The request has been accepted for processing, but the processing has not been completed."',
'spec_title': 'RFC7231#6.3.3',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.3',
},
'203': {
'code': 203,
'text': 'Non-Authoritative Information',
'description':
'"The request was successful but the enclosed payload has been modified from that of the origin server\'s 200 (OK) response by a transforming proxy."',
'spec_title': 'RFC7231#6.3.4',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.4',
},
'204': {
'code': 204,
'text': 'No Content',
'description':
'"The server has successfully fulfilled the request and that there is no additional content to send in the response payload body."',
'spec_title': 'RFC7231#6.3.5',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.5',
},
'205': {
'code': 205,
'text': 'Reset Content',
'description':
'"The server has fulfilled the request and desires that the user agent reset the "document view", which caused the request to be sent, to its original state as received from the origin server."',
'spec_title': 'RFC7231#6.3.6',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.6',
},
'206': {
'code': 206,
'text': 'Partial Content',
'description':
'"The server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation that correspond to the satisfiable ranges found in the requests\'s Range header field."',
'spec_title': 'RFC7233#4.1',
'spec_href': 'https://tools.ietf.org/html/rfc7233#section-4.1',
},
'300': {
'code': 300,
'text': 'Multiple Choices',
'description':
'"The target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers."',
'spec_title': 'RFC7231#6.4.1',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.1',
},
'301': {
'code': 301,
'text': 'Moved Permanently',
'description':
'"The target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs."',
'spec_title': 'RFC7231#6.4.2',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.2',
},
'302': {
'code': 302,
'text': 'Found',
'description': '"The target resource resides temporarily under a different URI."',
'spec_title': 'RFC7231#6.4.3',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.3',
},
'303': {
'code': 303,
'text': 'See Other',
'description':
'"The server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, that is intended to provide an indirect response to the original request."',
'spec_title': 'RFC7231#6.4.4',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.4',
},
'304': {
'code': 304,
'text': 'Not Modified',
'description':
'"A conditional GET request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition has evaluated to false."',
'spec_title': 'RFC7232#4.1',
'spec_href': 'https://tools.ietf.org/html/rfc7232#section-4.1',
},
'305': {
'code': 305,
'text': 'Use Proxy',
'description': '*deprecated*',
'spec_title': 'RFC7231#6.4.5',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.5',
},
'307': {
'code': 307,
'text': 'Temporary Redirect',
'description':
'"The target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI."',
'spec_title': 'RFC7231#6.4.7',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.7',
},
'400': {
'code': 400,
'text': 'Bad Request',
'description':
'"The server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process."',
'spec_title': 'RFC7231#6.5.1',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.1',
},
'401': {
'code': 401,
'text': 'Unauthorized',
'description':
'"The request has not been applied because it lacks valid authentication credentials for the target resource."',
'spec_title': 'RFC7235#6.3.1',
'spec_href': 'https://tools.ietf.org/html/rfc7235#section-3.1',
},
'402': {
'code': 402,
'text': 'Payment Required',
'description': '*reserved*',
'spec_title': 'RFC7231#6.5.2',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.2',
},
'403': {
'code': 403,
'text': 'Forbidden',
'description': '"The server understood the request but refuses to authorize it."',
'spec_title': 'RFC7231#6.5.3',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.3',
},
'404': {
'code': 404,
'text': 'Not Found',
'description':
'"The origin server did not find a current representation for the target resource or is not willing to disclose that one exists."',
'spec_title': 'RFC7231#6.5.4',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.4',
}, | {
"end_byte": 8526,
"start_byte": 1766,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts_8529_15354 | '405': {
'code': 405,
'text': 'Method Not Allowed',
'description':
'"The method specified in the request-line is known by the origin server but not supported by the target resource."',
'spec_title': 'RFC7231#6.5.5',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.5',
},
'406': {
'code': 406,
'text': 'Not Acceptable',
'description':
'"The target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation."',
'spec_title': 'RFC7231#6.5.6',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.6',
},
'407': {
'code': 407,
'text': 'Proxy Authentication Required',
'description': '"The client needs to authenticate itself in order to use a proxy."',
'spec_title': 'RFC7231#6.3.2',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.2',
},
'408': {
'code': 408,
'text': 'Request Timeout',
'description':
'"The server did not receive a complete request message within the time that it was prepared to wait."',
'spec_title': 'RFC7231#6.5.7',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.7',
},
'409': {
'code': 409,
'text': 'Conflict',
'description':
'"The request could not be completed due to a conflict with the current state of the resource."',
'spec_title': 'RFC7231#6.5.8',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.8',
},
'410': {
'code': 410,
'text': 'Gone',
'description':
'"Access to the target resource is no longer available at the origin server and that this condition is likely to be permanent."',
'spec_title': 'RFC7231#6.5.9',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.9',
},
'411': {
'code': 411,
'text': 'Length Required',
'description': '"The server refuses to accept the request without a defined Content-Length."',
'spec_title': 'RFC7231#6.5.10',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.10',
},
'412': {
'code': 412,
'text': 'Precondition Failed',
'description':
'"One or more preconditions given in the request header fields evaluated to false when tested on the server."',
'spec_title': 'RFC7232#4.2',
'spec_href': 'https://tools.ietf.org/html/rfc7232#section-4.2',
},
'413': {
'code': 413,
'text': 'Payload Too Large',
'description':
'"The server is refusing to process a request because the request payload is larger than the server is willing or able to process."',
'spec_title': 'RFC7231#6.5.11',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.11',
},
'414': {
'code': 414,
'text': 'URI Too Long',
'description':
'"The server is refusing to service the request because the request-target is longer than the server is willing to interpret."',
'spec_title': 'RFC7231#6.5.12',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.12',
},
'415': {
'code': 415,
'text': 'Unsupported Media Type',
'description':
'"The origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method."',
'spec_title': 'RFC7231#6.5.13',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.13',
},
'416': {
'code': 416,
'text': 'Range Not Satisfiable',
'description':
'"None of the ranges in the request\'s Range header field overlap the current extent of the selected resource or that the set of ranges requested has been rejected due to invalid ranges or an excessive request of small or overlapping ranges."',
'spec_title': 'RFC7233#4.4',
'spec_href': 'https://tools.ietf.org/html/rfc7233#section-4.4',
},
'417': {
'code': 417,
'text': 'Expectation Failed',
'description':
'"The expectation given in the request\'s Expect header field could not be met by at least one of the inbound servers."',
'spec_title': 'RFC7231#6.5.14',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.14',
},
'418': {
'code': 418,
'text': "I'm a teapot",
'description': '"1988 April Fools Joke. Returned by tea pots requested to brew coffee."',
'spec_title': 'RFC 2324',
'spec_href': 'https://tools.ietf.org/html/rfc2324',
},
'426': {
'code': 426,
'text': 'Upgrade Required',
'description':
'"The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol."',
'spec_title': 'RFC7231#6.5.15',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.15',
},
'500': {
'code': 500,
'text': 'Internal Server Error',
'description':
'"The server encountered an unexpected condition that prevented it from fulfilling the request."',
'spec_title': 'RFC7231#6.6.1',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.1',
},
'501': {
'code': 501,
'text': 'Not Implemented',
'description':
'"The server does not support the functionality required to fulfill the request."',
'spec_title': 'RFC7231#6.6.2',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.2',
},
'502': {
'code': 502,
'text': 'Bad Gateway',
'description':
'"The server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request."',
'spec_title': 'RFC7231#6.6.3',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.3',
},
'503': {
'code': 503,
'text': 'Service Unavailable',
'description':
'"The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay."',
'spec_title': 'RFC7231#6.6.4',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.4',
},
'504': {
'code': 504,
'text': 'Gateway Time-out',
'description':
'"The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request."',
'spec_title': 'RFC7231#6.6.5',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.5',
},
'505': {
'code': 505,
'text': 'HTTP Version Not Supported',
'description':
'"The server does not support, or refuses to support, the protocol version that was used in the request message."',
'spec_title': 'RFC7231#6.6.6',
'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.6',
}, | {
"end_byte": 15354,
"start_byte": 8529,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts_15357_20322 | '102': {
'code': 102,
'text': 'Processing',
'description':
'"An interim response to inform the client that the server has accepted the complete request, but has not yet completed it."',
'spec_title': 'RFC5218#10.1',
'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.1',
},
'207': {
'code': 207,
'text': 'Multi-Status',
'description': '"Status for multiple independent operations."',
'spec_title': 'RFC5218#10.2',
'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.2',
},
'226': {
'code': 226,
'text': 'IM Used',
'description':
'"The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance."',
'spec_title': 'RFC3229#10.4.1',
'spec_href': 'https://tools.ietf.org/html/rfc3229#section-10.4.1',
},
'308': {
'code': 308,
'text': 'Permanent Redirect',
'description':
'"The target resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. [...] This status code is similar to 301 Moved Permanently (Section 7.3.2 of rfc7231), except that it does not allow rewriting the request method from POST to GET."',
'spec_title': 'RFC7238',
'spec_href': 'https://tools.ietf.org/html/rfc7238',
},
'422': {
'code': 422,
'text': 'Unprocessable Entity',
'description':
'"The server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions."',
'spec_title': 'RFC5218#10.3',
'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.3',
},
'423': {
'code': 423,
'text': 'Locked',
'description': '"The source or destination resource of a method is locked."',
'spec_title': 'RFC5218#10.4',
'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.4',
},
'424': {
'code': 424,
'text': 'Failed Dependency',
'description':
'"The method could not be performed on the resource because the requested action depended on another action and that action failed."',
'spec_title': 'RFC5218#10.5',
'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.5',
},
'428': {
'code': 428,
'text': 'Precondition Required',
'description': '"The origin server requires the request to be conditional."',
'spec_title': 'RFC6585#3',
'spec_href': 'https://tools.ietf.org/html/rfc6585#section-3',
},
'429': {
'code': 429,
'text': 'Too Many Requests',
'description':
'"The user has sent too many requests in a given amount of time ("rate limiting")."',
'spec_title': 'RFC6585#4',
'spec_href': 'https://tools.ietf.org/html/rfc6585#section-4',
},
'431': {
'code': 431,
'text': 'Request Header Fields Too Large',
'description':
'"The server is unwilling to process the request because its header fields are too large."',
'spec_title': 'RFC6585#5',
'spec_href': 'https://tools.ietf.org/html/rfc6585#section-5',
},
'451': {
'code': 451,
'text': 'Unavailable For Legal Reasons',
'description': '"The server is denying access to the resource in response to a legal demand."',
'spec_title': 'draft-ietf-httpbis-legally-restricted-status',
'spec_href': 'https://tools.ietf.org/html/draft-ietf-httpbis-legally-restricted-status',
},
'506': {
'code': 506,
'text': 'Variant Also Negotiates',
'description':
'"The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process."',
'spec_title': 'RFC2295#8.1',
'spec_href': 'https://tools.ietf.org/html/rfc2295#section-8.1',
},
'507': {
'code': 507,
'text': 'Insufficient Storage',
'description':
'The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request."',
'spec_title': 'RFC5218#10.6',
'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.6',
},
'511': {
'code': 511,
'text': 'Network Authentication Required',
'description': '"The client needs to authenticate to gain network access."',
'spec_title': 'RFC6585#6',
'spec_href': 'https://tools.ietf.org/html/rfc6585#section-6',
},
};
/**
* get the status text from StatusCode
*/
export function getStatusText(code: number) {
return STATUS_CODE_INFO[code + ''].text || 'Unknown Status';
}
/**
* Returns true if the Http Status Code is 200-299 (success)
*/
export function isSuccess(status: number): boolean {
return status >= 200 && status < 300;
} | {
"end_byte": 20322,
"start_byte": 15357,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/delay-response.ts_0_1107 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable} from 'rxjs';
// Replaces use of RxJS delay. See v0.5.4.
/** adds specified delay (in ms) to both next and error channels of the response observable */
export function delayResponse<T>(response$: Observable<T>, delayMs: number): Observable<T> {
return new Observable<T>((observer) => {
let completePending = false;
let nextPending = false;
const subscription = response$.subscribe(
(value) => {
nextPending = true;
setTimeout(() => {
observer.next(value);
if (completePending) {
observer.complete();
}
}, delayMs);
},
(error) => setTimeout(() => observer.error(error), delayMs),
() => {
completePending = true;
if (!nextPending) {
observer.complete();
}
},
);
return () => {
return subscription.unsubscribe();
};
});
}
| {
"end_byte": 1107,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/delay-response.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/interfaces.ts_0_7498 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {HttpHeaders} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
/**
* Interface for a class that creates an in-memory database
*
* Its `createDb` method creates a hash of named collections that represents the database
*
* For maximum flexibility, the service may define HTTP method overrides.
* Such methods must match the spelling of an HTTP method in lower case (e.g, "get").
* If a request has a matching method, it will be called as in
* `get(info: requestInfo, db: {})` where `db` is the database object described above.
*/
export abstract class InMemoryDbService {
/**
* Creates an in-memory "database" hash whose keys are collection names
* and whose values are arrays of collection objects to return or update.
*
* returns Observable of the database because could have to create it asynchronously.
*
* This method must be safe to call repeatedly.
* Each time it should return a new object with new arrays containing new item objects.
* This condition allows the in-memory backend service to mutate the collections
* and their items without touching the original source data.
*
* The in-mem backend service calls this method without a value the first time.
* The service calls it with the `RequestInfo` when it receives a POST `commands/resetDb` request.
* Your InMemoryDbService can adjust its behavior accordingly.
*/
abstract createDb(reqInfo?: RequestInfo): {} | Observable<{}> | Promise<{}>;
}
/**
* Interface for InMemoryBackend configuration options
*/
export abstract class InMemoryBackendConfigArgs {
/**
* The base path to the api, e.g, 'api/'.
* If not specified than `parseRequestUrl` assumes it is the first path segment in the request.
*/
apiBase?: string;
/**
* false (default) if search match should be case insensitive
*/
caseSensitiveSearch?: boolean;
/**
* false (default) put content directly inside the response body.
* true: encapsulate content in a `data` property inside the response body, `{ data: ... }`.
*/
dataEncapsulation?: boolean;
/**
* delay (in ms) to simulate latency
*/
delay?: number;
/**
* false (default) should 204 when object-to-delete not found; true: 404
*/
delete404?: boolean;
/**
* host for this service, e.g., 'localhost'
*/
host?: string;
/**
* true, should pass unrecognized request URL through to original backend; false (default): 404
*/
passThruUnknownUrl?: boolean;
/**
* true (default) should NOT return the item (204) after a POST. false: return the item (200).
*/
post204?: boolean;
/**
* false (default) should NOT update existing item with POST. false: OK to update.
*/
post409?: boolean;
/**
* true (default) should NOT return the item (204) after a POST. false: return the item (200).
*/
put204?: boolean;
/**
* false (default) if item not found, create as new item; false: should 404.
*/
put404?: boolean;
/**
* root path _before_ any API call, e.g., ''
*/
rootPath?: string;
}
/////////////////////////////////
/**
* InMemoryBackendService configuration options
* Usage:
* InMemoryWebApiModule.forRoot(InMemHeroService, {delay: 600})
*
* or if providing separately:
* provide(InMemoryBackendConfig, {useValue: {delay: 600}}),
*/
@Injectable()
export class InMemoryBackendConfig implements InMemoryBackendConfigArgs {
constructor(config: InMemoryBackendConfigArgs = {}) {
Object.assign(
this,
{
// default config:
caseSensitiveSearch: false,
dataEncapsulation: false, // do NOT wrap content within an object with a `data` property
delay: 500, // simulate latency by delaying response
delete404: false, // don't complain if can't find entity to delete
passThruUnknownUrl: false, // 404 if can't process URL
post204: true, // don't return the item after a POST
post409: false, // don't update existing item with that ID
put204: true, // don't return the item after a PUT
put404: false, // create new item if PUT item with that ID not found
apiBase: undefined, // assumed to be the first path segment
host: undefined, // default value is actually set in InMemoryBackendService ctor
rootPath: undefined, // default value is actually set in InMemoryBackendService ctor
},
config,
);
}
}
/** Return information (UriInfo) about a URI */
export function parseUri(str: string): UriInfo {
// Adapted from parseuri package - http://blog.stevenlevithan.com/archives/parseuri
// tslint:disable-next-line:max-line-length
const URL_REGEX =
/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
const m = URL_REGEX.exec(str);
const uri: UriInfo & {[key: string]: string} = {
source: '',
protocol: '',
authority: '',
userInfo: '',
user: '',
password: '',
host: '',
port: '',
relative: '',
path: '',
directory: '',
file: '',
query: '',
anchor: '',
};
const keys = Object.keys(uri);
let i = keys.length;
while (i--) {
uri[keys[i]] = (m && m[i]) || '';
}
return uri;
}
/**
*
* Interface for the result of the `parseRequestUrl` method:
* Given URL "http://localhost:8080/api/customers/42?foo=1 the default implementation returns
* base: 'api/'
* collectionName: 'customers'
* id: '42'
* query: this.createQuery('foo=1')
* resourceUrl: 'http://localhost/api/customers/'
*/
export interface ParsedRequestUrl {
apiBase: string; // the slash-terminated "base" for api requests (e.g. `api/`)
collectionName: string; // the name of the collection of data items (e.g.,`customers`)
id: string; // the (optional) id of the item in the collection (e.g., `42`)
query: Map<string, string[]>; // the query parameters;
resourceUrl: string; // the effective URL for the resource (e.g., 'http://localhost/api/customers/')
}
export interface PassThruBackend {
/**
* Handle an HTTP request and return an Observable of HTTP response
* Both the request type and the response type are determined by the supporting HTTP library.
*/
handle(req: any): Observable<any>;
}
export function removeTrailingSlash(path: string) {
return path.replace(/\/$/, '');
}
/**
* Minimum definition needed by base class
*/
export interface RequestCore {
url: string; // request URL
urlWithParams?: string; // request URL with query parameters added by `HttpParams`
}
/**
* Interface for object w/ info about the current request url
* extracted from an Http Request.
* Also holds utility methods and configuration data from this service
*/
export interface RequestInfo {
req: RequestCore; // concrete type depends upon the Http library
apiBase: string;
collectionName: string;
collection: any;
headers: HttpHeaders;
method: string;
id: any;
query: Map<string, string[]>;
resourceUrl: string;
url: string; // request URL
utils: RequestInfoUtilities;
}
/**
* Interface for utility methods from this service instance.
* Useful within an HTTP method override
*/ | {
"end_byte": 7498,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/interfaces.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/interfaces.ts_7499_10122 | export interface RequestInfoUtilities {
/**
* Create a cold response Observable from a factory for ResponseOptions
* the same way that the in-mem backend service does.
* @param resOptionsFactory - creates ResponseOptions when observable is subscribed
* @param withDelay - if true (default), add simulated latency delay from configuration
*/
createResponse$: (resOptionsFactory: () => ResponseOptions) => Observable<any>;
/**
* Find first instance of item in collection by `item.id`
* @param collection
* @param id
*/
findById<T extends {id: any}>(collection: T[], id: any): T | undefined;
/** return the current, active configuration which is a blend of defaults and overrides */
getConfig(): InMemoryBackendConfigArgs;
/** Get the in-mem service's copy of the "database" */
getDb(): {};
/** Get JSON body from the request object */
getJsonBody(req: any): any;
/** Get location info from a url, even on server where `document` is not defined */
getLocation(url: string): UriInfo;
/** Get (or create) the "real" backend */
getPassThruBackend(): PassThruBackend;
/**
* return true if can determine that the collection's `item.id` is a number
* */
isCollectionIdNumeric<T extends {id: any}>(collection: T[], collectionName: string): boolean;
/**
* Parses the request URL into a `ParsedRequestUrl` object.
* Parsing depends upon certain values of `config`: `apiBase`, `host`, and `urlRoot`.
*/
parseRequestUrl(url: string): ParsedRequestUrl;
}
/**
* Provide a `responseInterceptor` method of this type in your `inMemDbService` to
* morph the response options created in the `collectionHandler`.
*/
export type ResponseInterceptor = (res: ResponseOptions, ri: RequestInfo) => ResponseOptions;
export interface ResponseOptions {
/**
* String, Object, ArrayBuffer or Blob representing the body of the {@link Response}.
*/
body?: string | Object | ArrayBuffer | Blob;
/**
* Response headers
*/
headers?: HttpHeaders;
/**
* Http {@link https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html status code}
* associated with the response.
*/
status?: number;
/**
* Status text for the status code
*/
statusText?: string;
/**
* request url
*/
url?: string;
}
/** Interface of information about a Uri */
export interface UriInfo {
source: string;
protocol: string;
authority: string;
userInfo: string;
user: string;
password: string;
host: string;
port: string;
relative: string;
path: string;
directory: string;
file: string;
query: string;
anchor: string;
} | {
"end_byte": 10122,
"start_byte": 7499,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/interfaces.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/backend-service.ts_0_1060 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {HttpHeaders} from '@angular/common/http';
import {BehaviorSubject, from, Observable, Observer, of} from 'rxjs';
import {concatMap, first} from 'rxjs/operators';
import {delayResponse} from './delay-response';
import {getStatusText, isSuccess, STATUS} from './http-status-codes';
import {
InMemoryBackendConfig,
InMemoryBackendConfigArgs,
InMemoryDbService,
ParsedRequestUrl,
parseUri,
PassThruBackend,
removeTrailingSlash,
RequestCore,
RequestInfo,
RequestInfoUtilities,
ResponseOptions,
UriInfo,
} from './interfaces';
/**
* Base class for in-memory web api back-ends
* Simulate the behavior of a RESTy web api
* backed by the simple in-memory data store provided by the injected `InMemoryDbService` service.
* Conforms mostly to behavior described here:
* http://www.restapitutorial.com/lessons/httpmethods.html
*/ | {
"end_byte": 1060,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/backend-service.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/backend-service.ts_1061_8724 | export abstract class BackendService {
protected config: InMemoryBackendConfigArgs = new InMemoryBackendConfig();
protected db: {[key: string]: any} = {};
protected dbReadySubject: BehaviorSubject<boolean> | undefined;
private passThruBackend: PassThruBackend | undefined;
protected requestInfoUtils = this.getRequestInfoUtils();
constructor(
protected inMemDbService: InMemoryDbService,
config: InMemoryBackendConfigArgs = {},
) {
const loc = this.getLocation('/');
this.config.host = loc.host; // default to app web server host
this.config.rootPath = loc.path; // default to path when app is served (e.g.'/')
Object.assign(this.config, config);
}
protected get dbReady(): Observable<boolean> {
if (!this.dbReadySubject) {
// first time the service is called.
this.dbReadySubject = new BehaviorSubject<boolean>(false);
this.resetDb();
}
return this.dbReadySubject.asObservable().pipe(first((r: boolean) => r));
}
/**
* Process Request and return an Observable of Http Response object
* in the manner of a RESTy web api.
*
* Expect URI pattern in the form :base/:collectionName/:id?
* Examples:
* // for store with a 'customers' collection
* GET api/customers // all customers
* GET api/customers/42 // the character with id=42
* GET api/customers?name=^j // 'j' is a regex; returns customers whose name starts with 'j' or
* 'J' GET api/customers.json/42 // ignores the ".json"
*
* Also accepts direct commands to the service in which the last segment of the apiBase is the
* word "commands" Examples: POST commands/resetDb, GET/POST commands/config - get or (re)set the
* config
*
* HTTP overrides:
* If the injected inMemDbService defines an HTTP method (lowercase)
* The request is forwarded to that method as in
* `inMemDbService.get(requestInfo)`
* which must return either an Observable of the response type
* for this http library or null|undefined (which means "keep processing").
*/
protected handleRequest(req: RequestCore): Observable<any> {
// handle the request when there is an in-memory database
return this.dbReady.pipe(concatMap(() => this.handleRequest_(req)));
}
protected handleRequest_(req: RequestCore): Observable<any> {
const url = req.urlWithParams ? req.urlWithParams : req.url;
// Try override parser
// If no override parser or it returns nothing, use default parser
const parser = this.bind('parseRequestUrl');
const parsed: ParsedRequestUrl =
(parser && parser(url, this.requestInfoUtils)) || this.parseRequestUrl(url);
const collectionName = parsed.collectionName;
const collection = this.db[collectionName];
const reqInfo: RequestInfo = {
req: req,
apiBase: parsed.apiBase,
collection: collection,
collectionName: collectionName,
headers: this.createHeaders({'Content-Type': 'application/json'}),
id: this.parseId(collection, collectionName, parsed.id),
method: this.getRequestMethod(req),
query: parsed.query,
resourceUrl: parsed.resourceUrl,
url: url,
utils: this.requestInfoUtils,
};
let resOptions: ResponseOptions;
if (/commands\/?$/i.test(reqInfo.apiBase)) {
return this.commands(reqInfo);
}
const methodInterceptor = this.bind(reqInfo.method);
if (methodInterceptor) {
// InMemoryDbService intercepts this HTTP method.
// if interceptor produced a response, return it.
// else InMemoryDbService chose not to intercept; continue processing.
const interceptorResponse = methodInterceptor(reqInfo);
if (interceptorResponse) {
return interceptorResponse;
}
}
if (this.db[collectionName]) {
// request is for a known collection of the InMemoryDbService
return this.createResponse$(() => this.collectionHandler(reqInfo));
}
if (this.config.passThruUnknownUrl) {
// unknown collection; pass request thru to a "real" backend.
return this.getPassThruBackend().handle(req);
}
// 404 - can't handle this request
resOptions = this.createErrorResponseOptions(
url,
STATUS.NOT_FOUND,
`Collection '${collectionName}' not found`,
);
return this.createResponse$(() => resOptions);
}
/**
* Add configured delay to response observable unless delay === 0
*/
protected addDelay(response: Observable<any>): Observable<any> {
const d = this.config.delay;
return d === 0 ? response : delayResponse(response, d || 500);
}
/**
* Apply query/search parameters as a filter over the collection
* This impl only supports RegExp queries on string properties of the collection
* ANDs the conditions together
*/
protected applyQuery(collection: any[], query: Map<string, string[]>): any[] {
// extract filtering conditions - {propertyName, RegExps) - from query/search parameters
const conditions: {name: string; rx: RegExp}[] = [];
const caseSensitive = this.config.caseSensitiveSearch ? undefined : 'i';
query.forEach((value: string[], name: string) => {
value.forEach((v) => conditions.push({name, rx: new RegExp(decodeURI(v), caseSensitive)}));
});
const len = conditions.length;
if (!len) {
return collection;
}
// AND the RegExp conditions
return collection.filter((row) => {
let ok = true;
let i = len;
while (ok && i) {
i -= 1;
const cond = conditions[i];
ok = cond.rx.test(row[cond.name]);
}
return ok;
});
}
/**
* Get a method from the `InMemoryDbService` (if it exists), bound to that service
*/
protected bind<T extends Function>(methodName: string) {
const fn = (this.inMemDbService as any)[methodName];
return fn ? (fn.bind(this.inMemDbService) as T) : undefined;
}
protected bodify(data: any) {
return this.config.dataEncapsulation ? {data} : data;
}
protected clone(data: any) {
return JSON.parse(JSON.stringify(data));
}
protected collectionHandler(reqInfo: RequestInfo): ResponseOptions {
// const req = reqInfo.req;
let resOptions: ResponseOptions;
switch (reqInfo.method) {
case 'get':
resOptions = this.get(reqInfo);
break;
case 'post':
resOptions = this.post(reqInfo);
break;
case 'put':
resOptions = this.put(reqInfo);
break;
case 'delete':
resOptions = this.delete(reqInfo);
break;
default:
resOptions = this.createErrorResponseOptions(
reqInfo.url,
STATUS.METHOD_NOT_ALLOWED,
'Method not allowed',
);
break;
}
// If `inMemDbService.responseInterceptor` exists, let it morph the response options
const interceptor = this.bind('responseInterceptor');
return interceptor ? interceptor(resOptions, reqInfo) : resOptions;
}
/**
* Commands reconfigure the in-memory web api service or extract information from it.
* Commands ignore the latency delay and respond ASAP.
*
* When the last segment of the `apiBase` path is "commands",
* the `collectionName` is the command.
*
* Example URLs:
* commands/resetdb (POST) // Reset the "database" to its original state
* commands/config (GET) // Return this service's config object
* commands/config (POST) // Update the config (e.g. the delay)
*
* Usage:
* http.post('commands/resetdb', undefined);
* http.get('commands/config');
* http.post('commands/config', '{"delay":1000}');
*/ | {
"end_byte": 8724,
"start_byte": 1061,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/backend-service.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/backend-service.ts_8727_17295 | protected commands(reqInfo: RequestInfo): Observable<any> {
const command = reqInfo.collectionName.toLowerCase();
const method = reqInfo.method;
let resOptions: ResponseOptions = {url: reqInfo.url};
switch (command) {
case 'resetdb':
resOptions.status = STATUS.NO_CONTENT;
return this.resetDb(reqInfo).pipe(
concatMap(() => this.createResponse$(() => resOptions, false /* no latency delay */)),
);
case 'config':
if (method === 'get') {
resOptions.status = STATUS.OK;
resOptions.body = this.clone(this.config);
// any other HTTP method is assumed to be a config update
} else {
const body = this.getJsonBody(reqInfo.req);
Object.assign(this.config, body);
this.passThruBackend = undefined; // re-create when needed
resOptions.status = STATUS.NO_CONTENT;
}
break;
default:
resOptions = this.createErrorResponseOptions(
reqInfo.url,
STATUS.INTERNAL_SERVER_ERROR,
`Unknown command "${command}"`,
);
}
return this.createResponse$(() => resOptions, false /* no latency delay */);
}
protected createErrorResponseOptions(
url: string,
status: number,
message: string,
): ResponseOptions {
return {
body: {error: `${message}`},
url: url,
headers: this.createHeaders({'Content-Type': 'application/json'}),
status: status,
};
}
/**
* Create standard HTTP headers object from hash map of header strings
* @param headers
*/
protected abstract createHeaders(headers: {[index: string]: string}): HttpHeaders;
/**
* create the function that passes unhandled requests through to the "real" backend.
*/
protected abstract createPassThruBackend(): PassThruBackend;
/**
* return a search map from a location query/search string
*/
protected abstract createQueryMap(search: string): Map<string, string[]>;
/**
* Create a cold response Observable from a factory for ResponseOptions
* @param resOptionsFactory - creates ResponseOptions when observable is subscribed
* @param withDelay - if true (default), add simulated latency delay from configuration
*/
protected createResponse$(
resOptionsFactory: () => ResponseOptions,
withDelay = true,
): Observable<any> {
const resOptions$ = this.createResponseOptions$(resOptionsFactory);
let resp$ = this.createResponse$fromResponseOptions$(resOptions$);
return withDelay ? this.addDelay(resp$) : resp$;
}
/**
* Create a Response observable from ResponseOptions observable.
*/
protected abstract createResponse$fromResponseOptions$(
resOptions$: Observable<ResponseOptions>,
): Observable<any>;
/**
* Create a cold Observable of ResponseOptions.
* @param resOptionsFactory - creates ResponseOptions when observable is subscribed
*/
protected createResponseOptions$(
resOptionsFactory: () => ResponseOptions,
): Observable<ResponseOptions> {
return new Observable<ResponseOptions>((responseObserver: Observer<ResponseOptions>) => {
let resOptions: ResponseOptions;
try {
resOptions = resOptionsFactory();
} catch (error) {
const err = (error as Error).message || error;
resOptions = this.createErrorResponseOptions('', STATUS.INTERNAL_SERVER_ERROR, `${err}`);
}
const status = resOptions.status;
try {
resOptions.statusText = status != null ? getStatusText(status) : undefined;
} catch (e) {
/* ignore failure */
}
if (status != null && isSuccess(status)) {
responseObserver.next(resOptions);
responseObserver.complete();
} else {
responseObserver.error(resOptions);
}
return () => {}; // unsubscribe function
});
}
protected delete({collection, collectionName, headers, id, url}: RequestInfo): ResponseOptions {
if (id == null) {
return this.createErrorResponseOptions(
url,
STATUS.NOT_FOUND,
`Missing "${collectionName}" id`,
);
}
const exists = this.removeById(collection, id);
return {
headers: headers,
status: exists || !this.config.delete404 ? STATUS.NO_CONTENT : STATUS.NOT_FOUND,
};
}
/**
* Find first instance of item in collection by `item.id`
* @param collection
* @param id
*/
protected findById<T extends {id: any}>(collection: T[], id: any): T | undefined {
return collection.find((item: T) => item.id === id);
}
/**
* Generate the next available id for item in this collection
* Use method from `inMemDbService` if it exists and returns a value,
* else delegates to `genIdDefault`.
* @param collection - collection of items with `id` key property
*/
protected genId<T extends {id: any}>(collection: T[], collectionName: string): any {
const genId = this.bind('genId');
if (genId) {
const id = genId(collection, collectionName);
if (id != null) {
return id;
}
}
return this.genIdDefault(collection, collectionName);
}
/**
* Default generator of the next available id for item in this collection
* This default implementation works only for numeric ids.
* @param collection - collection of items with `id` key property
* @param collectionName - name of the collection
*/
protected genIdDefault<T extends {id: any}>(collection: T[], collectionName: string): any {
if (!this.isCollectionIdNumeric(collection, collectionName)) {
throw new Error(
`Collection '${collectionName}' id type is non-numeric or unknown. Can only generate numeric ids.`,
);
}
let maxId = 0;
collection.reduce((prev: any, item: any) => {
maxId = Math.max(maxId, typeof item.id === 'number' ? item.id : maxId);
}, undefined);
return maxId + 1;
}
protected get({
collection,
collectionName,
headers,
id,
query,
url,
}: RequestInfo): ResponseOptions {
let data = collection;
if (id != null && id !== '') {
data = this.findById(collection, id);
} else if (query) {
data = this.applyQuery(collection, query);
}
if (!data) {
return this.createErrorResponseOptions(
url,
STATUS.NOT_FOUND,
`'${collectionName}' with id='${id}' not found`,
);
}
return {body: this.bodify(this.clone(data)), headers: headers, status: STATUS.OK};
}
/** Get JSON body from the request object */
protected abstract getJsonBody(req: any): any;
/**
* Get location info from a url, even on server where `document` is not defined
*/
protected getLocation(url: string): UriInfo {
if (!url.startsWith('http')) {
// get the document iff running in browser
const doc = typeof document === 'undefined' ? undefined : document;
// add host info to url before parsing. Use a fake host when not in browser.
const base = doc ? doc.location.protocol + '//' + doc.location.host : 'http://fake';
url = url.startsWith('/') ? base + url : base + '/' + url;
}
return parseUri(url);
}
/**
* get or create the function that passes unhandled requests
* through to the "real" backend.
*/
protected getPassThruBackend(): PassThruBackend {
return this.passThruBackend
? this.passThruBackend
: (this.passThruBackend = this.createPassThruBackend());
}
/**
* Get utility methods from this service instance.
* Useful within an HTTP method override
*/
protected getRequestInfoUtils(): RequestInfoUtilities {
return {
createResponse$: this.createResponse$.bind(this),
findById: this.findById.bind(this),
isCollectionIdNumeric: this.isCollectionIdNumeric.bind(this),
getConfig: () => this.config,
getDb: () => this.db,
getJsonBody: this.getJsonBody.bind(this),
getLocation: this.getLocation.bind(this),
getPassThruBackend: this.getPassThruBackend.bind(this),
parseRequestUrl: this.parseRequestUrl.bind(this),
};
}
/**
* return canonical HTTP method name (lowercase) from the request object
* e.g. (req.method || 'get').toLowerCase();
* @param req - request object from the http call
*
*/
protected abstract getRequestMethod(req: any): string;
protected indexOf(collection: any[], id: number): number {
return collection.findIndex((item: any) => item.id === id);
}
/** Parse the id as a number. Return original value if not a number. */ | {
"end_byte": 17295,
"start_byte": 8727,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/backend-service.ts"
} |
angular/packages/misc/angular-in-memory-web-api/src/backend-service.ts_17298_25133 | protected parseId(collection: any[], collectionName: string, id: string): any {
if (!this.isCollectionIdNumeric(collection, collectionName)) {
// Can't confirm that `id` is a numeric type; don't parse as a number
// or else `'42'` -> `42` and _get by id_ fails.
return id;
}
const idNum = parseFloat(id);
return isNaN(idNum) ? id : idNum;
}
/**
* return true if can determine that the collection's `item.id` is a number
* This implementation can't tell if the collection is empty so it assumes NO
* */
protected isCollectionIdNumeric<T extends {id: any}>(
collection: T[],
collectionName: string,
): boolean {
// collectionName not used now but override might maintain collection type information
// so that it could know the type of the `id` even when the collection is empty.
return !!(collection && collection[0]) && typeof collection[0].id === 'number';
}
/**
* Parses the request URL into a `ParsedRequestUrl` object.
* Parsing depends upon certain values of `config`: `apiBase`, `host`, and `urlRoot`.
*
* Configuring the `apiBase` yields the most interesting changes to `parseRequestUrl` behavior:
* When apiBase=undefined and url='http://localhost/api/collection/42'
* {base: 'api/', collectionName: 'collection', id: '42', ...}
* When apiBase='some/api/root/' and url='http://localhost/some/api/root/collection'
* {base: 'some/api/root/', collectionName: 'collection', id: undefined, ...}
* When apiBase='/' and url='http://localhost/collection'
* {base: '/', collectionName: 'collection', id: undefined, ...}
*
* The actual api base segment values are ignored. Only the number of segments matters.
* The following api base strings are considered identical: 'a/b' ~ 'some/api/' ~ `two/segments'
*
* To replace this default method, assign your alternative to your
* InMemDbService['parseRequestUrl']
*/
protected parseRequestUrl(url: string): ParsedRequestUrl {
try {
const loc = this.getLocation(url);
let drop = (this.config.rootPath || '').length;
let urlRoot = '';
if (loc.host !== this.config.host) {
// url for a server on a different host!
// assume it's collection is actually here too.
drop = 1; // the leading slash
urlRoot = loc.protocol + '//' + loc.host + '/';
}
const path = loc.path.substring(drop);
const pathSegments = path.split('/');
let segmentIndex = 0;
// apiBase: the front part of the path devoted to getting to the api route
// Assumes first path segment if no config.apiBase
// else ignores as many path segments as are in config.apiBase
// Does NOT care what the api base chars actually are.
let apiBase: string;
if (this.config.apiBase == null) {
apiBase = pathSegments[segmentIndex++];
} else {
apiBase = removeTrailingSlash(this.config.apiBase.trim());
if (apiBase) {
segmentIndex = apiBase.split('/').length;
} else {
segmentIndex = 0; // no api base at all; unwise but allowed.
}
}
apiBase += '/';
let collectionName = pathSegments[segmentIndex++];
// ignore anything after a '.' (e.g.,the "json" in "customers.json")
collectionName = collectionName && collectionName.split('.')[0];
const id = pathSegments[segmentIndex++];
const query = this.createQueryMap(loc.query);
const resourceUrl = urlRoot + apiBase + collectionName + '/';
return {apiBase, collectionName, id, query, resourceUrl};
} catch (err) {
const msg = `unable to parse url '${url}'; original error: ${(err as Error).message}`;
throw new Error(msg);
}
}
// Create entity
// Can update an existing entity too if post409 is false.
protected post({
collection,
collectionName,
headers,
id,
req,
resourceUrl,
url,
}: RequestInfo): ResponseOptions {
const item = this.clone(this.getJsonBody(req));
if (item.id == null) {
try {
item.id = id || this.genId(collection, collectionName);
} catch (err) {
const emsg: string = (err as Error).message || '';
if (/id type is non-numeric/.test(emsg)) {
return this.createErrorResponseOptions(url, STATUS.UNPROCESSABLE_ENTRY, emsg);
} else {
return this.createErrorResponseOptions(
url,
STATUS.INTERNAL_SERVER_ERROR,
`Failed to generate new id for '${collectionName}'`,
);
}
}
}
if (id && id !== item.id) {
return this.createErrorResponseOptions(
url,
STATUS.BAD_REQUEST,
`Request id does not match item.id`,
);
} else {
id = item.id;
}
const existingIx = this.indexOf(collection, id);
const body = this.bodify(item);
if (existingIx === -1) {
collection.push(item);
headers.set('Location', resourceUrl + '/' + id);
return {headers, body, status: STATUS.CREATED};
} else if (this.config.post409) {
return this.createErrorResponseOptions(
url,
STATUS.CONFLICT,
`'${collectionName}' item with id='${id} exists and may not be updated with POST; use PUT instead.`,
);
} else {
collection[existingIx] = item;
return this.config.post204
? {headers, status: STATUS.NO_CONTENT} // successful; no content
: {headers, body, status: STATUS.OK}; // successful; return entity
}
}
// Update existing entity
// Can create an entity too if put404 is false.
protected put({collection, collectionName, headers, id, req, url}: RequestInfo): ResponseOptions {
const item = this.clone(this.getJsonBody(req));
if (item.id == null) {
return this.createErrorResponseOptions(
url,
STATUS.NOT_FOUND,
`Missing '${collectionName}' id`,
);
}
if (id && id !== item.id) {
return this.createErrorResponseOptions(
url,
STATUS.BAD_REQUEST,
`Request for '${collectionName}' id does not match item.id`,
);
} else {
id = item.id;
}
const existingIx = this.indexOf(collection, id);
const body = this.bodify(item);
if (existingIx > -1) {
collection[existingIx] = item;
return this.config.put204
? {headers, status: STATUS.NO_CONTENT} // successful; no content
: {headers, body, status: STATUS.OK}; // successful; return entity
} else if (this.config.put404) {
// item to update not found; use POST to create new item for this id.
return this.createErrorResponseOptions(
url,
STATUS.NOT_FOUND,
`'${collectionName}' item with id='${id} not found and may not be created with PUT; use POST instead.`,
);
} else {
// create new item for id not found
collection.push(item);
return {headers, body, status: STATUS.CREATED};
}
}
protected removeById(collection: any[], id: number) {
const ix = this.indexOf(collection, id);
if (ix > -1) {
collection.splice(ix, 1);
return true;
}
return false;
}
/**
* Tell your in-mem "database" to reset.
* returns Observable of the database because resetting it could be async
*/
protected resetDb(reqInfo?: RequestInfo): Observable<boolean> {
this.dbReadySubject && this.dbReadySubject.next(false);
const db = this.inMemDbService.createDb(reqInfo);
const db$ =
db instanceof Observable
? db
: typeof (db as any).then === 'function'
? from(db as Promise<any>)
: of(db);
db$.pipe(first()).subscribe((d: {}) => {
this.db = d;
this.dbReadySubject && this.dbReadySubject.next(true);
});
return this.dbReady;
}
} | {
"end_byte": 25133,
"start_byte": 17298,
"url": "https://github.com/angular/angular/blob/main/packages/misc/angular-in-memory-web-api/src/backend-service.ts"
} |
angular/packages/upgrade/PACKAGE.md_0_234 | Provides support for upgrading applications from Angular JS to Angular.
The primary entry point is deprecated. Use the secondary entry point,
`upgrade/static`.
See [Angular deprecation policy](reference/releases#deprecation-policy). | {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/PACKAGE.md"
} |
angular/packages/upgrade/BUILD.bazel_0_1593 | load("//tools:defaults.bzl", "api_golden_test_npm_package", "generate_api_docs", "ng_module", "ng_package")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "upgrade",
srcs = glob(
[
"*.ts",
"src/dynamic/src/*.ts",
],
),
deps = [
"//packages/core",
"//packages/platform-browser-dynamic",
"//packages/upgrade/src/common",
"//packages/zone.js/lib:zone_d_ts",
],
)
ng_package(
name = "npm_package",
package_name = "@angular/upgrade",
srcs = [
"package.json",
],
tags = [
"release-with-framework",
],
# Do not add more to this list.
# Dependencies on the full npm_package cause long re-builds.
visibility = [
"//integration:__subpackages__",
"//modules/ssr-benchmarks:__subpackages__",
],
deps = [
":upgrade",
"//packages/upgrade/static",
"//packages/upgrade/static/testing",
],
)
api_golden_test_npm_package(
name = "upgrade_api",
data = [
":npm_package",
"//goldens:public-api",
],
golden_dir = "angular/goldens/public-api/upgrade",
npm_package = "angular/packages/upgrade/npm_package",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "upgrade_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/upgrade",
)
| {
"end_byte": 1593,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/BUILD.bazel"
} |
angular/packages/upgrade/index.ts_0_481 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/index.ts"
} |
angular/packages/upgrade/public_api.ts_0_585 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package. allowing
* Angular 1 and Angular 2+ to run side by side in the same application.
*/
export {VERSION} from './src/common/src/version';
export {UpgradeAdapter, UpgradeAdapterRef} from './src/dynamic/src/upgrade_adapter';
// This file only re-exports content of the `src` folder. Keep it that way.
| {
"end_byte": 585,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/public_api.ts"
} |
angular/packages/upgrade/static/common.ts_0_846 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Note: We intentionally use cross entry-point relative paths here. This
* is because the primary entry-point is deprecated and we also don't have
* it available in G3.
*/
// @ng_package: ignore-cross-repo-import
import * as ɵangular1 from '../src/common/src/angular1';
// @ng_package: ignore-cross-repo-import
import * as ɵconstants from '../src/common/src/constants';
// @ng_package: ignore-cross-repo-import
import * as ɵupgradeHelper from '../src/common/src/upgrade_helper';
// @ng_package: ignore-cross-repo-import
import * as ɵutil from '../src/common/src/util';
export {ɵangular1, ɵconstants, ɵupgradeHelper, ɵutil};
| {
"end_byte": 846,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/common.ts"
} |
angular/packages/upgrade/static/PACKAGE.md_0_139 | Supports the upgrade path from AngularJS to Angular, allowing
components and services from both systems to be used in the same application. | {
"end_byte": 139,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/PACKAGE.md"
} |
angular/packages/upgrade/static/BUILD.bazel_0_857 | load("//tools:defaults.bzl", "generate_api_docs", "ng_module")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "static",
srcs = glob(
[
"*.ts",
"src/*.ts",
],
),
deps = [
"//packages/core",
"//packages/platform-browser",
"//packages/upgrade",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "upgrade_static_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
"//packages/upgrade:files_for_docgen",
"//packages/upgrade/src/common:files_for_docgen",
],
entry_point = ":index.ts",
module_name = "@angular/upgrade/static",
)
| {
"end_byte": 857,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/BUILD.bazel"
} |
angular/packages/upgrade/static/index.ts_0_481 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/index.ts"
} |
angular/packages/upgrade/static/public_api.ts_0_804 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {
getAngularJSGlobal,
getAngularLib,
setAngularJSGlobal,
setAngularLib,
} from '../src/common/src/angular1';
export {downgradeComponent} from '../src/common/src/downgrade_component';
export {downgradeInjectable} from '../src/common/src/downgrade_injectable';
export {VERSION} from '../src/common/src/version';
export {downgradeModule} from './src/downgrade_module';
export {UpgradeComponent} from './src/upgrade_component';
export {UpgradeModule} from './src/upgrade_module';
export * from './common';
// This file only re-exports items to appear in the public api. Keep it that way.
| {
"end_byte": 804,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/public_api.ts"
} |
angular/packages/upgrade/static/test/angular1_providers_spec.ts_0_2521 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Ng1Token} from '../../src/common/src/angular1';
import {
compileFactory,
injectorFactory,
parseFactory,
rootScopeFactory,
setTempInjectorRef,
} from '../src/angular1_providers';
describe('upgrade angular1_providers', () => {
describe('compileFactory', () => {
it('should retrieve and return `$compile`', () => {
const services: {[key: string]: any} = {$compile: 'foo'};
const mockInjector = {get: (name: Ng1Token): any => services[name], has: () => true};
expect(compileFactory(mockInjector)).toBe('foo');
});
});
describe('injectorFactory', () => {
it('should return the injector value that was previously set', () => {
const mockInjector = {get: () => undefined, has: () => false};
setTempInjectorRef(mockInjector);
const injector = injectorFactory();
expect(injector).toBe(mockInjector);
});
it('should throw if the injector value is not set', () => {
// Ensure the injector is not set. This shouldn't be necessary, but on CI there seems to be
// some race condition with previous tests not being cleaned up properly.
// Related:
// - https://github.com/angular/angular/pull/28045
// - https://github.com/angular/angular/pull/28181
setTempInjectorRef(null as any);
expect(injectorFactory).toThrowError();
});
it('should unset the injector after the first call (to prevent memory leaks)', () => {
const mockInjector = {get: () => undefined, has: () => false};
setTempInjectorRef(mockInjector);
injectorFactory();
expect(injectorFactory).toThrowError(); // ...because it has been unset
});
});
describe('parseFactory', () => {
it('should retrieve and return `$parse`', () => {
const services: {[key: string]: any} = {$parse: 'bar'};
const mockInjector = {get: (name: Ng1Token): any => services[name], has: () => true};
expect(parseFactory(mockInjector)).toBe('bar');
});
});
describe('rootScopeFactory', () => {
it('should retrieve and return `$rootScope`', () => {
const services: {[key: string]: any} = {$rootScope: 'baz'};
const mockInjector = {get: (name: Ng1Token): any => services[name], has: () => true};
expect(rootScopeFactory(mockInjector)).toBe('baz');
});
});
});
| {
"end_byte": 2521,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/angular1_providers_spec.ts"
} |
angular/packages/upgrade/static/test/BUILD.bazel_0_947 | load("//tools:defaults.bzl", "karma_web_test_suite", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/upgrade/static/index.mjs",
deps = ["//packages/upgrade/static"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob([
"**/*.ts",
]),
deps = [
"//packages/core",
"//packages/core/testing",
"//packages/platform-browser",
"//packages/platform-browser-dynamic",
"//packages/platform-browser/testing",
"//packages/private/testing",
"//packages/upgrade/src/common",
"//packages/upgrade/src/common/test/helpers",
"//packages/upgrade/static",
],
)
karma_web_test_suite(
name = "test",
static_files = [
"//:angularjs_scripts",
],
deps = [
":test_lib",
],
)
| {
"end_byte": 947,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/BUILD.bazel"
} |
angular/packages/upgrade/static/test/integration/static_test_helpers.ts_0_1889 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgZone, PlatformRef, Type} from '@angular/core';
import {UpgradeModule} from '@angular/upgrade/static';
import * as angular from '../../../src/common/src/angular1';
import {$EXCEPTION_HANDLER, $ROOT_SCOPE} from '../../../src/common/src/constants';
export function bootstrap(
platform: PlatformRef,
Ng2Module: Type<{}>,
element: Element,
ng1Module: angular.IModule,
) {
// We bootstrap the Angular module first; then when it is ready (async) we bootstrap the AngularJS
// module on the bootstrap element (also ensuring that AngularJS errors will fail the test).
return platform.bootstrapModule(Ng2Module).then((ref) => {
const ngZone = ref.injector.get<NgZone>(NgZone);
const upgrade = ref.injector.get(UpgradeModule);
const failHardModule: any = ($provide: angular.IProvideService) => {
$provide.value($EXCEPTION_HANDLER, (err: any) => {
throw err;
});
};
// The `bootstrap()` helper is used for convenience in tests, so that we don't have to inject
// and call `upgrade.bootstrap()` on every Angular module.
// In order to closer emulate what happens in real application, ensure AngularJS is bootstrapped
// inside the Angular zone.
//
ngZone.run(() => upgrade.bootstrap(element, [failHardModule, ng1Module.name]));
return upgrade;
});
}
export function $apply(adapter: UpgradeModule, exp: angular.Ng1Expression) {
const $rootScope = adapter.$injector.get($ROOT_SCOPE) as angular.IRootScopeService;
$rootScope.$apply(exp);
}
export function $digest(adapter: UpgradeModule) {
const $rootScope = adapter.$injector.get($ROOT_SCOPE) as angular.IRootScopeService;
$rootScope.$digest();
}
| {
"end_byte": 1889,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/static_test_helpers.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_module_spec.ts_0_1293 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AfterContentChecked,
AfterContentInit,
AfterViewChecked,
AfterViewInit,
ApplicationRef,
Compiler,
Component,
destroyPlatform,
Directive,
DoCheck,
ElementRef,
getPlatform,
Inject,
Injectable,
Injector,
Input,
NgModule,
NgZone,
OnChanges,
OnDestroy,
OnInit,
StaticProvider,
Type,
ViewRef,
} from '@angular/core';
import {fakeAsync, tick, waitForAsync} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {downgradeComponent, downgradeModule, UpgradeComponent} from '@angular/upgrade/static';
import * as angular from '../../../src/common/src/angular1';
import {
$EXCEPTION_HANDLER,
$ROOT_SCOPE,
INJECTOR_KEY,
LAZY_MODULE_REF,
} from '../../../src/common/src/constants';
import {LazyModuleRef} from '../../../src/common/src/util';
import {
html,
multiTrim,
withEachNg1Version,
} from '../../../src/common/test/helpers/common_test_helpers';
import {setTempInjectorRef} from '../../src/angular1_providers'; | {
"end_byte": 1293,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_module_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_module_spec.ts_1295_10172 | withEachNg1Version(() => {
[true, false].forEach((propagateDigest) => {
describe(`lazy-load ng2 module (propagateDigest: ${propagateDigest})`, () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
it('should support multiple downgraded modules', waitForAsync(() => {
@Component({
selector: 'ng2A',
template: 'a',
standalone: false,
})
class Ng2ComponentA {}
@Component({
selector: 'ng2B',
template: 'b',
standalone: false,
})
class Ng2ComponentB {}
@NgModule({
declarations: [Ng2ComponentA],
imports: [BrowserModule],
})
class Ng2ModuleA {
ngDoBootstrap() {}
}
@NgModule({
declarations: [Ng2ComponentB],
imports: [BrowserModule],
})
class Ng2ModuleB {
ngDoBootstrap() {}
}
const doDowngradeModule = (module: Type<any>) => {
const bootstrapFn = (extraProviders: StaticProvider[]) =>
(getPlatform() || platformBrowserDynamic(extraProviders)).bootstrapModule(module);
return downgradeModule(bootstrapFn);
};
const downModA = doDowngradeModule(Ng2ModuleA);
const downModB = doDowngradeModule(Ng2ModuleB);
const ng1Module = angular
.module_('ng1', [downModA, downModB])
.directive(
'ng2A',
downgradeComponent({
component: Ng2ComponentA,
downgradedModule: downModA,
propagateDigest,
}),
)
.directive(
'ng2B',
downgradeComponent({
component: Ng2ComponentB,
downgradedModule: downModB,
propagateDigest,
}),
);
const element = html('<ng2-a></ng2-a> | <ng2-b></ng2-b>');
angular.bootstrap(element, [ng1Module.name]);
// Wait for the module to be bootstrapped.
setTimeout(() => expect(element.textContent).toBe('a | b'));
}));
it('should support downgrading modules by providing NgModule class to `downgradeModule` call', waitForAsync(() => {
@Component({
selector: 'ng2A',
template: 'a',
standalone: false,
})
class Ng2ComponentA {}
@Component({
selector: 'ng2B',
template: 'b',
standalone: false,
})
class Ng2ComponentB {}
@NgModule({
declarations: [Ng2ComponentA],
imports: [BrowserModule],
})
class Ng2ModuleA {
ngDoBootstrap() {}
}
@NgModule({
declarations: [Ng2ComponentB],
imports: [BrowserModule],
})
class Ng2ModuleB {
ngDoBootstrap() {}
}
const downModA = downgradeModule(Ng2ModuleA);
const downModB = downgradeModule(Ng2ModuleB);
const ng1Module = angular
.module_('ng1', [downModA, downModB])
.directive(
'ng2A',
downgradeComponent({
component: Ng2ComponentA,
downgradedModule: downModA,
propagateDigest,
}),
)
.directive(
'ng2B',
downgradeComponent({
component: Ng2ComponentB,
downgradedModule: downModB,
propagateDigest,
}),
);
const element = html('<ng2-a></ng2-a> | <ng2-b></ng2-b>');
angular.bootstrap(element, [ng1Module.name]);
// Wait for the module to be bootstrapped.
setTimeout(() => expect(element.textContent).toBe('a | b'));
}));
it('should support nesting components from different downgraded modules', waitForAsync(() => {
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentA extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Component({
selector: 'ng2A',
template: 'ng2A(<ng1A></ng1A>)',
standalone: false,
})
class Ng2ComponentA {}
@Component({
selector: 'ng2B',
template: 'ng2B',
standalone: false,
})
class Ng2ComponentB {}
@NgModule({
declarations: [Ng1ComponentA, Ng2ComponentA],
imports: [BrowserModule],
})
class Ng2ModuleA {
ngDoBootstrap() {}
}
@NgModule({
declarations: [Ng2ComponentB],
imports: [BrowserModule],
})
class Ng2ModuleB {
ngDoBootstrap() {}
}
const doDowngradeModule = (module: Type<any>) => {
const bootstrapFn = (extraProviders: StaticProvider[]) => {
const platformRef = getPlatform() || platformBrowserDynamic(extraProviders);
return platformRef.bootstrapModule(module);
};
return downgradeModule(bootstrapFn);
};
const downModA = doDowngradeModule(Ng2ModuleA);
const downModB = doDowngradeModule(Ng2ModuleB);
const ng1Module = angular
.module_('ng1', [downModA, downModB])
.directive('ng1A', () => ({template: 'ng1A(<ng2-b ng-if="showB"></ng2-b>)'}))
.directive(
'ng2A',
downgradeComponent({
component: Ng2ComponentA,
downgradedModule: downModA,
propagateDigest,
}),
)
.directive(
'ng2B',
downgradeComponent({
component: Ng2ComponentB,
downgradedModule: downModB,
propagateDigest,
}),
);
const element = html('<ng2-a></ng2-a>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
// Wait for module A to be bootstrapped.
setTimeout(() => {
// Wait for the upgraded component's `ngOnInit()`.
setTimeout(() => {
expect(element.textContent).toBe('ng2A(ng1A())');
$rootScope.$apply('showB = true');
// Wait for module B to be bootstrapped.
setTimeout(() => expect(element.textContent).toBe('ng2A(ng1A(ng2B))'));
});
});
}));
it('should support nesting components from different downgraded modules (via projection)', waitForAsync(() => {
@Component({
selector: 'ng2A',
template: 'ng2A(<ng-content></ng-content>)',
standalone: false,
})
class Ng2ComponentA {}
@Component({
selector: 'ng2B',
template: 'ng2B',
standalone: false,
})
class Ng2ComponentB {}
@NgModule({
declarations: [Ng2ComponentA],
imports: [BrowserModule],
})
class Ng2ModuleA {
ngDoBootstrap() {}
}
@NgModule({
declarations: [Ng2ComponentB],
imports: [BrowserModule],
})
class Ng2ModuleB {
ngDoBootstrap() {}
}
const doDowngradeModule = (module: Type<any>) => {
const bootstrapFn = (extraProviders: StaticProvider[]) => {
const platformRef = getPlatform() || platformBrowserDynamic(extraProviders);
return platformRef.bootstrapModule(module);
};
return downgradeModule(bootstrapFn);
};
const downModA = doDowngradeModule(Ng2ModuleA);
const downModB = doDowngradeModule(Ng2ModuleB);
const ng1Module = angular
.module_('ng1', [downModA, downModB])
.directive(
'ng2A',
downgradeComponent({
component: Ng2ComponentA,
downgradedModule: downModA,
propagateDigest,
}),
)
.directive(
'ng2B',
downgradeComponent({
component: Ng2ComponentB,
downgradedModule: downModB,
propagateDigest,
}),
);
const element = html('<ng2-a><ng2-b ng-if="showB"></ng2-b></ng2-a>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
// Wait for module A to be bootstrapped.
setTimeout(() => {
expect(element.textContent).toBe('ng2A()');
$rootScope.$apply('showB = true');
// Wait for module B to be bootstrapped.
setTimeout(() => expect(element.textContent).toBe('ng2A(ng2B)'));
});
})); | {
"end_byte": 10172,
"start_byte": 1295,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_module_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_module_spec.ts_10180_16854 | it('should support manually setting up a root module for all downgraded modules', fakeAsync(() => {
@Injectable({providedIn: 'root'})
class CounterService {
private static counter = 0;
value = ++CounterService.counter;
}
@Component({
selector: 'ng2A',
template: 'ng2A(Counter:{{ counter.value }} | <ng-content></ng-content>)',
standalone: false,
})
class Ng2ComponentA {
constructor(public counter: CounterService) {}
}
@Component({
selector: 'ng2B',
template: 'Counter:{{ counter.value }}',
standalone: false,
})
class Ng2ComponentB {
constructor(public counter: CounterService) {}
}
@NgModule({
declarations: [Ng2ComponentA],
})
class Ng2ModuleA {}
@NgModule({
declarations: [Ng2ComponentB],
})
class Ng2ModuleB {}
// "Empty" module that will serve as root for all downgraded modules,
// ensuring there will only be one instance for all injectables provided in "root".
@NgModule({
imports: [BrowserModule],
})
class Ng2ModuleRoot {
ngDoBootstrap() {}
}
let rootInjectorPromise: Promise<Injector> | null = null;
const doDowngradeModule = (module: Type<any>) => {
const bootstrapFn = (extraProviders: StaticProvider[]) => {
if (!rootInjectorPromise) {
rootInjectorPromise = platformBrowserDynamic(extraProviders)
.bootstrapModule(Ng2ModuleRoot)
.then((ref) => ref.injector);
}
return rootInjectorPromise.then((rootInjector) => {
const compiler = rootInjector.get(Compiler);
const moduleFactory = compiler.compileModuleSync(module);
return moduleFactory.create(rootInjector);
});
};
return downgradeModule(bootstrapFn);
};
const downModA = doDowngradeModule(Ng2ModuleA);
const downModB = doDowngradeModule(Ng2ModuleB);
const ng1Module = angular
.module_('ng1', [downModA, downModB])
.directive(
'ng2A',
downgradeComponent({
component: Ng2ComponentA,
downgradedModule: downModA,
propagateDigest,
}),
)
.directive(
'ng2B',
downgradeComponent({
component: Ng2ComponentB,
downgradedModule: downModB,
propagateDigest,
}),
);
const element = html(`
<ng2-a><ng2-b ng-if="showB1"></ng2-b></ng2-a>
<ng2-b ng-if="showB2"></ng2-b>
`);
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
tick(); // Wait for module A to be bootstrapped.
expect(multiTrim(element.textContent)).toBe('ng2A(Counter:1 | )');
// Nested component B should use the same `CounterService` instance.
$rootScope.$apply('showB1 = true');
tick(); // Wait for module B to be bootstrapped.
expect(multiTrim(element.children[0].textContent)).toBe('ng2A(Counter:1 | Counter:1)');
// Top-level component B should use the same `CounterService` instance.
$rootScope.$apply('showB2 = true');
tick();
expect(multiTrim(element.children[1].textContent)).toBe('Counter:1');
}));
it('should correctly traverse the injector tree of downgraded components', waitForAsync(() => {
@Component({
selector: 'ng2A',
template: 'ng2A(<ng-content></ng-content>)',
providers: [
{provide: 'FOO', useValue: 'CompA-foo'},
{provide: 'BAR', useValue: 'CompA-bar'},
],
standalone: false,
})
class Ng2ComponentA {}
@Component({
selector: 'ng2B',
template: ` FOO:{{ foo }} BAR:{{ bar }} BAZ:{{ baz }} QUX:{{ qux }} `,
providers: [{provide: 'FOO', useValue: 'CompB-foo'}],
standalone: false,
})
class Ng2ComponentB {
constructor(
@Inject('FOO') public foo: string,
@Inject('BAR') public bar: string,
@Inject('BAZ') public baz: string,
@Inject('QUX') public qux: string,
) {}
}
@NgModule({
declarations: [Ng2ComponentA, Ng2ComponentB],
imports: [BrowserModule],
providers: [
{provide: 'FOO', useValue: 'Mod-foo'},
{provide: 'BAR', useValue: 'Mod-bar'},
{provide: 'BAZ', useValue: 'Mod-baz'},
],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) => {
const platformRef =
getPlatform() ||
platformBrowserDynamic([
...extraProviders,
{provide: 'FOO', useValue: 'Plat-foo'},
{provide: 'BAR', useValue: 'Plat-bar'},
{provide: 'BAZ', useValue: 'Plat-baz'},
{provide: 'QUX', useValue: 'Plat-qux'},
]);
return platformRef.bootstrapModule(Ng2Module);
};
const downMod = downgradeModule(bootstrapFn);
const ng1Module = angular
.module_('ng1', [downMod])
.directive('ng2A', downgradeComponent({component: Ng2ComponentA, propagateDigest}))
.directive('ng2B', downgradeComponent({component: Ng2ComponentB, propagateDigest}));
const element = html(`
<ng2-a><ng2-b ng-if="showB1"></ng2-b></ng2-a>
<ng2-b ng-if="showB2"></ng2-b>
`);
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
// Wait for the module to be bootstrapped.
setTimeout(() => {
expect(multiTrim(element.textContent)).toBe('ng2A()');
// Nested component B.
$rootScope.$apply('showB1 = true');
expect(multiTrim(element.children[0].textContent)).toBe(
'ng2A( FOO:CompB-foo BAR:CompA-bar BAZ:Mod-baz QUX:Plat-qux )',
);
// Standalone component B.
$rootScope.$apply('showB2 = true');
expect(multiTrim(element.children[1].textContent)).toBe(
'FOO:CompB-foo BAR:Mod-bar BAZ:Mod-baz QUX:Plat-qux',
);
});
})); | {
"end_byte": 16854,
"start_byte": 10180,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_module_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_module_spec.ts_16862_23453 | it('should correctly traverse the injector tree of downgraded components (from different modules)', waitForAsync(() => {
@Component({
selector: 'ng2A',
template: 'ng2A(<ng-content></ng-content>)',
providers: [
{provide: 'FOO', useValue: 'CompA-foo'},
{provide: 'BAR', useValue: 'CompA-bar'},
],
standalone: false,
})
class Ng2ComponentA {}
@Component({
selector: 'ng2B',
template: ` FOO:{{ foo }} BAR:{{ bar }} BAZ:{{ baz }} QUX:{{ qux }} QUUX:{{ quux }} `,
providers: [{provide: 'FOO', useValue: 'CompB-foo'}],
standalone: false,
})
class Ng2ComponentB {
constructor(
@Inject('FOO') public foo: string,
@Inject('BAR') public bar: string,
@Inject('BAZ') public baz: string,
@Inject('QUX') public qux: string,
@Inject('QUUX') public quux: string,
) {}
}
@NgModule({
declarations: [Ng2ComponentA],
imports: [BrowserModule],
providers: [
{provide: 'FOO', useValue: 'ModA-foo'},
{provide: 'BAR', useValue: 'ModA-bar'},
{provide: 'BAZ', useValue: 'ModA-baz'},
{provide: 'QUX', useValue: 'ModA-qux'},
],
})
class Ng2ModuleA {
ngDoBootstrap() {}
}
@NgModule({
declarations: [Ng2ComponentB],
imports: [BrowserModule],
providers: [
{provide: 'FOO', useValue: 'ModB-foo'},
{provide: 'BAR', useValue: 'ModB-bar'},
{provide: 'BAZ', useValue: 'ModB-baz'},
],
})
class Ng2ModuleB {
ngDoBootstrap() {}
}
const doDowngradeModule = (module: Type<any>) => {
const bootstrapFn = (extraProviders: StaticProvider[]) => {
const platformRef =
getPlatform() ||
platformBrowserDynamic([
...extraProviders,
{provide: 'FOO', useValue: 'Plat-foo'},
{provide: 'BAR', useValue: 'Plat-bar'},
{provide: 'BAZ', useValue: 'Plat-baz'},
{provide: 'QUX', useValue: 'Plat-qux'},
{provide: 'QUUX', useValue: 'Plat-quux'},
]);
return platformRef.bootstrapModule(module);
};
return downgradeModule(bootstrapFn);
};
const downModA = doDowngradeModule(Ng2ModuleA);
const downModB = doDowngradeModule(Ng2ModuleB);
const ng1Module = angular
.module_('ng1', [downModA, downModB])
.directive(
'ng2A',
downgradeComponent({
component: Ng2ComponentA,
downgradedModule: downModA,
propagateDigest,
}),
)
.directive(
'ng2B',
downgradeComponent({
component: Ng2ComponentB,
downgradedModule: downModB,
propagateDigest,
}),
);
const element = html(`
<ng2-a><ng2-b ng-if="showB1"></ng2-b></ng2-a>
<ng2-b ng-if="showB2"></ng2-b>
`);
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
// Wait for module A to be bootstrapped.
setTimeout(() => {
expect(multiTrim(element.textContent)).toBe('ng2A()');
// Nested component B.
$rootScope.$apply('showB1 = true');
// Wait for module B to be bootstrapped.
setTimeout(() => {
// It is debatable, whether the order of traversal should be:
// CompB > CompA > ModB > ModA > Plat (similar to how lazy-loaded components
// work)
expect(multiTrim(element.children[0].textContent)).toBe(
'ng2A( FOO:CompB-foo BAR:CompA-bar BAZ:ModB-baz QUX:Plat-qux QUUX:Plat-quux )',
);
// Standalone component B.
$rootScope.$apply('showB2 = true');
expect(multiTrim(element.children[1].textContent)).toBe(
'FOO:CompB-foo BAR:ModB-bar BAZ:ModB-baz QUX:Plat-qux QUUX:Plat-quux',
);
});
});
}));
it('should support downgrading a component and propagate inputs', waitForAsync(() => {
@Component({
selector: 'ng2A',
template: 'a({{ value }}) | <ng2B [value]="value"></ng2B>',
standalone: false,
})
class Ng2AComponent {
@Input() value = -1;
}
@Component({
selector: 'ng2B',
template: 'b({{ value }})',
standalone: false,
})
class Ng2BComponent {
@Input() value = -2;
}
@NgModule({
declarations: [Ng2AComponent, Ng2BComponent],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('ng2', downgradeComponent({component: Ng2AComponent, propagateDigest}))
.run([
'$rootScope',
($rootScope: angular.IRootScopeService) => ($rootScope['value'] = 0),
]);
const element = html('<div><ng2 [value]="value" ng-if="loadNg2"></ng2></div>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
expect(element.textContent).toBe('');
expect(() => $injector.get(INJECTOR_KEY)).toThrowError();
$rootScope.$apply('value = 1');
expect(element.textContent).toBe('');
expect(() => $injector.get(INJECTOR_KEY)).toThrowError();
$rootScope.$apply('loadNg2 = true');
expect(element.textContent).toBe('');
expect(() => $injector.get(INJECTOR_KEY)).toThrowError();
// Wait for the module to be bootstrapped.
setTimeout(() => {
expect(() => $injector.get(INJECTOR_KEY)).not.toThrow();
// Wait for `$evalAsync()` to propagate inputs.
setTimeout(() => expect(element.textContent).toBe('a(1) | b(1)'));
});
})); | {
"end_byte": 23453,
"start_byte": 16862,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_module_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_module_spec.ts_23461_30762 | it('should support using an upgraded service', waitForAsync(() => {
@Injectable()
class Ng2Service {
constructor(@Inject('ng1Value') private ng1Value: string) {}
getValue = () => `${this.ng1Value}-bar`;
}
@Component({
selector: 'ng2',
template: '{{ value }}',
standalone: false,
})
class Ng2Component {
value: string;
constructor(ng2Service: Ng2Service) {
this.value = ng2Service.getValue();
}
}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
providers: [
Ng2Service,
{
provide: 'ng1Value',
useFactory: (i: angular.IInjectorService) => i.get('ng1Value'),
deps: ['$injector'],
},
],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest}))
.value('ng1Value', 'foo');
const element = html('<div><ng2 ng-if="loadNg2"></ng2></div>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
expect(element.textContent).toBe('');
expect(() => $injector.get(INJECTOR_KEY)).toThrowError();
$rootScope.$apply('loadNg2 = true');
expect(element.textContent).toBe('');
expect(() => $injector.get(INJECTOR_KEY)).toThrowError();
// Wait for the module to be bootstrapped.
setTimeout(() => {
expect(() => $injector.get(INJECTOR_KEY)).not.toThrow();
// Wait for `$evalAsync()` to propagate inputs.
setTimeout(() => expect(element.textContent).toBe('foo-bar'));
});
}));
it('should create components inside the Angular zone', waitForAsync(() => {
@Component({
selector: 'ng2',
template: 'In the zone: {{ inTheZone }}',
standalone: false,
})
class Ng2Component {
private inTheZone = false;
constructor() {
this.inTheZone = NgZone.isInAngularZone();
}
}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest}));
const element = html('<ng2></ng2>');
angular.bootstrap(element, [ng1Module.name]);
// Wait for the module to be bootstrapped.
setTimeout(() => {
// Wait for `$evalAsync()` to propagate inputs.
setTimeout(() => expect(element.textContent).toBe('In the zone: true'));
});
}));
it('should destroy components inside the Angular zone', waitForAsync(() => {
let destroyedInTheZone = false;
@Component({
selector: 'ng2',
template: '',
standalone: false,
})
class Ng2Component implements OnDestroy {
ngOnDestroy() {
destroyedInTheZone = NgZone.isInAngularZone();
}
}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest}));
const element = html('<ng2 ng-if="!hideNg2"></ng2>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
// Wait for the module to be bootstrapped.
setTimeout(() => {
$rootScope.$apply('hideNg2 = true');
expect(destroyedInTheZone).toBe(true);
});
}));
it('should propagate input changes inside the Angular zone', waitForAsync(() => {
let ng2Component: Ng2Component;
@Component({
selector: 'ng2',
template: '',
standalone: false,
})
class Ng2Component implements OnChanges {
@Input() attrInput = 'foo';
@Input() propInput = 'foo';
constructor() {
ng2Component = this;
}
ngOnChanges() {}
}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest}))
.run([
'$rootScope',
($rootScope: angular.IRootScopeService) => {
$rootScope['attrVal'] = 'bar';
$rootScope['propVal'] = 'bar';
},
]);
const element = html('<ng2 attr-input="{{ attrVal }}" [prop-input]="propVal"></ng2>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
setTimeout(() => {
// Wait for the module to be bootstrapped.
setTimeout(() => {
// Wait for `$evalAsync()` to propagate inputs.
const expectToBeInNgZone = () => expect(NgZone.isInAngularZone()).toBe(true);
const changesSpy = spyOn(ng2Component, 'ngOnChanges').and.callFake(expectToBeInNgZone);
expect(ng2Component.attrInput).toBe('bar');
expect(ng2Component.propInput).toBe('bar');
$rootScope.$apply('attrVal = "baz"');
expect(ng2Component.attrInput).toBe('baz');
expect(ng2Component.propInput).toBe('bar');
expect(changesSpy).toHaveBeenCalledTimes(1);
$rootScope.$apply('propVal = "qux"');
expect(ng2Component.attrInput).toBe('baz');
expect(ng2Component.propInput).toBe('qux');
expect(changesSpy).toHaveBeenCalledTimes(2);
});
});
})); | {
"end_byte": 30762,
"start_byte": 23461,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_module_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_module_spec.ts_30770_36548 | it('should create and destroy nested, asynchronously instantiated components inside the Angular zone', waitForAsync(() => {
let createdInTheZone = false;
let destroyedInTheZone = false;
@Component({
selector: 'test',
template: '',
standalone: false,
})
class TestComponent implements OnDestroy {
constructor() {
createdInTheZone = NgZone.isInAngularZone();
}
ngOnDestroy() {
destroyedInTheZone = NgZone.isInAngularZone();
}
}
@Component({
selector: 'wrapper',
template: '<ng-content></ng-content>',
standalone: false,
})
class WrapperComponent {}
@NgModule({
declarations: [TestComponent, WrapperComponent],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('test', downgradeComponent({component: TestComponent, propagateDigest}))
.directive('wrapper', downgradeComponent({component: WrapperComponent, propagateDigest}));
// Important: `ng-if` makes `<test>` render asynchronously.
const element = html('<wrapper><test ng-if="showNg2"></test></wrapper>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
// Wait for the module to be bootstrapped.
setTimeout(() => {
// Create nested component asynchronously.
expect(createdInTheZone).toBe(false);
$rootScope.$apply('showNg2 = true');
expect(createdInTheZone).toBe(true);
// Destroy nested component asynchronously.
expect(destroyedInTheZone).toBe(false);
$rootScope.$apply('showNg2 = false');
expect(destroyedInTheZone).toBe(true);
});
}));
it('should wire up the component for change detection', waitForAsync(() => {
@Component({
selector: 'ng2',
template: '{{ count }}<button (click)="increment()"></button>',
standalone: false,
})
class Ng2Component {
private count = 0;
increment() {
++this.count;
}
}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest}));
const element = html('<ng2></ng2>');
angular.bootstrap(element, [ng1Module.name]);
setTimeout(() => {
// Wait for the module to be bootstrapped.
setTimeout(() => {
// Wait for `$evalAsync()` to propagate inputs.
const button = element.querySelector('button')!;
expect(element.textContent).toBe('0');
button.click();
expect(element.textContent).toBe('1');
button.click();
expect(element.textContent).toBe('2');
});
});
}));
it('should wire up nested, asynchronously instantiated components for change detection', waitForAsync(() => {
@Component({
selector: 'test',
template: '{{ count }}<button (click)="increment()"></button>',
standalone: false,
})
class TestComponent {
count = 0;
increment() {
++this.count;
}
}
@Component({
selector: 'wrapper',
template: '<ng-content></ng-content>',
standalone: false,
})
class WrapperComponent {}
@NgModule({
declarations: [TestComponent, WrapperComponent],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('test', downgradeComponent({component: TestComponent, propagateDigest}))
.directive('wrapper', downgradeComponent({component: WrapperComponent, propagateDigest}));
// Important: `ng-if` makes `<test>` render asynchronously.
const element = html('<wrapper><test ng-if="showNg2"></test></wrapper>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
// Wait for the module to be bootstrapped.
setTimeout(() => {
// Create nested component asynchronously.
$rootScope.$apply('showNg2 = true');
const button = element.querySelector('button')!;
expect(element.textContent).toBe('0');
button.click();
expect(element.textContent).toBe('1');
button.click();
expect(element.textContent).toBe('2');
});
})); | {
"end_byte": 36548,
"start_byte": 30770,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_module_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_module_spec.ts_36556_45004 | it('should run the lifecycle hooks in the correct order', waitForAsync(() => {
const logs: string[] = [];
let rootScope: angular.IRootScopeService;
@Component({
selector: 'ng2',
template: `
{{ value }}
<button (click)="value = 'qux'"></button>
<ng-content></ng-content>
`,
standalone: false,
})
class Ng2Component
implements
AfterContentChecked,
AfterContentInit,
AfterViewChecked,
AfterViewInit,
DoCheck,
OnChanges,
OnDestroy,
OnInit
{
@Input() value = 'foo';
ngAfterContentChecked() {
this.log('AfterContentChecked');
}
ngAfterContentInit() {
this.log('AfterContentInit');
}
ngAfterViewChecked() {
this.log('AfterViewChecked');
}
ngAfterViewInit() {
this.log('AfterViewInit');
}
ngDoCheck() {
this.log('DoCheck');
}
ngOnChanges() {
this.log('OnChanges');
}
ngOnDestroy() {
this.log('OnDestroy');
}
ngOnInit() {
this.log('OnInit');
}
private log(hook: string) {
logs.push(`${hook}(${this.value})`);
}
}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest}))
.run(($rootScope: angular.IRootScopeService) => {
rootScope = $rootScope;
rootScope['value'] = 'bar';
});
const element = html('<div><ng2 value="{{ value }}" ng-if="!hideNg2">Content</ng2></div>');
angular.bootstrap(element, [ng1Module.name]);
setTimeout(() => {
// Wait for the module to be bootstrapped.
setTimeout(() => {
// Wait for `$evalAsync()` to propagate inputs.
const button = element.querySelector('button')!;
// Once initialized.
expect(multiTrim(element.textContent)).toBe('bar Content');
expect(logs).toEqual([
// `ngOnChanges()` call triggered directly through the `inputChanges`
// $watcher.
'OnChanges(bar)',
// Initial CD triggered directly through the `detectChanges()` or
// `inputChanges`
// $watcher (for `propagateDigest` true/false respectively).
'OnInit(bar)',
'DoCheck(bar)',
'AfterContentInit(bar)',
'AfterContentChecked(bar)',
'AfterViewInit(bar)',
'AfterViewChecked(bar)',
...(propagateDigest
? [
// CD triggered directly through the `detectChanges()` $watcher (2nd
// $digest).
'DoCheck(bar)',
'AfterContentChecked(bar)',
'AfterViewChecked(bar)',
]
: []),
// CD triggered due to entering/leaving the NgZone (in `downgradeFn()`).
'DoCheck(bar)',
'AfterContentChecked(bar)',
'AfterViewChecked(bar)',
]);
logs.length = 0;
// Change inputs and run `$digest`.
rootScope.$apply('value = "baz"');
expect(multiTrim(element.textContent)).toBe('baz Content');
expect(logs).toEqual([
// `ngOnChanges()` call triggered directly through the `inputChanges`
// $watcher.
'OnChanges(baz)',
// `propagateDigest: true` (3 CD runs):
// - CD triggered due to entering/leaving the NgZone (in `inputChanges`
// $watcher).
// - CD triggered directly through the `detectChanges()` $watcher.
// - CD triggered due to entering/leaving the NgZone (in `detectChanges`
// $watcher).
// `propagateDigest: false` (2 CD runs):
// - CD triggered directly through the `inputChanges` $watcher.
// - CD triggered due to entering/leaving the NgZone (in `inputChanges`
// $watcher).
'DoCheck(baz)',
'AfterContentChecked(baz)',
'AfterViewChecked(baz)',
'DoCheck(baz)',
'AfterContentChecked(baz)',
'AfterViewChecked(baz)',
...(propagateDigest
? ['DoCheck(baz)', 'AfterContentChecked(baz)', 'AfterViewChecked(baz)']
: []),
]);
logs.length = 0;
// Run `$digest` (without changing inputs).
rootScope.$digest();
expect(multiTrim(element.textContent)).toBe('baz Content');
expect(logs).toEqual(
propagateDigest
? [
// CD triggered directly through the `detectChanges()` $watcher.
'DoCheck(baz)',
'AfterContentChecked(baz)',
'AfterViewChecked(baz)',
// CD triggered due to entering/leaving the NgZone (in the above
// $watcher).
'DoCheck(baz)',
'AfterContentChecked(baz)',
'AfterViewChecked(baz)',
]
: [],
);
logs.length = 0;
// Trigger change detection (without changing inputs).
button.click();
expect(multiTrim(element.textContent)).toBe('qux Content');
expect(logs).toEqual([
'DoCheck(qux)',
'AfterContentChecked(qux)',
'AfterViewChecked(qux)',
]);
logs.length = 0;
// Destroy the component.
rootScope.$apply('hideNg2 = true');
expect(logs).toEqual(['OnDestroy(qux)']);
logs.length = 0;
});
});
}));
it('should detach hostViews from the ApplicationRef once destroyed', waitForAsync(() => {
let ng2Component: Ng2Component;
@Component({
selector: 'ng2',
template: '',
standalone: false,
})
class Ng2Component {
constructor(public appRef: ApplicationRef) {
ng2Component = this;
spyOn(appRef, 'attachView').and.callThrough();
spyOn(appRef, 'detachView').and.callThrough();
}
}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest}));
const element = html('<ng2 ng-if="!hideNg2"></ng2>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
setTimeout(() => {
// Wait for the module to be bootstrapped.
setTimeout(() => {
// Wait for the hostView to be attached (during the `$digest`).
const hostView: ViewRef = (
ng2Component.appRef.attachView as jasmine.Spy
).calls.mostRecent().args[0];
expect(hostView.destroyed).toBe(false);
$rootScope.$apply('hideNg2 = true');
expect(hostView.destroyed).toBe(true);
expect(ng2Component.appRef.detachView).toHaveBeenCalledWith(hostView);
});
});
})); | {
"end_byte": 45004,
"start_byte": 36556,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_module_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_module_spec.ts_45012_51471 | it('should properly run cleanup when a downgraded component is destroyed', waitForAsync(() => {
let destroyed = false;
@Component({
selector: 'ng2',
template: '<ul><li>test1</li><li>test2</li></ul>',
standalone: false,
})
class Ng2Component implements OnDestroy {
ngOnDestroy() {
destroyed = true;
}
}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest}));
const element = html('<div><div ng-if="!hideNg2"><ng2></ng2></div></div>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
setTimeout(() => {
// Wait for the module to be bootstrapped.
const ng2Element = angular.element(element.querySelector('ng2') as Element);
const ng2Descendants = Array.from(element.querySelectorAll('ng2 li')).map(
angular.element,
);
let ng2ElementDestroyed = false;
let ng2DescendantsDestroyed = [false, false];
ng2Element.data!('test', 42);
ng2Descendants.forEach((elem, i) => elem.data!('test', i));
ng2Element.on!('$destroy', () => (ng2ElementDestroyed = true));
ng2Descendants.forEach((elem, i) =>
elem.on!('$destroy', () => (ng2DescendantsDestroyed[i] = true)),
);
expect(element.textContent).toBe('test1test2');
expect(destroyed).toBe(false);
expect(ng2Element.data!('test')).toBe(42);
ng2Descendants.forEach((elem, i) => expect(elem.data!('test')).toBe(i));
expect(ng2ElementDestroyed).toBe(false);
expect(ng2DescendantsDestroyed).toEqual([false, false]);
$rootScope.$apply('hideNg2 = true');
expect(element.textContent).toBe('');
expect(destroyed).toBe(true);
expect(ng2Element.data!('test')).toBeUndefined();
ng2Descendants.forEach((elem) => expect(elem.data!('test')).toBeUndefined());
expect(ng2ElementDestroyed).toBe(true);
expect(ng2DescendantsDestroyed).toEqual([true, true]);
});
}));
it('should only retrieve the Angular zone once (and cache it for later use)', fakeAsync(() => {
let count = 0;
let getNgZoneCount = 0;
@Component({
selector: 'ng2',
template: 'Count: {{ count }} | In the zone: {{ inTheZone }}',
standalone: false,
})
class Ng2Component {
private count = ++count;
private inTheZone = false;
constructor() {
this.inTheZone = NgZone.isInAngularZone();
}
}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {
constructor(injector: Injector) {
const originalGet = injector.get;
injector.get = function (token: any) {
if (arguments[0] === NgZone) ++getNgZoneCount;
return originalGet.apply(injector, arguments as any);
};
}
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest}));
const element = html('<div><ng2 ng-if="showNg2"></ng2></div>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService;
$rootScope.$apply('showNg2 = true');
tick(0); // Wait for the module to be bootstrapped and `$evalAsync()` to
// propagate inputs.
const injector = ($injector.get(LAZY_MODULE_REF) as LazyModuleRef).injector!;
const injectorGet = injector.get;
spyOn(injector, 'get').and.callFake((...args: [any, any?]) => {
expect(args[0]).not.toBe(NgZone);
return injectorGet.apply(injector, args);
});
expect(element.textContent).toBe('Count: 1 | In the zone: true');
$rootScope.$apply('showNg2 = false');
expect(element.textContent).toBe('');
$rootScope.$apply('showNg2 = true');
tick(0); // Wait for `$evalAsync()` to propagate inputs.
expect(element.textContent).toBe('Count: 2 | In the zone: true');
$rootScope.$destroy();
}));
it("should give access to both injectors in the Angular module's constructor", waitForAsync(() => {
let $injectorFromNg2: angular.IInjectorService | null = null;
@Component({
selector: 'ng2',
template: '',
standalone: false,
})
class Ng2Component {}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {
constructor(injector: Injector) {
$injectorFromNg2 = injector.get<angular.IInjectorService>('$injector' as any);
}
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest}));
const element = html('<ng2></ng2>');
const $injectorFromNg1 = angular.bootstrap(element, [ng1Module.name]);
// Wait for the module to be bootstrapped.
setTimeout(() => expect($injectorFromNg2).toBe($injectorFromNg1));
})); | {
"end_byte": 51471,
"start_byte": 45012,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_module_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_module_spec.ts_51479_60135 | it('should destroy the AngularJS app when `PlatformRef` is destroyed', waitForAsync(() => {
@Component({
selector: 'ng2',
template: '<span>NG2</span>',
standalone: false,
})
class Ng2Component {}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowserDynamic(extraProviders).bootstrapModule(Ng2Module);
const lazyModuleName = downgradeModule<Ng2Module>(bootstrapFn);
const ng1Module = angular
.module_('ng1', [lazyModuleName])
.component('ng1', {template: '<ng2></ng2>'})
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest}));
const element = html('<div><ng1></ng1></div>');
const $injector = angular.bootstrap(element, [ng1Module.name]);
setTimeout(() => {
// Wait for the module to be bootstrapped.
const $rootScope: angular.IRootScopeService = $injector.get($ROOT_SCOPE);
const rootScopeDestroySpy = spyOn($rootScope, '$destroy');
const appElem = angular.element(element);
const ng1Elem = angular.element(element.querySelector('ng1') as Element);
const ng2Elem = angular.element(element.querySelector('ng2') as Element);
const ng2ChildElem = angular.element(element.querySelector('ng2 span') as Element);
// Attach data to all elements.
appElem.data!('testData', 1);
ng1Elem.data!('testData', 2);
ng2Elem.data!('testData', 3);
ng2ChildElem.data!('testData', 4);
// Verify data can be retrieved.
expect(appElem.data!('testData')).toBe(1);
expect(ng1Elem.data!('testData')).toBe(2);
expect(ng2Elem.data!('testData')).toBe(3);
expect(ng2ChildElem.data!('testData')).toBe(4);
expect(rootScopeDestroySpy).not.toHaveBeenCalled();
// Destroy `PlatformRef`.
getPlatform()?.destroy();
// Verify `$rootScope` has been destroyed and data has been cleaned up.
expect(rootScopeDestroySpy).toHaveBeenCalled();
expect(appElem.data!('testData')).toBeUndefined();
expect(ng1Elem.data!('testData')).toBeUndefined();
expect(ng2Elem.data!('testData')).toBeUndefined();
expect(ng2ChildElem.data!('testData')).toBeUndefined();
});
}));
describe('(common error)', () => {
let Ng2CompA: Type<any>;
let Ng2CompB: Type<any>;
let downModA: string;
let downModB: string;
let errorSpy: jasmine.Spy;
const doDowngradeModule = (module: Type<any>) => {
const bootstrapFn = (extraProviders: StaticProvider[]) =>
(getPlatform() || platformBrowserDynamic(extraProviders)).bootstrapModule(module);
return downgradeModule(bootstrapFn);
};
beforeEach(() => {
@Component({
selector: 'ng2A',
template: 'a',
standalone: false,
})
class Ng2ComponentA {}
@Component({
selector: 'ng2B',
template: 'b',
standalone: false,
})
class Ng2ComponentB {}
@NgModule({
declarations: [Ng2ComponentA],
imports: [BrowserModule],
})
class Ng2ModuleA {
ngDoBootstrap() {}
}
@NgModule({
declarations: [Ng2ComponentB],
imports: [BrowserModule],
})
class Ng2ModuleB {
ngDoBootstrap() {}
}
Ng2CompA = Ng2ComponentA;
Ng2CompB = Ng2ComponentB;
downModA = doDowngradeModule(Ng2ModuleA);
downModB = doDowngradeModule(Ng2ModuleB);
errorSpy = jasmine.createSpy($EXCEPTION_HANDLER);
});
// In the tests below, some of the components' bootstrap process is interrupted by an error.
// If the bootstrap process for other components/modules is not completed in time, there is
// a chance that some global state is retained, possibly messing subsequent tests.
// Explicitly clean up after each test to prevent that.
afterEach(() => setTempInjectorRef(null!));
it('should throw if no downgraded module is included', waitForAsync(() => {
const ng1Module = angular
.module_('ng1', [])
.value($EXCEPTION_HANDLER, errorSpy)
.directive(
'ng2A',
downgradeComponent({
component: Ng2CompA,
downgradedModule: downModA,
propagateDigest,
}),
)
.directive(
'ng2B',
downgradeComponent({
component: Ng2CompB,
propagateDigest,
}),
);
const element = html('<ng2-a></ng2-a> | <ng2-b></ng2-b>');
angular.bootstrap(element, [ng1Module.name]);
expect(errorSpy).toHaveBeenCalledTimes(2);
expect(errorSpy).toHaveBeenCalledWith(
new Error(
"Error while instantiating component 'Ng2ComponentA': Not a valid " +
"'@angular/upgrade' application.\n" +
'Did you forget to downgrade an Angular module or include it in the AngularJS ' +
'application?',
),
'<ng2-a>',
);
expect(errorSpy).toHaveBeenCalledWith(
new Error(
"Error while instantiating component 'Ng2ComponentB': Not a valid " +
"'@angular/upgrade' application.\n" +
'Did you forget to downgrade an Angular module or include it in the AngularJS ' +
'application?',
),
'<ng2-b>',
);
}));
it('should throw if the corresponding downgraded module is not included', waitForAsync(() => {
const ng1Module = angular
.module_('ng1', [downModA])
.value($EXCEPTION_HANDLER, errorSpy)
.directive(
'ng2A',
downgradeComponent({
component: Ng2CompA,
downgradedModule: downModA,
propagateDigest,
}),
)
.directive(
'ng2B',
downgradeComponent({
component: Ng2CompB,
downgradedModule: downModB,
propagateDigest,
}),
);
const element = html('<ng2-a></ng2-a> | <ng2-b></ng2-b>');
angular.bootstrap(element, [ng1Module.name]);
expect(errorSpy).toHaveBeenCalledTimes(1);
expect(errorSpy).toHaveBeenCalledWith(
new Error(
"Error while instantiating component 'Ng2ComponentB': Unable to find the " +
'specified downgraded module.\n' +
'Did you forget to downgrade an Angular module or include it in the AngularJS ' +
'application?',
),
'<ng2-b>',
);
}));
it('should throw if `downgradedModule` is not specified and there are multiple downgraded modules', waitForAsync(() => {
const ng1Module = angular
.module_('ng1', [downModA, downModB])
.value($EXCEPTION_HANDLER, errorSpy)
.directive(
'ng2A',
downgradeComponent({
component: Ng2CompA,
downgradedModule: downModA,
propagateDigest,
}),
)
.directive(
'ng2B',
downgradeComponent({
component: Ng2CompB,
propagateDigest,
}),
);
const element = html('<ng2-a></ng2-a> | <ng2-b></ng2-b>');
angular.bootstrap(element, [ng1Module.name]);
expect(errorSpy).toHaveBeenCalledTimes(1);
expect(errorSpy).toHaveBeenCalledWith(
new Error(
"Error while instantiating component 'Ng2ComponentB': 'downgradedModule' not " +
'specified.\n' +
'This application contains more than one downgraded Angular module, thus you need ' +
"to always specify 'downgradedModule' when downgrading components and " +
'injectables.',
),
'<ng2-b>',
);
}));
});
});
});
}); | {
"end_byte": 60135,
"start_byte": 51479,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_module_spec.ts"
} |
angular/packages/upgrade/static/test/integration/testability_spec.ts_0_4461 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {destroyPlatform, NgModule, Testability, NgZone} from '@angular/core';
import {fakeAsync, flush, tick} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {UpgradeModule} from '@angular/upgrade/static';
import * as angular from '../../../src/common/src/angular1';
import {html, withEachNg1Version} from '../../../src/common/test/helpers/common_test_helpers';
import {bootstrap} from './static_test_helpers';
withEachNg1Version(() => {
describe('testability', () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
@NgModule({imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
it('should handle deferred bootstrap', fakeAsync(() => {
let applicationRunning = false;
let stayedInTheZone: boolean = undefined!;
const ng1Module = angular.module_('ng1', []).run(() => {
applicationRunning = true;
stayedInTheZone = NgZone.isInAngularZone();
});
const element = html('<div></div>');
window.name = 'NG_DEFER_BOOTSTRAP!' + window.name;
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module);
setTimeout(() => {
(<any>window).angular.resumeBootstrap();
}, 100);
expect(applicationRunning).toEqual(false);
tick(100);
expect(applicationRunning).toEqual(true);
expect(stayedInTheZone).toEqual(true);
}));
it('should propagate return value of resumeBootstrap', fakeAsync(() => {
const ng1Module = angular.module_('ng1', []);
let a1Injector: angular.IInjectorService | undefined;
ng1Module.run([
'$injector',
function ($injector: angular.IInjectorService) {
a1Injector = $injector;
},
]);
const element = html('<div></div>');
window.name = 'NG_DEFER_BOOTSTRAP!' + window.name;
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module);
tick(100);
const value = (<any>window).angular.resumeBootstrap();
expect(value).toBe(a1Injector);
flush();
}));
it('should wait for ng2 testability', fakeAsync(() => {
const ng1Module = angular.module_('ng1', []);
const element = html('<div></div>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
const zone = upgrade.injector.get(NgZone);
let ng2Stable = false;
let ng1Stable = false;
zone.run(() => {
setTimeout(() => {
ng2Stable = true;
}, 100);
});
angular.getTestability(element).whenStable(() => {
ng1Stable = true;
});
expect(ng1Stable).toEqual(false);
expect(ng2Stable).toEqual(false);
tick(100);
expect(ng1Stable).toEqual(true);
expect(ng2Stable).toEqual(true);
});
}));
it('should not wait for $interval', fakeAsync(() => {
const ng1Module = angular.module_('ng1', []);
const element = html('<div></div>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
const ng2Testability: Testability = upgrade.injector.get(Testability);
const $interval: angular.IIntervalService = upgrade.$injector.get('$interval');
let ng2Stable = false;
let intervalDone = false;
const id = $interval(
(arg: string) => {
// should only be called once
expect(intervalDone).toEqual(false);
intervalDone = true;
expect(NgZone.isInAngularZone()).toEqual(true);
expect(arg).toEqual('passed argument');
},
200,
0,
true,
'passed argument',
);
ng2Testability.whenStable(() => {
ng2Stable = true;
});
tick(100);
expect(intervalDone).toEqual(false);
expect(ng2Stable).toEqual(true);
tick(200);
expect(intervalDone).toEqual(true);
expect($interval.cancel(id)).toEqual(true);
// Interval should not fire after cancel
tick(200);
});
}));
});
});
| {
"end_byte": 4461,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/testability_spec.ts"
} |
angular/packages/upgrade/static/test/integration/change_detection_spec.ts_0_8061 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
destroyPlatform,
Directive,
ElementRef,
Injector,
Input,
NgModule,
NgZone,
SimpleChanges,
} from '@angular/core';
import {waitForAsync} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {downgradeComponent, UpgradeComponent, UpgradeModule} from '@angular/upgrade/static';
import * as angular from '../../../src/common/src/angular1';
import {html, withEachNg1Version} from '../../../src/common/test/helpers/common_test_helpers';
import {bootstrap} from './static_test_helpers';
withEachNg1Version(() => {
describe('change-detection', () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
it('should not break if a $digest is already in progress', waitForAsync(() => {
const element = html('<my-app></my-app>');
@Component({
selector: 'my-app',
template: '',
standalone: false,
})
class AppComponent {}
@NgModule({declarations: [AppComponent], imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('myApp', downgradeComponent({component: AppComponent}));
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService;
const ngZone: NgZone = upgrade.ngZone;
// Wrap in a setTimeout to ensure all bootstrap operations have completed.
setTimeout(
// Run inside the Angular zone, so that operations such as emitting
// `onMicrotaskEmpty` do not trigger entering/existing the zone (and thus another
// `$digest`). This also closer simulates what would happen in a real app.
() =>
ngZone.run(() => {
const digestSpy = spyOn($rootScope, '$digest').and.callThrough();
// Step 1: Ensure `$digest` is run on `onMicrotaskEmpty`.
ngZone.onMicrotaskEmpty.emit(null);
expect(digestSpy).toHaveBeenCalledTimes(1);
digestSpy.calls.reset();
// Step 2: Cause the issue.
$rootScope.$apply(() => ngZone.onMicrotaskEmpty.emit(null));
// With the fix, `$digest` will only be run once (for `$apply()`).
// Without the fix, `$digest()` would have been run an extra time
// (`onMicrotaskEmpty`).
expect(digestSpy).toHaveBeenCalledTimes(1);
digestSpy.calls.reset();
// Step 3: Ensure that `$digest()` is still executed on `onMicrotaskEmpty`.
ngZone.onMicrotaskEmpty.emit(null);
expect(digestSpy).toHaveBeenCalledTimes(1);
}),
0,
);
});
}));
it('should interleave scope and component expressions', waitForAsync(() => {
const log: string[] = [];
const l = (value: string) => {
log.push(value);
return value + ';';
};
@Directive({
selector: 'ng1a',
standalone: false,
})
class Ng1aComponent extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1a', elementRef, injector);
}
}
@Directive({
selector: 'ng1b',
standalone: false,
})
class Ng1bComponent extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1b', elementRef, injector);
}
}
@Component({
selector: 'ng2',
template: `{{ l('2A') }}<ng1a></ng1a>{{ l('2B') }}<ng1b></ng1b>{{ l('2C') }}`,
standalone: false,
})
class Ng2Component {
l = l;
}
@NgModule({
declarations: [Ng1aComponent, Ng1bComponent, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng1a', () => ({template: "{{ l('ng1a') }}"}))
.directive('ng1b', () => ({template: "{{ l('ng1b') }}"}))
.directive('ng2', downgradeComponent({component: Ng2Component}))
.run(($rootScope: angular.IRootScopeService) => {
$rootScope['l'] = l;
$rootScope['reset'] = () => (log.length = 0);
});
const element = html("<div>{{reset(); l('1A');}}<ng2>{{l('1B')}}</ng2>{{l('1C')}}</div>");
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(document.body.textContent).toEqual('1A;2A;ng1a;2B;ng1b;2C;1C;');
expect(log).toEqual(['1A', '1C', '2A', '2B', '2C', 'ng1a', 'ng1b']);
});
}));
it('should propagate changes to a downgraded component inside the ngZone', waitForAsync(() => {
const element = html('<my-app></my-app>');
let appComponent: AppComponent;
@Component({
selector: 'my-app',
template: '<my-child [value]="value"></my-child>',
standalone: false,
})
class AppComponent {
value?: number;
constructor() {
appComponent = this;
}
}
@Component({
selector: 'my-child',
template: '<div>{{ valueFromPromise }}</div>',
standalone: false,
})
class ChildComponent {
valueFromPromise?: number;
@Input()
set value(v: number) {
expect(NgZone.isInAngularZone()).toBe(true);
}
constructor(private zone: NgZone) {}
ngOnChanges(changes: SimpleChanges) {
if (changes['value'].isFirstChange()) return;
this.zone.onMicrotaskEmpty.subscribe(() => {
expect(element.textContent).toEqual('5');
});
// Create a micro-task to update the value to be rendered asynchronously.
queueMicrotask(() => (this.valueFromPromise = changes['value'].currentValue));
}
}
@NgModule({
declarations: [AppComponent, ChildComponent],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('myApp', downgradeComponent({component: AppComponent}));
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
appComponent.value = 5;
});
}));
// This test demonstrates https://github.com/angular/angular/issues/6385
// which was invalidly fixed by https://github.com/angular/angular/pull/6386
// it('should not trigger $digest from an async operation in a watcher', async(() => {
// @Component({selector: 'my-app', template: ''})
// class AppComponent {
// }
// @NgModule({declarations: [AppComponent], imports: [BrowserModule]})
// class Ng2Module {
// }
// const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
// const ng1Module = angular.module_('ng1', []).directive(
// 'myApp', adapter.downgradeNg2Component(AppComponent));
// const element = html('<my-app></my-app>');
// adapter.bootstrap(element, ['ng1']).ready((ref) => {
// let doTimeout = false;
// let timeoutId: number;
// ref.ng1RootScope.$watch(() => {
// if (doTimeout && !timeoutId) {
// timeoutId = window.setTimeout(function() {
// timeoutId = null;
// }, 10);
// }
// });
// doTimeout = true;
// });
// }));
});
});
| {
"end_byte": 8061,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/change_detection_spec.ts"
} |
angular/packages/upgrade/static/test/integration/content_projection_spec.ts_0_6198 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
destroyPlatform,
Directive,
ElementRef,
Injector,
Input,
NgModule,
} from '@angular/core';
import {waitForAsync} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {downgradeComponent, UpgradeComponent, UpgradeModule} from '@angular/upgrade/static';
import * as angular from '../../../src/common/src/angular1';
import {
html,
multiTrim,
withEachNg1Version,
} from '../../../src/common/test/helpers/common_test_helpers';
import {bootstrap} from './static_test_helpers';
withEachNg1Version(() => {
describe('content projection', () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
it('should instantiate ng2 in ng1 template and project content', waitForAsync(() => {
// the ng2 component that will be used in ng1 (downgraded)
@Component({
selector: 'ng2',
template: `{{ prop }}(<ng-content></ng-content>)`,
standalone: false,
})
class Ng2Component {
prop = 'NG2';
ngContent = 'ng2-content';
}
// our upgrade module to host the component to downgrade
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
// the ng1 app module that will consume the downgraded component
const ng1Module = angular
.module_('ng1', [])
// create an ng1 facade of the ng2 component
.directive('ng2', downgradeComponent({component: Ng2Component}))
.run(($rootScope: angular.IRootScopeService) => {
$rootScope['prop'] = 'NG1';
$rootScope['ngContent'] = 'ng1-content';
});
const element = html("<div>{{ 'ng1[' }}<ng2>~{{ ngContent }}~</ng2>{{ ']' }}</div>");
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(document.body.textContent).toEqual('ng1[NG2(~ng1-content~)]');
});
}));
it('should correctly project structural directives', waitForAsync(() => {
@Component({
selector: 'ng2',
template: 'ng2-{{ itemId }}(<ng-content></ng-content>)',
standalone: false,
})
class Ng2Component {
@Input() itemId: string = '';
}
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng2', downgradeComponent({component: Ng2Component}))
.run(($rootScope: angular.IRootScopeService) => {
$rootScope['items'] = [
{id: 'a', subitems: [1, 2, 3]},
{id: 'b', subitems: [4, 5, 6]},
{id: 'c', subitems: [7, 8, 9]},
];
});
const element = html(`
<ng2 ng-repeat="item in items" [item-id]="item.id">
<div ng-repeat="subitem in item.subitems">{{ subitem }}</div>
</ng2>
`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(multiTrim(document.body.textContent)).toBe('ng2-a( 123 )ng2-b( 456 )ng2-c( 789 )');
});
}));
it('should instantiate ng1 in ng2 template and project content', waitForAsync(() => {
@Component({
selector: 'ng2',
template: `{{ 'ng2(' }}<ng1>{{ transclude }}</ng1
>{{ ')' }}`,
standalone: false,
})
class Ng2Component {
prop = 'ng2';
transclude = 'ng2-transclude';
}
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1WrapperComponent extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
@NgModule({
declarations: [Ng1WrapperComponent, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng1', () => ({
transclude: true,
template: '{{ prop }}(<ng-transclude></ng-transclude>)',
}))
.directive('ng2', downgradeComponent({component: Ng2Component}))
.run(($rootScope: angular.IRootScopeService) => {
$rootScope['prop'] = 'ng1';
$rootScope['transclude'] = 'ng1-transclude';
});
const element = html("<div>{{ 'ng1(' }}<ng2></ng2>{{ ')' }}</div>");
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(document.body.textContent).toEqual('ng1(ng2(ng1(ng2-transclude)))');
});
}));
it('should support multi-slot projection', waitForAsync(() => {
@Component({
selector: 'ng2',
template:
'2a(<ng-content select=".ng1a"></ng-content>)' +
'2b(<ng-content select=".ng1b"></ng-content>)',
standalone: false,
})
class Ng2Component {
constructor() {}
}
@NgModule({declarations: [Ng2Component], imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng2', downgradeComponent({component: Ng2Component}));
// The ng-if on one of the projected children is here to make sure
// the correct slot is targeted even with structural directives in play.
const element = html(
'<ng2><div ng-if="true" class="ng1a">1a</div><div' + ' class="ng1b">1b</div></ng2>',
);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(document.body.textContent).toEqual('2a(1a)2b(1b)');
});
}));
});
});
| {
"end_byte": 6198,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/content_projection_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_component_spec.ts_0_1051 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ChangeDetectionStrategy,
Compiler,
Component,
destroyPlatform,
Directive,
ElementRef,
EventEmitter,
Injector,
input,
Input,
NgModule,
NgModuleRef,
OnChanges,
OnDestroy,
Output,
SimpleChanges,
} from '@angular/core';
import {fakeAsync, tick, waitForAsync} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {downgradeComponent, UpgradeComponent, UpgradeModule} from '@angular/upgrade/static';
import * as angular from '../../../src/common/src/angular1';
import {$ROOT_SCOPE} from '../../../src/common/src/constants';
import {
html,
multiTrim,
withEachNg1Version,
} from '../../../src/common/test/helpers/common_test_helpers';
import {$apply, bootstrap} from './static_test_helpers'; | {
"end_byte": 1051,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_component_spec.ts_1053_8511 | withEachNg1Version(() => {
describe('downgrade ng2 component', () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
it('should bind properties, events', waitForAsync(() => {
const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => {
$rootScope['name'] = 'world';
$rootScope['dataA'] = 'A';
$rootScope['dataB'] = 'B';
$rootScope['modelA'] = 'initModelA';
$rootScope['modelB'] = 'initModelB';
$rootScope['eventA'] = '?';
$rootScope['eventB'] = '?';
});
@Component({
selector: 'ng2',
inputs: ['literal', 'interpolate', 'oneWayA', 'oneWayB', 'twoWayA', 'twoWayB'],
outputs: [
'eventA',
'eventB',
'twoWayAEmitter: twoWayAChange',
'twoWayBEmitter: twoWayBChange',
],
template:
'ignore: {{ignore}}; ' +
'literal: {{literal}}; interpolate: {{interpolate}}; ' +
'oneWayA: {{oneWayA}}; oneWayB: {{oneWayB}}; ' +
'twoWayA: {{twoWayA}}; twoWayB: {{twoWayB}}; ({{ngOnChangesCount}})',
standalone: false,
})
class Ng2Component implements OnChanges {
ngOnChangesCount = 0;
ignore = '-';
literal = '?';
interpolate = '?';
oneWayA = '?';
oneWayB = '?';
twoWayA = '?';
twoWayB = '?';
eventA = new EventEmitter();
eventB = new EventEmitter();
twoWayAEmitter = new EventEmitter();
twoWayBEmitter = new EventEmitter();
ngOnChanges(changes: SimpleChanges) {
const assert = (prop: string, value: any) => {
const propVal = (this as any)[prop];
if (propVal != value) {
throw new Error(`Expected: '${prop}' to be '${value}' but was '${propVal}'`);
}
};
const assertChange = (prop: string, value: any) => {
assert(prop, value);
if (!changes[prop]) {
throw new Error(`Changes record for '${prop}' not found.`);
}
const actualValue = changes[prop].currentValue;
if (actualValue != value) {
throw new Error(
`Expected changes record for'${prop}' to be '${value}' but was '${actualValue}'`,
);
}
};
switch (this.ngOnChangesCount++) {
case 0:
assert('ignore', '-');
assertChange('literal', 'Text');
assertChange('interpolate', 'Hello world');
assertChange('oneWayA', 'A');
assertChange('oneWayB', 'B');
assertChange('twoWayA', 'initModelA');
assertChange('twoWayB', 'initModelB');
this.twoWayAEmitter.emit('newA');
this.twoWayBEmitter.emit('newB');
this.eventA.emit('aFired');
this.eventB.emit('bFired');
break;
case 1:
assertChange('twoWayA', 'newA');
assertChange('twoWayB', 'newB');
break;
case 2:
assertChange('interpolate', 'Hello everyone');
break;
default:
throw new Error('Called too many times! ' + JSON.stringify(changes));
}
}
}
ng1Module.directive(
'ng2',
downgradeComponent({
component: Ng2Component,
}),
);
@NgModule({declarations: [Ng2Component], imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
const element = html(`
<div>
<ng2 literal="Text" interpolate="Hello {{name}}"
bind-one-way-a="dataA" [one-way-b]="dataB"
bindon-two-way-a="modelA" [(two-way-b)]="modelB"
on-event-a='eventA=$event' (event-b)="eventB=$event"></ng2>
| modelA: {{modelA}}; modelB: {{modelB}}; eventA: {{eventA}}; eventB: {{eventB}};
</div>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(multiTrim(document.body.textContent)).toEqual(
'ignore: -; ' +
'literal: Text; interpolate: Hello world; ' +
'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (2) | ' +
'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;',
);
$apply(upgrade, 'name = "everyone"');
expect(multiTrim(document.body.textContent)).toEqual(
'ignore: -; ' +
'literal: Text; interpolate: Hello everyone; ' +
'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (3) | ' +
'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;',
);
});
}));
it('should bind properties to signal inputs', waitForAsync(() => {
const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => {
$rootScope['name'] = 'world';
});
@Component({
selector: 'ng2',
inputs: ['message'],
template: 'Message: {{message()}}',
standalone: false,
})
class Ng2Component {
message = input<string>('');
}
@NgModule({declarations: [Ng2Component], imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
// Hack to wire up the `input()` signal correctly, since our JIT tests don't run with the
// transform which supports `input()`.
(Ng2Component as any).ɵcmp.inputs.message = ['message', /* InputFlags.SignalBased */ 1];
ng1Module.directive(
'ng2',
downgradeComponent({
component: Ng2Component,
}),
);
const element = html(`
<div>
<ng2 literal="Text" message="Hello {{name}}"></ng2>
</div>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(multiTrim(document.body.textContent)).toEqual('Message: Hello world');
$apply(upgrade, 'name = "everyone"');
expect(multiTrim(document.body.textContent)).toEqual('Message: Hello everyone');
});
}));
it('should bind properties to onpush components', waitForAsync(() => {
const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => {
$rootScope['dataB'] = 'B';
});
@Component({
selector: 'ng2',
inputs: ['oneWayB'],
template: 'oneWayB: {{oneWayB}}',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
class Ng2Component {
ngOnChangesCount = 0;
oneWayB = '?';
}
ng1Module.directive(
'ng2',
downgradeComponent({
component: Ng2Component,
}),
);
@NgModule({declarations: [Ng2Component], imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
const element = html(`
<div>
<ng2 [one-way-b]="dataB"></ng2>
</div>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(multiTrim(document.body.textContent)).toEqual('oneWayB: B');
$apply(upgrade, 'dataB= "everyone"');
expect(multiTrim(document.body.textContent)).toEqual('oneWayB: everyone');
});
}));
| {
"end_byte": 8511,
"start_byte": 1053,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_component_spec.ts_8517_15720 | t('should support two-way binding and event listener', waitForAsync(() => {
const listenerSpy = jasmine.createSpy('$rootScope.listener');
const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => {
$rootScope['value'] = 'world';
$rootScope['listener'] = listenerSpy;
});
@Component({
selector: 'ng2',
template: `model: {{ model }};`,
standalone: false,
})
class Ng2Component implements OnChanges {
ngOnChangesCount = 0;
@Input() model = '?';
@Output() modelChange = new EventEmitter();
ngOnChanges(changes: SimpleChanges) {
switch (this.ngOnChangesCount++) {
case 0:
expect(changes['model'].currentValue).toBe('world');
this.modelChange.emit('newC');
break;
case 1:
expect(changes['model'].currentValue).toBe('newC');
break;
default:
throw new Error('Called too many times! ' + JSON.stringify(changes));
}
}
}
ng1Module.directive('ng2', downgradeComponent({component: Ng2Component}));
@NgModule({declarations: [Ng2Component], imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
const element = html(`
<div>
<ng2 [(model)]="value" (model-change)="listener($event)"></ng2>
| value: {{value}}
</div>
`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(multiTrim(element.textContent)).toEqual('model: newC; | value: newC');
expect(listenerSpy).toHaveBeenCalledWith('newC');
});
}));
it('should run change-detection on every digest (by default)', waitForAsync(() => {
let ng2Component: Ng2Component;
@Component({
selector: 'ng2',
template: '{{ value1 }} | {{ value2 }}',
standalone: false,
})
class Ng2Component {
@Input() value1 = -1;
@Input() value2 = -1;
constructor() {
ng2Component = this;
}
}
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng2', downgradeComponent({component: Ng2Component}))
.run(($rootScope: angular.IRootScopeService) => {
$rootScope['value1'] = 0;
$rootScope['value2'] = 0;
});
const element = html('<ng2 [value1]="value1" value2="{{ value2 }}"></ng2>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService;
expect(element.textContent).toBe('0 | 0');
// Digest should invoke CD
$rootScope.$digest();
$rootScope.$digest();
expect(element.textContent).toBe('0 | 0');
// Internal changes should be detected on digest
ng2Component.value1 = 1;
ng2Component.value2 = 2;
$rootScope.$digest();
expect(element.textContent).toBe('1 | 2');
// Digest should propagate change in prop-bound input
$rootScope.$apply('value1 = 3');
expect(element.textContent).toBe('3 | 2');
// Digest should propagate change in attr-bound input
ng2Component.value1 = 4;
$rootScope.$apply('value2 = 5');
expect(element.textContent).toBe('4 | 5');
// Digest should propagate changes that happened before the digest
$rootScope['value1'] = 6;
expect(element.textContent).toBe('4 | 5');
$rootScope.$digest();
expect(element.textContent).toBe('6 | 5');
});
}));
it('should not run change-detection on every digest when opted out', waitForAsync(() => {
let ng2Component: Ng2Component;
@Component({
selector: 'ng2',
template: '{{ value1 }} | {{ value2 }}',
standalone: false,
})
class Ng2Component {
@Input() value1 = -1;
@Input() value2 = -1;
constructor() {
ng2Component = this;
}
}
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest: false}))
.run(($rootScope: angular.IRootScopeService) => {
$rootScope['value1'] = 0;
$rootScope['value2'] = 0;
});
const element = html('<ng2 [value1]="value1" value2="{{ value2 }}"></ng2>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService;
expect(element.textContent).toBe('0 | 0');
// Digest should not invoke CD
$rootScope.$digest();
$rootScope.$digest();
expect(element.textContent).toBe('0 | 0');
// Digest should not invoke CD, even if component values have changed (internally)
ng2Component.value1 = 1;
ng2Component.value2 = 2;
$rootScope.$digest();
expect(element.textContent).toBe('0 | 0');
// Digest should invoke CD, if prop-bound input has changed
$rootScope.$apply('value1 = 3');
expect(element.textContent).toBe('3 | 2');
// Digest should invoke CD, if attr-bound input has changed
ng2Component.value1 = 4;
$rootScope.$apply('value2 = 5');
expect(element.textContent).toBe('4 | 5');
// Digest should invoke CD, if input has changed before the digest
$rootScope['value1'] = 6;
$rootScope.$digest();
expect(element.textContent).toBe('6 | 5');
});
}));
it('should still run normal Angular change-detection regardless of `propagateDigest`', fakeAsync(() => {
@Component({
selector: 'ng2',
template: '{{ value }}',
standalone: false,
})
class Ng2Component {
value = 'foo';
constructor() {
setTimeout(() => (this.value = 'bar'), 1000);
}
}
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng2A', downgradeComponent({component: Ng2Component, propagateDigest: true}))
.directive('ng2B', downgradeComponent({component: Ng2Component, propagateDigest: false}));
const element = html('<ng2-a></ng2-a> | <ng2-b></ng2-b>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(element.textContent).toBe('foo | foo');
tick(1000);
expect(element.textContent).toBe('bar | bar');
});
}));
| {
"end_byte": 15720,
"start_byte": 8517,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_component_spec.ts_15726_22523 | t('should initialize inputs in time for `ngOnChanges`', waitForAsync(() => {
@Component({
selector: 'ng2',
template: ` ngOnChangesCount: {{ ngOnChangesCount }} | firstChangesCount:
{{ firstChangesCount }} | initialValue: {{ initialValue }}`,
standalone: false,
})
class Ng2Component implements OnChanges {
ngOnChangesCount = 0;
firstChangesCount = 0;
@Input() foo: string = '';
initialValue: string = this.foo;
ngOnChanges(changes: SimpleChanges) {
this.ngOnChangesCount++;
if (this.ngOnChangesCount === 1) {
this.initialValue = this.foo;
}
if (changes['foo'] && changes['foo'].isFirstChange()) {
this.firstChangesCount++;
}
}
}
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng2', downgradeComponent({component: Ng2Component}));
const element = html(`
<ng2 [foo]="'foo'"></ng2>
<ng2 foo="bar"></ng2>
<ng2 [foo]="'baz'" ng-if="true"></ng2>
<ng2 foo="qux" ng-if="true"></ng2>
`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
const nodes = element.querySelectorAll('ng2');
const expectedTextWith = (value: string) =>
`ngOnChangesCount: 1 | firstChangesCount: 1 | initialValue: ${value}`;
expect(multiTrim(nodes[0].textContent)).toBe(expectedTextWith('foo'));
expect(multiTrim(nodes[1].textContent)).toBe(expectedTextWith('bar'));
expect(multiTrim(nodes[2].textContent)).toBe(expectedTextWith('baz'));
expect(multiTrim(nodes[3].textContent)).toBe(expectedTextWith('qux'));
});
}));
it('should bind to ng-model', waitForAsync(() => {
const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => {
$rootScope['modelA'] = 'A';
});
let ng2Instance: Ng2;
@Component({
selector: 'ng2',
template: '<span>{{_value}}</span>',
standalone: false,
})
class Ng2 {
private _value: any = '';
private _onChangeCallback: (_: any) => void = () => {};
private _onTouchedCallback: () => void = () => {};
constructor() {
ng2Instance = this;
}
writeValue(value: any) {
this._value = value;
}
registerOnChange(fn: any) {
this._onChangeCallback = fn;
}
registerOnTouched(fn: any) {
this._onTouchedCallback = fn;
}
doTouch() {
this._onTouchedCallback();
}
doChange(newValue: string) {
this._value = newValue;
this._onChangeCallback(newValue);
}
}
ng1Module.directive('ng2', downgradeComponent({component: Ng2}));
const element = html(`<div><ng2 ng-model="modelA"></ng2> | {{modelA}}</div>`);
@NgModule({declarations: [Ng2], imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
platformBrowserDynamic()
.bootstrapModule(Ng2Module)
.then((ref) => {
const adapter = ref.injector.get(UpgradeModule) as UpgradeModule;
adapter.bootstrap(element, [ng1Module.name]);
const $rootScope = adapter.$injector.get('$rootScope');
expect(multiTrim(document.body.textContent)).toEqual('A | A');
$rootScope.modelA = 'B';
$rootScope.$apply();
expect(multiTrim(document.body.textContent)).toEqual('B | B');
ng2Instance.doChange('C');
expect($rootScope.modelA).toBe('C');
expect(multiTrim(document.body.textContent)).toEqual('C | C');
const downgradedElement = <Element>document.body.querySelector('ng2');
expect(downgradedElement.classList.contains('ng-touched')).toBe(false);
ng2Instance.doTouch();
$rootScope.$apply();
expect(downgradedElement.classList.contains('ng-touched')).toBe(true);
});
}));
it('should properly run cleanup when ng1 directive is destroyed', waitForAsync(() => {
let destroyed = false;
@Component({
selector: 'ng2',
template: '<ul><li>test1</li><li>test2</li></ul>',
standalone: false,
})
class Ng2Component implements OnDestroy {
ngOnDestroy() {
destroyed = true;
}
}
@NgModule({declarations: [Ng2Component], imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng1', () => {
return {template: '<div ng-if="!destroyIt"><ng2></ng2></div>'};
})
.directive('ng2', downgradeComponent({component: Ng2Component}));
const element = html('<ng1></ng1>');
platformBrowserDynamic()
.bootstrapModule(Ng2Module)
.then((ref) => {
const adapter = ref.injector.get(UpgradeModule) as UpgradeModule;
adapter.bootstrap(element, [ng1Module.name]);
const ng2Element = angular.element(element.querySelector('ng2') as Element);
const ng2Descendants = Array.from(element.querySelectorAll('ng2 li')).map(
angular.element,
);
let ng2ElementDestroyed = false;
let ng2DescendantsDestroyed = [false, false];
ng2Element.data!('test', 42);
ng2Descendants.forEach((elem, i) => elem.data!('test', i));
ng2Element.on!('$destroy', () => (ng2ElementDestroyed = true));
ng2Descendants.forEach((elem, i) =>
elem.on!('$destroy', () => (ng2DescendantsDestroyed[i] = true)),
);
expect(element.textContent).toBe('test1test2');
expect(destroyed).toBe(false);
expect(ng2Element.data!('test')).toBe(42);
ng2Descendants.forEach((elem, i) => expect(elem.data!('test')).toBe(i));
expect(ng2ElementDestroyed).toBe(false);
expect(ng2DescendantsDestroyed).toEqual([false, false]);
const $rootScope = adapter.$injector.get('$rootScope');
$rootScope.$apply('destroyIt = true');
expect(element.textContent).toBe('');
expect(destroyed).toBe(true);
expect(ng2Element.data!('test')).toBeUndefined();
ng2Descendants.forEach((elem) => expect(elem.data!('test')).toBeUndefined());
expect(ng2ElementDestroyed).toBe(true);
expect(ng2DescendantsDestroyed).toEqual([true, true]);
});
}));
| {
"end_byte": 22523,
"start_byte": 15726,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_component_spec.ts_22529_31252 | t('should properly run cleanup with multiple levels of nesting', waitForAsync(() => {
let destroyed = false;
@Component({
selector: 'ng2-outer',
template: '<div *ngIf="!destroyIt"><ng1></ng1></div>',
standalone: false,
})
class Ng2OuterComponent {
@Input() destroyIt = false;
}
@Component({
selector: 'ng2-inner',
template: 'test',
standalone: false,
})
class Ng2InnerComponent implements OnDestroy {
ngOnDestroy() {
destroyed = true;
}
}
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2InnerComponent, Ng2OuterComponent],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng1', () => ({template: '<ng2-inner></ng2-inner>'}))
.directive('ng2Inner', downgradeComponent({component: Ng2InnerComponent}))
.directive('ng2Outer', downgradeComponent({component: Ng2OuterComponent}));
const element = html('<ng2-outer [destroy-it]="destroyIt"></ng2-outer>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(element.textContent).toBe('test');
expect(destroyed).toBe(false);
$apply(upgrade, 'destroyIt = true');
expect(element.textContent).toBe('');
expect(destroyed).toBe(true);
});
}));
it('should destroy the AngularJS app when `PlatformRef` is destroyed', waitForAsync(() => {
@Component({
selector: 'ng2',
template: '<span>NG2</span>',
standalone: false,
})
class Ng2Component {}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.component('ng1', {template: '<ng2></ng2>'})
.directive('ng2', downgradeComponent({component: Ng2Component}));
const element = html('<div><ng1></ng1></div>');
const platformRef = platformBrowserDynamic();
platformRef.bootstrapModule(Ng2Module).then((ref) => {
const upgrade = ref.injector.get(UpgradeModule);
upgrade.bootstrap(element, [ng1Module.name]);
const $rootScope: angular.IRootScopeService = upgrade.$injector.get($ROOT_SCOPE);
const rootScopeDestroySpy = spyOn($rootScope, '$destroy');
const appElem = angular.element(element);
const ng1Elem = angular.element(element.querySelector('ng1') as Element);
const ng2Elem = angular.element(element.querySelector('ng2') as Element);
const ng2ChildElem = angular.element(element.querySelector('ng2 span') as Element);
// Attach data to all elements.
appElem.data!('testData', 1);
ng1Elem.data!('testData', 2);
ng2Elem.data!('testData', 3);
ng2ChildElem.data!('testData', 4);
// Verify data can be retrieved.
expect(appElem.data!('testData')).toBe(1);
expect(ng1Elem.data!('testData')).toBe(2);
expect(ng2Elem.data!('testData')).toBe(3);
expect(ng2ChildElem.data!('testData')).toBe(4);
expect(rootScopeDestroySpy).not.toHaveBeenCalled();
// Destroy `PlatformRef`.
platformRef.destroy();
// Verify `$rootScope` has been destroyed and data has been cleaned up.
expect(rootScopeDestroySpy).toHaveBeenCalled();
expect(appElem.data!('testData')).toBeUndefined();
expect(ng1Elem.data!('testData')).toBeUndefined();
expect(ng2Elem.data!('testData')).toBeUndefined();
expect(ng2ChildElem.data!('testData')).toBeUndefined();
});
}));
it('should work when compiled outside the dom (by fallback to the root ng2.injector)', waitForAsync(() => {
@Component({
selector: 'ng2',
template: 'test',
standalone: false,
})
class Ng2Component {}
@NgModule({declarations: [Ng2Component], imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng1', [
'$compile',
($compile: angular.ICompileService) => {
return {
link: function (
$scope: angular.IScope,
$element: angular.IAugmentedJQuery,
$attrs: angular.IAttributes,
) {
// here we compile some HTML that contains a downgraded component
// since it is not currently in the DOM it is not able to "require"
// an ng2 injector so it should use the `moduleInjector` instead.
const compiled = $compile('<ng2></ng2>');
const template = compiled($scope);
$element.append!(template);
},
};
},
])
.directive('ng2', downgradeComponent({component: Ng2Component}));
const element = html('<ng1></ng1>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
// the fact that the body contains the correct text means that the
// downgraded component was able to access the moduleInjector
// (since there is no other injector in this system)
expect(multiTrim(document.body.textContent)).toEqual('test');
});
}));
it('should allow attribute selectors for downgraded components', waitForAsync(() => {
@Component({
selector: '[itWorks]',
template: 'It works',
standalone: false,
})
class WorksComponent {}
@NgModule({declarations: [WorksComponent], imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('worksComponent', downgradeComponent({component: WorksComponent}));
const element = html('<works-component></works-component>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(multiTrim(document.body.textContent)).toBe('It works');
});
}));
it('should allow attribute selectors for components in ng2', waitForAsync(() => {
@Component({
selector: '[itWorks]',
template: 'It works',
standalone: false,
})
class WorksComponent {}
@Component({
selector: 'root-component',
template: '<span itWorks></span>!',
standalone: false,
})
class RootComponent {}
@NgModule({
declarations: [RootComponent, WorksComponent],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('rootComponent', downgradeComponent({component: RootComponent}));
const element = html('<root-component></root-component>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(multiTrim(document.body.textContent)).toBe('It works!');
});
}));
it('should respect hierarchical dependency injection for ng2', waitForAsync(() => {
@Component({
selector: 'parent',
template: 'parent(<ng-content></ng-content>)',
standalone: false,
})
class ParentComponent {}
@Component({
selector: 'child',
template: 'child',
standalone: false,
})
class ChildComponent {
constructor(parent: ParentComponent) {}
}
@NgModule({
declarations: [ParentComponent, ChildComponent],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('parent', downgradeComponent({component: ParentComponent}))
.directive('child', downgradeComponent({component: ChildComponent}));
const element = html('<parent><child></child></parent>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(multiTrim(document.body.textContent)).toBe('parent(child)');
});
}));
| {
"end_byte": 31252,
"start_byte": 22529,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/downgrade_component_spec.ts_31258_35907 | t('should be compiled synchronously, if possible', waitForAsync(() => {
@Component({
selector: 'ng2A',
template: '<ng-content></ng-content>',
standalone: false,
})
class Ng2ComponentA {}
@Component({
selector: 'ng2B',
template: "{{ 'Ng2 template' }}",
standalone: false,
})
class Ng2ComponentB {}
@NgModule({
declarations: [Ng2ComponentA, Ng2ComponentB],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng2A', downgradeComponent({component: Ng2ComponentA}))
.directive('ng2B', downgradeComponent({component: Ng2ComponentB}));
const element = html('<ng2-a><ng2-b></ng2-b></ng2-a>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(element.textContent).toBe('Ng2 template');
});
}));
it('should work with ng2 lazy loaded components', waitForAsync(() => {
let componentInjector: Injector;
@Component({
selector: 'ng2',
template: '',
standalone: false,
})
class Ng2Component {
constructor(injector: Injector) {
componentInjector = injector;
}
}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
@Component({
template: '',
standalone: false,
})
class LazyLoadedComponent {
constructor(public module: NgModuleRef<any>) {}
}
@NgModule({
declarations: [LazyLoadedComponent],
})
class LazyLoadedModule {}
const ng1Module = angular
.module_('ng1', [])
.directive('ng2', downgradeComponent({component: Ng2Component}));
const element = html('<ng2></ng2>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
const modInjector = upgrade.injector;
// Emulate the router lazy loading a module and creating a component
const compiler = modInjector.get(Compiler);
const modFactory = compiler.compileModuleSync(LazyLoadedModule);
const childMod = modFactory.create(modInjector);
const cmpFactory =
childMod.componentFactoryResolver.resolveComponentFactory(LazyLoadedComponent)!;
const lazyCmp = cmpFactory.create(componentInjector);
expect(lazyCmp.instance.module.injector === childMod.injector).toBe(true);
});
}));
it('should throw if `downgradedModule` is specified', waitForAsync(() => {
@Component({
selector: 'ng2',
template: '',
standalone: false,
})
class Ng2Component {}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular
.module_('ng1', [])
.directive('ng2', downgradeComponent({component: Ng2Component, downgradedModule: 'foo'}));
const element = html('<ng2></ng2>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(
() => {
throw new Error('Expected bootstraping to fail.');
},
(err) =>
expect(err.message).toBe(
"Error while instantiating component 'Ng2Component': 'downgradedModule' " +
'unexpectedly specified.\n' +
"You should not specify a value for 'downgradedModule', unless you are " +
"downgrading more than one Angular module (via 'downgradeModule()').",
),
);
}));
});
describe('standalone', () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
it('should downgrade a standalone component using NgModule APIs', waitForAsync(() => {
@Component({selector: 'ng2', standalone: true, template: 'Hi from Angular!'})
class Ng2Component {}
const ng1Module = angular
.module_('ng1', [])
.directive('ng2', downgradeComponent({component: Ng2Component}));
@NgModule({
imports: [BrowserModule, UpgradeModule, Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
const element = html('<ng2></ng2>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(element.textContent).toBe('Hi from Angular!');
});
}));
});
});
| {
"end_byte": 35907,
"start_byte": 31258,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/downgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_0_8859 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
destroyPlatform,
Directive,
ElementRef,
EventEmitter,
Inject,
Injector,
Input,
NgModule,
NO_ERRORS_SCHEMA,
Output,
SimpleChanges,
} from '@angular/core';
import {fakeAsync, tick, waitForAsync} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import * as angular from '../../../src/common/src/angular1';
import {$EXCEPTION_HANDLER, $SCOPE} from '../../../src/common/src/constants';
import {
html,
multiTrim,
withEachNg1Version,
} from '../../../src/common/test/helpers/common_test_helpers';
import {downgradeComponent, UpgradeComponent, UpgradeModule} from '../../index';
import {$digest, bootstrap} from './static_test_helpers';
withEachNg1Version(() => {
describe('upgrade ng1 component', () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
describe('template/templateUrl', () => {
it('should support `template` (string)', waitForAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {template: 'Hello, Angular!'};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(multiTrim(element.textContent)).toBe('Hello, Angular!');
});
}));
it('should support `template` (function)', waitForAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {template: () => 'Hello, Angular!'};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('Hello, Angular!');
});
}));
it('should pass $element to `template` function and not $attrs', waitForAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: ($attrs: angular.IAttributes, $element: angular.IAugmentedJQuery) => {
expect($attrs).toBeUndefined();
expect($element).toBeDefined();
return 'Hello, Angular!';
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('Hello, Angular!');
});
}));
it('should support `templateUrl` (string) fetched from `$templateCache`', waitForAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {templateUrl: 'ng1.component.html'};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}))
.run(($templateCache: angular.ITemplateCacheService) =>
$templateCache.put('ng1.component.html', 'Hello, Angular!'),
);
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('Hello, Angular!');
});
}));
it('should support `templateUrl` (function) fetched from `$templateCache`', waitForAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {templateUrl: () => 'ng1.component.html'};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}))
.run(($templateCache: angular.ITemplateCacheService) =>
$templateCache.put('ng1.component.html', 'Hello, Angular!'),
);
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('Hello, Angular!');
});
})); | {
"end_byte": 8859,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_8867_17171 | it('should pass $element to `templateUrl` function and not $attrs', waitForAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {
templateUrl: ($attrs: angular.IAttributes, $element: angular.IAugmentedJQuery) => {
expect($attrs).toBeUndefined();
expect($element).toBeDefined();
return 'ng1.component.html';
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}))
.run(($templateCache: angular.ITemplateCacheService) =>
$templateCache.put('ng1.component.html', 'Hello, Angular!'),
);
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('Hello, Angular!');
});
}));
// NOT SUPPORTED YET
xit('should support `templateUrl` (string) fetched from the server', fakeAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {templateUrl: 'ng1.component.html'};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}))
.value('$httpBackend', (method: string, url: string, post: any, callback: Function) =>
setTimeout(() => callback(200, `${method}:${url}`.toLowerCase()), 1000),
);
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
tick(500);
expect(multiTrim(element.textContent)).toBe('');
tick(500);
expect(multiTrim(element.textContent)).toBe('get:ng1.component.html');
});
}));
// NOT SUPPORTED YET
xit('should support `templateUrl` (function) fetched from the server', fakeAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {templateUrl: () => 'ng1.component.html'};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}))
.value('$httpBackend', (method: string, url: string, post: any, callback: Function) =>
setTimeout(() => callback(200, `${method}:${url}`.toLowerCase()), 1000),
);
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
tick(500);
expect(multiTrim(element.textContent)).toBe('');
tick(500);
expect(multiTrim(element.textContent)).toBe('get:ng1.component.html');
});
}));
it('should support empty templates', waitForAsync(() => {
// Define `ng1Component`s
const ng1ComponentA: angular.IComponent = {template: ''};
const ng1ComponentB: angular.IComponent = {template: () => ''};
const ng1ComponentC: angular.IComponent = {templateUrl: 'ng1.component.html'};
const ng1ComponentD: angular.IComponent = {templateUrl: () => 'ng1.component.html'};
// Define `Ng1ComponentFacade`s
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(e: ElementRef, i: Injector) {
super('ng1A', e, i);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(e: ElementRef, i: Injector) {
super('ng1B', e, i);
}
}
@Directive({
selector: 'ng1C',
standalone: false,
})
class Ng1ComponentCFacade extends UpgradeComponent {
constructor(e: ElementRef, i: Injector) {
super('ng1C', e, i);
}
}
@Directive({
selector: 'ng1D',
standalone: false,
})
class Ng1ComponentDFacade extends UpgradeComponent {
constructor(e: ElementRef, i: Injector) {
super('ng1D', e, i);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1A>Ignore this</ng1A>
<ng1B>Ignore this</ng1B>
<ng1C>Ignore this</ng1C>
<ng1D>Ignore this</ng1D>
`,
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1A', ng1ComponentA)
.component('ng1B', ng1ComponentB)
.component('ng1C', ng1ComponentC)
.component('ng1D', ng1ComponentD)
.directive('ng2', downgradeComponent({component: Ng2Component}))
.run(($templateCache: angular.ITemplateCacheService) =>
$templateCache.put('ng1.component.html', ''),
);
// Define `Ng2Module`
@NgModule({
declarations: [
Ng1ComponentAFacade,
Ng1ComponentBFacade,
Ng1ComponentCFacade,
Ng1ComponentDFacade,
Ng2Component,
],
imports: [BrowserModule, UpgradeModule],
schemas: [NO_ERRORS_SCHEMA],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('');
});
}));
}); | {
"end_byte": 17171,
"start_byte": 8867,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_17177_24964 | describe('bindings', () => {
it('should support `@` bindings', fakeAsync(() => {
let ng2ComponentInstance: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'Inside: {{ $ctrl.inputA }}, {{ $ctrl.inputB }}',
bindings: {inputA: '@inputAttrA', inputB: '@'},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
@Input('inputAttrA') inputA: string = '';
@Input() inputB: string = '';
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1 inputAttrA="{{ dataA }}" inputB="{{ dataB }}"></ng1>
| Outside: {{ dataA }}, {{ dataB }}
`,
standalone: false,
})
class Ng2Component {
dataA = 'foo';
dataB = 'bar';
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
const ng1 = element.querySelector('ng1')!;
const ng1Controller = angular.element(ng1).controller?.('ng1');
expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar');
ng1Controller.inputA = 'baz';
ng1Controller.inputB = 'qux';
tick();
expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: foo, bar');
ng2ComponentInstance.dataA = 'foo2';
ng2ComponentInstance.dataB = 'bar2';
$digest(adapter);
tick();
expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2');
});
}));
it('should support `<` bindings', fakeAsync(() => {
let ng2ComponentInstance: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'Inside: {{ $ctrl.inputA.value }}, {{ $ctrl.inputB.value }}',
bindings: {inputA: '<inputAttrA', inputB: '<'},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
@Input('inputAttrA') inputA: string = '';
@Input() inputB: string = '';
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1 [inputAttrA]="dataA" [inputB]="dataB"></ng1>
| Outside: {{ dataA.value }}, {{ dataB.value }}
`,
standalone: false,
})
class Ng2Component {
dataA = {value: 'foo'};
dataB = {value: 'bar'};
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
const ng1 = element.querySelector('ng1')!;
const ng1Controller = angular.element(ng1).controller?.('ng1');
expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar');
ng1Controller.inputA = {value: 'baz'};
ng1Controller.inputB = {value: 'qux'};
tick();
expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: foo, bar');
ng2ComponentInstance.dataA = {value: 'foo2'};
ng2ComponentInstance.dataB = {value: 'bar2'};
$digest(adapter);
tick();
expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2');
});
}));
it('should support `=` bindings', fakeAsync(() => {
let ng2ComponentInstance: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'Inside: {{ $ctrl.inputA.value }}, {{ $ctrl.inputB.value }}',
bindings: {inputA: '=inputAttrA', inputB: '='},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
@Input('inputAttrA') inputA: string = '';
@Output('inputAttrAChange') inputAChange = new EventEmitter();
@Input() inputB: string = '';
@Output() inputBChange = new EventEmitter();
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1 [(inputAttrA)]="dataA" [(inputB)]="dataB"></ng1>
| Outside: {{ dataA.value }}, {{ dataB.value }}
`,
standalone: false,
})
class Ng2Component {
dataA = {value: 'foo'};
dataB = {value: 'bar'};
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
const ng1 = element.querySelector('ng1')!;
const ng1Controller = angular.element(ng1).controller?.('ng1');
expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar');
ng1Controller.inputA = {value: 'baz'};
ng1Controller.inputB = {value: 'qux'};
tick();
expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: baz, qux');
ng2ComponentInstance.dataA = {value: 'foo2'};
ng2ComponentInstance.dataB = {value: 'bar2'};
$digest(adapter);
tick();
expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2');
});
})); | {
"end_byte": 24964,
"start_byte": 17177,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_24972_30560 | it('should support `&` bindings', fakeAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'Inside: -',
bindings: {outputA: '&outputAttrA', outputB: '&'},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
@Output('outputAttrA') outputA = new EventEmitter();
@Output() outputB = new EventEmitter();
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1 (outputAttrA)="dataA = $event" (outputB)="dataB = $event"></ng1>
| Outside: {{ dataA }}, {{ dataB }}
`,
standalone: false,
})
class Ng2Component {
dataA = 'foo';
dataB = 'bar';
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
const ng1 = element.querySelector('ng1')!;
const ng1Controller = angular.element(ng1).controller?.('ng1');
expect(multiTrim(element.textContent)).toBe('Inside: - | Outside: foo, bar');
ng1Controller.outputA('baz');
ng1Controller.outputB('qux');
tick();
expect(multiTrim(element.textContent)).toBe('Inside: - | Outside: baz, qux');
});
}));
it('should bind properties, events', fakeAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: `
Hello {{ $ctrl.fullName }};
A: {{ $ctrl.modelA }};
B: {{ $ctrl.modelB }};
C: {{ $ctrl.modelC }}
`,
bindings: {fullName: '@', modelA: '<dataA', modelB: '=dataB', modelC: '=', event: '&'},
controller: function (this: any, $scope: angular.IScope) {
$scope.$watch('$ctrl.modelB', (v: string) => {
if (v === 'Savkin') {
this.modelB = 'SAVKIN';
this.event('WORKS');
// Should not update because `modelA: '<dataA'` is uni-directional.
this.modelA = 'VICTOR';
// Should not update because `[modelC]` is uni-directional.
this.modelC = 'sf';
}
});
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
@Input() fullName: string = '';
@Input('dataA') modelA: any;
@Input('dataB') modelB: any;
@Output('dataBChange') modelBChange = new EventEmitter();
@Input() modelC: any;
@Output() modelCChange = new EventEmitter();
@Output() event = new EventEmitter();
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1
fullName="{{ last }}, {{ first }}, {{ city }}"
[(dataA)]="first"
[(dataB)]="last"
[modelC]="city"
(event)="event = $event"
>
</ng1>
| <ng1 fullName="{{ 'TEST' }}" dataA="First" dataB="Last" modelC="City"></ng1> |
{{ event }} - {{ last }}, {{ first }}, {{ city }}
`,
standalone: false,
})
class Ng2Component {
first = 'Victor';
last = 'Savkin';
city = 'SF';
event = '?';
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe(
'Hello Savkin, Victor, SF; A: VICTOR; B: SAVKIN; C: sf | ' +
'Hello TEST; A: First; B: Last; C: City | ' +
'WORKS - SAVKIN, Victor, SF',
);
// Detect changes
tick();
expect(multiTrim(element.textContent)).toBe(
'Hello SAVKIN, Victor, SF; A: VICTOR; B: SAVKIN; C: sf | ' +
'Hello TEST; A: First; B: Last; C: City | ' +
'WORKS - SAVKIN, Victor, SF',
);
});
})); | {
"end_byte": 30560,
"start_byte": 24972,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_30568_36856 | it('should bind optional properties', fakeAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'Inside: {{ $ctrl.inputA.value }}, {{ $ctrl.inputB }}',
bindings: {inputA: '=?inputAttrA', inputB: '=?', outputA: '&?outputAttrA', outputB: '&?'},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
@Input('inputAttrA') inputA: string = '';
@Output('inputAttrAChange') inputAChange = new EventEmitter();
@Input() inputB: string = '';
@Output() inputBChange = new EventEmitter();
@Output('outputAttrA') outputA = new EventEmitter();
@Output() outputB = new EventEmitter();
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1 [(inputAttrA)]="dataA" [(inputB)]="dataB.value"></ng1> |
<ng1 inputB="Bar" (outputAttrA)="dataA = $event"></ng1> |
<ng1 (outputB)="updateDataB($event)"></ng1> | <ng1></ng1> | Outside: {{ dataA.value }},
{{ dataB.value }}
`,
standalone: false,
})
class Ng2Component {
dataA = {value: 'foo'};
dataB = {value: 'bar'};
updateDataB(value: any) {
this.dataB.value = value;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
const ng1s = element.querySelectorAll('ng1')!;
const ng1Controller0 = angular.element(ng1s[0]).controller?.('ng1');
const ng1Controller1 = angular.element(ng1s[1]).controller?.('ng1');
const ng1Controller2 = angular.element(ng1s[2]).controller?.('ng1');
expect(multiTrim(element.textContent)).toBe(
'Inside: foo, bar | Inside: , Bar | Inside: , | Inside: , | Outside: foo, bar',
);
ng1Controller0.inputA.value = 'baz';
ng1Controller0.inputB = 'qux';
tick();
expect(multiTrim(element.textContent)).toBe(
'Inside: baz, qux | Inside: , Bar | Inside: , | Inside: , | Outside: baz, qux',
);
ng1Controller1.outputA({value: 'foo again'});
ng1Controller2.outputB('bar again');
$digest(adapter);
tick();
expect(ng1Controller0.inputA).toEqual({value: 'foo again'});
expect(ng1Controller0.inputB).toEqual('bar again');
expect(multiTrim(element.textContent)).toBe(
'Inside: foo again, bar again | Inside: , Bar | Inside: , | Inside: , | ' +
'Outside: foo again, bar again',
);
});
}));
it('should bind properties, events to scope when bindToController is not used', fakeAsync(() => {
// Define `ng1Directive`
const ng1Directive: angular.IDirective = {
template: '{{ someText }} - Data: {{ inputA }} - Length: {{ inputA.length }}',
scope: {inputA: '=', outputA: '&'},
controller: function (this: any, $scope: angular.IScope) {
$scope['someText'] = 'ng1';
this.$scope = $scope;
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: '[ng1]',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
@Input() inputA: string = '';
@Output() inputAChange = new EventEmitter();
@Output() outputA = new EventEmitter();
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<div ng1 [(inputA)]="dataA" (outputA)="dataA.push($event)"></div>
| {{ someText }} - Data: {{ dataA }} - Length: {{ dataA.length }}
`,
standalone: false,
})
class Ng2Component {
someText = 'ng2';
dataA = [1, 2, 3];
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1', () => ng1Directive)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
const ng1 = element.querySelector('[ng1]')!;
const ng1Controller = angular.element(ng1).controller?.('ng1');
expect(multiTrim(element.textContent)).toBe(
'ng1 - Data: [1,2,3] - Length: 3 | ng2 - Data: 1,2,3 - Length: 3',
);
ng1Controller.$scope.inputA = [4, 5];
tick();
expect(multiTrim(element.textContent)).toBe(
'ng1 - Data: [4,5] - Length: 2 | ng2 - Data: 4,5 - Length: 2',
);
ng1Controller.$scope.outputA(6);
$digest(adapter);
tick();
expect(ng1Controller.$scope.inputA).toEqual([4, 5, 6]);
expect(multiTrim(element.textContent)).toBe(
'ng1 - Data: [4,5,6] - Length: 3 | ng2 - Data: 4,5,6 - Length: 3',
);
});
}));
}); | {
"end_byte": 36856,
"start_byte": 30568,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_36862_38629 | describe('compiling', () => {
it('should compile the ng1 template in the correct DOM context', waitForAsync(() => {
let grandParentNodeName: string;
// Define `ng1Component`
const ng1ComponentA: angular.IComponent = {template: 'ng1A(<ng1-b></ng1-b>)'};
const ng1DirectiveB: angular.IDirective = {
compile: (tElem) => {
grandParentNodeName = tElem.parent!().parent!()[0].nodeName;
return {};
},
};
// Define `Ng1ComponentAFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
// Define `Ng2ComponentX`
@Component({
selector: 'ng2-x',
template: 'ng2X(<ng1A></ng1A>)',
standalone: false,
})
class Ng2ComponentX {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1', [])
.component('ng1A', ng1ComponentA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2X', downgradeComponent({component: Ng2ComponentX}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentAFacade, Ng2ComponentX],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2-x></ng2-x>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(grandParentNodeName).toBe('NG2-X');
});
}));
}); | {
"end_byte": 38629,
"start_byte": 36862,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_38635_46920 | describe('linking', () => {
it('should run the pre-linking after instantiating the controller', waitForAsync(() => {
const log: string[] = [];
// Define `ng1Directive`
const ng1Directive: angular.IDirective = {
template: '',
link: {pre: () => log.push('ng1-pre')},
controller: class {
constructor() {
log.push('ng1-ctrl');
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1', [])
.directive('ng1', () => ng1Directive)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(log).toEqual(['ng1-ctrl', 'ng1-pre']);
});
}));
it('should run the pre-linking function before linking', waitForAsync(() => {
const log: string[] = [];
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: '<ng1-b></ng1-b>',
link: {pre: () => log.push('ng1A-pre')},
};
const ng1DirectiveB: angular.IDirective = {link: () => log.push('ng1B-post')};
// Define `Ng1ComponentAFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A></ng1A>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentAFacade, Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(log).toEqual(['ng1A-pre', 'ng1B-post']);
});
}));
it('should run the post-linking function after linking (link: object)', waitForAsync(() => {
const log: string[] = [];
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: '<ng1-b></ng1-b>',
link: {post: () => log.push('ng1A-post')},
};
const ng1DirectiveB: angular.IDirective = {link: () => log.push('ng1B-post')};
// Define `Ng1ComponentAFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A></ng1A>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentAFacade, Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(log).toEqual(['ng1B-post', 'ng1A-post']);
});
}));
it('should run the post-linking function after linking (link: function)', waitForAsync(() => {
const log: string[] = [];
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: '<ng1-b></ng1-b>',
link: () => log.push('ng1A-post'),
};
const ng1DirectiveB: angular.IDirective = {link: () => log.push('ng1B-post')};
// Define `Ng1ComponentAFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A></ng1A>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentAFacade, Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(log).toEqual(['ng1B-post', 'ng1A-post']);
});
}));
it('should run the post-linking function before `$postLink`', waitForAsync(() => {
const log: string[] = [];
// Define `ng1Directive`
const ng1Directive: angular.IDirective = {
template: '',
link: () => log.push('ng1-post'),
controller: class {
$postLink() {
log.push('ng1-$post');
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1', [])
.directive('ng1', () => ng1Directive)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(log).toEqual(['ng1-post', 'ng1-$post']);
});
}));
}); | {
"end_byte": 46920,
"start_byte": 38635,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_46926_55138 | describe('controller', () => {
it('should support `controllerAs`', waitForAsync(() => {
// Define `ng1Directive`
const ng1Directive: angular.IDirective = {
template: '{{ vm.scope }}; {{ vm.isClass }}; {{ vm.hasElement }}; {{ vm.isPublished() }}',
scope: true,
controllerAs: 'vm',
controller: class {
hasElement: string;
isClass: string = '';
scope: string;
constructor(
public $element: angular.IAugmentedJQuery,
$scope: angular.IScope,
) {
this.hasElement = $element[0].nodeName;
this.scope = $scope.$parent.$parent === $scope.$root ? 'scope' : 'wrong-scope';
this.verifyIAmAClass();
}
isPublished() {
return this.$element.controller?.('ng1') === this ? 'published' : 'not-published';
}
verifyIAmAClass() {
this.isClass = 'isClass';
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1', () => ng1Directive)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('scope; isClass; NG1; published');
});
}));
it('should support `bindToController` (boolean)', waitForAsync(() => {
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: 'Scope: {{ title }}; Controller: {{ $ctrl.title }}',
scope: {title: '@'},
bindToController: false,
controllerAs: '$ctrl',
controller: class {},
};
const ng1DirectiveB: angular.IDirective = {
template: 'Scope: {{ title }}; Controller: {{ $ctrl.title }}',
scope: {title: '@'},
bindToController: true,
controllerAs: '$ctrl',
controller: class {},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
@Input() title: string = '';
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
@Input() title: string = '';
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1A title="WORKS"></ng1A> |
<ng1B title="WORKS"></ng1B>
`,
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
schemas: [NO_ERRORS_SCHEMA],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe(
'Scope: WORKS; Controller: | Scope: ; Controller: WORKS',
);
});
}));
it('should support `bindToController` (object)', waitForAsync(() => {
// Define `ng1Directive`
const ng1Directive: angular.IDirective = {
template: '{{ $ctrl.title }}',
scope: {},
bindToController: {title: '@'},
controllerAs: '$ctrl',
controller: class {},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
@Input() title: string = '';
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1 title="WORKS"></ng1>',
standalone: false,
})
class Ng2Component {
dataA = 'foo';
dataB = 'bar';
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1', () => ng1Directive)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('WORKS');
});
}));
it('should support `controller` as string', waitForAsync(() => {
// Define `ng1Directive`
const ng1Directive: angular.IDirective = {
template: '{{ $ctrl.title }} {{ $ctrl.text }}',
scope: {title: '@'},
bindToController: true,
controller: 'Ng1Controller as $ctrl',
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
@Input() title: string = '';
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1 title="WORKS"></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.controller(
'Ng1Controller',
class {
text = 'GREAT';
},
)
.directive('ng1', () => ng1Directive)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('WORKS GREAT');
});
})); | {
"end_byte": 55138,
"start_byte": 46926,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_55146_59124 | it('should insert the compiled content before instantiating the controller', waitForAsync(() => {
let compiledContent: string;
let getCurrentContent: () => string;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'Hello, {{ $ctrl.name }}!',
controller: class {
name = 'world';
constructor($element: angular.IAugmentedJQuery) {
getCurrentContent = () => $element.text!();
compiledContent = getCurrentContent();
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(compiledContent)).toBe('Hello, {{ $ctrl.name }}!');
expect(multiTrim(getCurrentContent())).toBe('Hello, world!');
});
}));
});
describe('require', () => {
// NOT YET SUPPORTED
xdescribe('in pre-/post-link', () => {
it('should resolve to its own controller if falsy', waitForAsync(() => {
// Define `ng1Directive`
const ng1Directive: angular.IDirective = {
template: 'Pre: {{ pre }} | Post: {{ post }}',
controller: class {
value = 'foo';
},
link: {
pre: function (scope: any, elem: any, attrs: any, ctrl: any) {
scope['pre'] = ctrl.value;
},
post: function (scope: any, elem: any, attrs: any, ctrl: any) {
scope['post'] = ctrl.value;
},
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1', () => ng1Directive)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(document.body.textContent)).toBe('Pre: foo | Post: foo');
});
}));
// TODO: Add more tests
}); | {
"end_byte": 59124,
"start_byte": 55146,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_59132_66718 | describe('in controller', () => {
it('should be available to children', waitForAsync(() => {
// Define `ng1Component`
const ng1ComponentA: angular.IComponent = {
template: '<ng1-b></ng1-b>',
controller: class {
value = 'ng1A';
},
};
const ng1ComponentB: angular.IComponent = {
template: 'Required: {{ $ctrl.required.value }}',
require: {required: '^^ng1A'},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A></ng1A>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1A', ng1ComponentA)
.component('ng1B', ng1ComponentB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('Required: ng1A');
});
}));
it('should throw if required controller cannot be found', waitForAsync(() => {
// Define `ng1Component`
const ng1ComponentA: angular.IComponent = {require: {foo: 'iDoNotExist'}};
const ng1ComponentB: angular.IComponent = {require: {foo: '^iDoNotExist'}};
const ng1ComponentC: angular.IComponent = {require: {foo: '^^iDoNotExist'}};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
@Directive({
selector: 'ng1C',
standalone: false,
})
class Ng1ComponentCFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1C', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2-a',
template: '<ng1A></ng1A>',
standalone: false,
})
class Ng2ComponentA {}
@Component({
selector: 'ng2-b',
template: '<ng1B></ng1B>',
standalone: false,
})
class Ng2ComponentB {}
@Component({
selector: 'ng2-c',
template: '<ng1C></ng1C>',
standalone: false,
})
class Ng2ComponentC {}
// Define `ng1Module`
const mockExceptionHandler = jasmine.createSpy($EXCEPTION_HANDLER);
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1A', ng1ComponentA)
.component('ng1B', ng1ComponentB)
.component('ng1C', ng1ComponentC)
.directive('ng2A', downgradeComponent({component: Ng2ComponentA}))
.directive('ng2B', downgradeComponent({component: Ng2ComponentB}))
.directive('ng2C', downgradeComponent({component: Ng2ComponentC}))
.value($EXCEPTION_HANDLER, mockExceptionHandler);
// Define `Ng2Module`
@NgModule({
declarations: [
Ng1ComponentAFacade,
Ng1ComponentBFacade,
Ng1ComponentCFacade,
Ng2ComponentA,
Ng2ComponentB,
Ng2ComponentC,
],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const elementA = html(`<ng2-a></ng2-a>`);
const elementB = html(`<ng2-b></ng2-b>`);
const elementC = html(`<ng2-c></ng2-c>`);
bootstrap(platformBrowserDynamic(), Ng2Module, elementA, ng1Module).then(() => {
expect(mockExceptionHandler).toHaveBeenCalledWith(
new Error("Unable to find required 'iDoNotExist' in upgraded directive 'ng1A'."),
);
});
bootstrap(platformBrowserDynamic(), Ng2Module, elementB, ng1Module).then(() => {
expect(mockExceptionHandler).toHaveBeenCalledWith(
new Error("Unable to find required '^iDoNotExist' in upgraded directive 'ng1B'."),
);
});
bootstrap(platformBrowserDynamic(), Ng2Module, elementC, ng1Module).then(() => {
expect(mockExceptionHandler).toHaveBeenCalledWith(
new Error("Unable to find required '^^iDoNotExist' in upgraded directive 'ng1C'."),
);
});
}));
it('should not throw if missing required controller is optional', waitForAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {
require: {
foo: '?iDoNotExist',
bar: '^?iDoNotExist',
baz: '?^^iDoNotExist',
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const mockExceptionHandler = jasmine.createSpy($EXCEPTION_HANDLER);
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}))
.value($EXCEPTION_HANDLER, mockExceptionHandler);
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(mockExceptionHandler).not.toHaveBeenCalled();
});
})); | {
"end_byte": 66718,
"start_byte": 59132,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_66728_74213 | it('should assign resolved values to the controller instance (if `require` is not object)', waitForAsync(() => {
// Define `ng1Component`
const ng1ComponentA: angular.IComponent = {
template: 'ng1A(<div><ng2></ng2></div>)',
controller: class {
value = 'A';
},
};
const ng1ComponentB: angular.IComponent = {
template: `ng1B({{ $ctrl.getProps() }})`,
require: '^ng1A',
controller: class {
getProps() {
// If all goes well, there should be no keys on `this`
return Object.keys(this).join(', ');
}
},
};
const ng1ComponentC: angular.IComponent = {
template: `ng1C({{ $ctrl.getProps() }})`,
require: ['?ng1A', '^ng1A', '^^ng1A', 'ng1C', '^ng1C', '?^^ng1C'],
controller: class {
getProps() {
// If all goes well, there should be no keys on `this`
return Object.keys(this).join(', ');
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
@Directive({
selector: 'ng1C',
standalone: false,
})
class Ng1ComponentCFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1C', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: 'ng2(<div><ng1B></ng1B> | <ng1C></ng1C></div>)',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1A', ng1ComponentA)
.component('ng1B', ng1ComponentB)
.component('ng1C', ng1ComponentC)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentBFacade, Ng1ComponentCFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng1-a></ng1-a>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('ng1A(ng2(ng1B() | ng1C()))');
});
}));
it('should assign resolved values to the controller instance (if `require` is object)', waitForAsync(() => {
// Define `ng1Component`
const ng1ComponentA: angular.IComponent = {
template: 'ng1A(<div><ng2></ng2></div>)',
controller: class {
value = 'A';
},
};
const ng1ComponentB: angular.IComponent = {
template: `ng1B(
ng1A: {{ $ctrl.ng1ASelf.value }} |
^ng1A: {{ $ctrl.ng1ASelfUp.value }} |
^^ng1A: {{ $ctrl.ng1AParentUp.value }} |
ng1B: {{ $ctrl.ng1BSelf.value }} |
^ng1B: {{ $ctrl.ng1BSelfUp.value }} |
^^ng1B: {{ $ctrl.ng1BParentUp.value }}
)`,
require: {
ng1ASelf: '?ng1A',
ng1ASelfUp: '^ng1A',
ng1AParentUp: '^^ng1A',
ng1BSelf: 'ng1B',
ng1BSelfUp: '^ng1B',
ng1BParentUp: '?^^ng1B',
},
controller: class {
value = 'B';
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: 'ng2(<div><ng1B></ng1B></div>)',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1A', ng1ComponentA)
.component('ng1B', ng1ComponentB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng1-a></ng1-a>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe(
'ng1A(ng2(ng1B( ng1A: | ^ng1A: A | ^^ng1A: A | ng1B: B | ^ng1B: B | ^^ng1B: )))',
);
});
}));
it('should assign to controller before calling `$onInit()`', waitForAsync(() => {
// Define `ng1Component`
const ng1ComponentA: angular.IComponent = {
template: '<ng2></ng2>',
controller: class {
value = 'ng1A';
},
};
const ng1ComponentB: angular.IComponent = {
template: '$onInit: {{ $ctrl.onInitValue }}',
require: {required: '^^ng1A'},
controller: class {
$onInit() {
const self = this as any;
self.onInitValue = self.required.value;
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1B></ng1B>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1A', ng1ComponentA)
.component('ng1B', ng1ComponentB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng1-a></ng1-a>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('$onInit: ng1A');
});
})); | {
"end_byte": 74213,
"start_byte": 66728,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_74223_76530 | it('should use the key as name if the required controller name is omitted', waitForAsync(() => {
// Define `ng1Component`
const ng1ComponentA: angular.IComponent = {
template: '<ng1-b></ng1-b>',
controller: class {
value = 'A';
},
};
const ng1ComponentB: angular.IComponent = {
template: '<ng2></ng2>',
controller: class {
value = 'B';
},
};
const ng1ComponentC: angular.IComponent = {
template:
'ng1A: {{ $ctrl.ng1A.value }} | ng1B: {{ $ctrl.ng1B.value }} | ng1C: {{ $ctrl.ng1C.value }}',
require: {
ng1A: '^^',
ng1B: '?^',
ng1C: '',
},
controller: class {
value = 'C';
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1C',
standalone: false,
})
class Ng1ComponentCFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1C', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1C></ng1C>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1A', ng1ComponentA)
.component('ng1B', ng1ComponentB)
.component('ng1C', ng1ComponentC)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentCFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html('<ng1-a></ng1-a>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('ng1A: A | ng1B: B | ng1C: C');
});
}));
});
}); | {
"end_byte": 76530,
"start_byte": 74223,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_76536_83465 | describe('transclusion', () => {
it('should support single-slot transclusion', waitForAsync(() => {
let ng2ComponentAInstance: Ng2ComponentA;
let ng2ComponentBInstance: Ng2ComponentB;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'ng1(<div ng-transclude></div>)',
transclude: true,
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2A',
template: 'ng2A(<ng1>{{ value }} | <ng2B *ngIf="showB"></ng2B></ng1>)',
standalone: false,
})
class Ng2ComponentA {
value = 'foo';
showB = false;
constructor() {
ng2ComponentAInstance = this;
}
}
@Component({
selector: 'ng2B',
template: 'ng2B({{ value }})',
standalone: false,
})
class Ng2ComponentB {
value = 'bar';
constructor() {
ng2ComponentBInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2A', downgradeComponent({component: Ng2ComponentA}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2ComponentA, Ng2ComponentB],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2-a></ng2-a>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
expect(multiTrim(element.textContent)).toBe('ng2A(ng1(foo | ))');
ng2ComponentAInstance.value = 'baz';
ng2ComponentAInstance.showB = true;
$digest(adapter);
expect(multiTrim(element.textContent)).toBe('ng2A(ng1(baz | ng2B(bar)))');
ng2ComponentBInstance.value = 'qux';
$digest(adapter);
expect(multiTrim(element.textContent)).toBe('ng2A(ng1(baz | ng2B(qux)))');
});
}));
it('should support single-slot transclusion with fallback content', waitForAsync(() => {
let ng1ControllerInstances: any[] = [];
let ng2ComponentInstance: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'ng1(<div ng-transclude>{{ $ctrl.value }}</div>)',
transclude: true,
controller: class {
value = 'from-ng1';
constructor() {
ng1ControllerInstances.push(this);
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: 'ng2(<ng1>{{ value }}</ng1> | <ng1></ng1>)',
standalone: false,
})
class Ng2Component {
value = 'from-ng2';
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
expect(multiTrim(element.textContent)).toBe('ng2(ng1(from-ng2) | ng1(from-ng1))');
ng1ControllerInstances.forEach((ctrl) => (ctrl.value = 'ng1-foo'));
ng2ComponentInstance.value = 'ng2-bar';
$digest(adapter);
expect(multiTrim(element.textContent)).toBe('ng2(ng1(ng2-bar) | ng1(ng1-foo))');
});
}));
it('should support multi-slot transclusion', waitForAsync(() => {
let ng2ComponentInstance: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template:
'ng1(x(<div ng-transclude="slotX"></div>) | y(<div ng-transclude="slotY"></div>))',
transclude: {slotX: 'contentX', slotY: 'contentY'},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: ` ng2(
<ng1>
<content-x>{{ x }}1</content-x>
<content-y>{{ y }}1</content-y>
<content-x>{{ x }}2</content-x>
<content-y>{{ y }}2</content-y>
</ng1>
)`,
standalone: false,
})
class Ng2Component {
x = 'foo';
y = 'bar';
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2Component],
schemas: [NO_ERRORS_SCHEMA],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(foo1foo2)|y(bar1bar2)))');
ng2ComponentInstance.x = 'baz';
ng2ComponentInstance.y = 'qux';
$digest(adapter);
expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz1baz2)|y(qux1qux2)))');
});
})); | {
"end_byte": 83465,
"start_byte": 76536,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_83473_90855 | it('should support default slot (with fallback content)', waitForAsync(() => {
let ng1ControllerInstances: any[] = [];
let ng2ComponentInstance: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'ng1(default(<div ng-transclude="">fallback-{{ $ctrl.value }}</div>))',
transclude: {slotX: 'contentX', slotY: 'contentY'},
controller: class {
value = 'ng1';
constructor() {
ng1ControllerInstances.push(this);
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: ` ng2(
<ng1>
({{ x }})
<content-x>ignored x</content-x>
{{ x }}-<span>{{ y }}</span>
<content-y>ignored y</content-y>
<span>({{ y }})</span>
</ng1>
|
<!--
Remove any whitespace, because in AngularJS versions prior to 1.6
even whitespace counts as transcluded content.
-->
<ng1><content-x>ignored x</content-x><content-y>ignored y</content-y></ng1>
)`,
standalone: false,
})
class Ng2Component {
x = 'foo';
y = 'bar';
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2Component],
schemas: [NO_ERRORS_SCHEMA],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
expect(multiTrim(element.textContent, true)).toBe(
'ng2(ng1(default((foo)foo-bar(bar)))|ng1(default(fallback-ng1)))',
);
ng1ControllerInstances.forEach((ctrl) => (ctrl.value = 'ng1-plus'));
ng2ComponentInstance.x = 'baz';
ng2ComponentInstance.y = 'qux';
$digest(adapter);
expect(multiTrim(element.textContent, true)).toBe(
'ng2(ng1(default((baz)baz-qux(qux)))|ng1(default(fallback-ng1-plus)))',
);
});
}));
it('should support optional transclusion slots (with fallback content)', waitForAsync(() => {
let ng1ControllerInstances: any[] = [];
let ng2ComponentInstance: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: `
ng1(
x(<div ng-transclude="slotX">{{ $ctrl.x }}</div>) |
y(<div ng-transclude="slotY">{{ $ctrl.y }}</div>)
)`,
transclude: {slotX: '?contentX', slotY: '?contentY'},
controller: class {
x = 'ng1X';
y = 'ng1Y';
constructor() {
ng1ControllerInstances.push(this);
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: ` ng2(
<ng1
><content-x>{{ x }}</content-x></ng1
>
|
<ng1
><content-y>{{ y }}</content-y></ng1
>
)`,
standalone: false,
})
class Ng2Component {
x = 'ng2X';
y = 'ng2Y';
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2Component],
schemas: [NO_ERRORS_SCHEMA],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
expect(multiTrim(element.textContent, true)).toBe(
'ng2(ng1(x(ng2X)|y(ng1Y))|ng1(x(ng1X)|y(ng2Y)))',
);
ng1ControllerInstances.forEach((ctrl) => {
ctrl.x = 'ng1X-foo';
ctrl.y = 'ng1Y-bar';
});
ng2ComponentInstance.x = 'ng2X-baz';
ng2ComponentInstance.y = 'ng2Y-qux';
$digest(adapter);
expect(multiTrim(element.textContent, true)).toBe(
'ng2(ng1(x(ng2X-baz)|y(ng1Y-bar))|ng1(x(ng1X-foo)|y(ng2Y-qux)))',
);
});
}));
it('should throw if a non-optional slot is not filled', waitForAsync(() => {
let errorMessage: string;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: '',
transclude: {slotX: '?contentX', slotY: 'contentY'},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.value($EXCEPTION_HANDLER, (error: Error) => (errorMessage = error.message))
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
expect(errorMessage).toContain("Required transclusion slot 'slotY' on directive: ng1");
});
})); | {
"end_byte": 90855,
"start_byte": 83473,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_90863_93475 | it('should support structural directives in transcluded content', waitForAsync(() => {
let ng2ComponentInstance: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template:
'ng1(x(<div ng-transclude="slotX"></div>) | default(<div ng-transclude=""></div>))',
transclude: {slotX: 'contentX'},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: ` ng2(
<ng1>
<content-x
><div *ngIf="show">{{ x }}1</div></content-x
>
<div *ngIf="!show">{{ y }}1</div>
<content-x
><div *ngIf="!show">{{ x }}2</div></content-x
>
<div *ngIf="show">{{ y }}2</div>
</ng1>
)`,
standalone: false,
})
class Ng2Component {
x = 'foo';
y = 'bar';
show = true;
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2Component],
schemas: [NO_ERRORS_SCHEMA],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(foo1)|default(bar2)))');
ng2ComponentInstance.x = 'baz';
ng2ComponentInstance.y = 'qux';
ng2ComponentInstance.show = false;
$digest(adapter);
expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz2)|default(qux1)))');
ng2ComponentInstance.show = true;
$digest(adapter);
expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz1)|default(qux2)))');
});
}));
}); | {
"end_byte": 93475,
"start_byte": 90863,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_93481_99663 | describe('lifecycle hooks', () => {
it('should call `$onChanges()` on binding destination (prototype)', fakeAsync(() => {
const scopeOnChanges = jasmine.createSpy('scopeOnChanges');
const controllerOnChangesA = jasmine.createSpy('controllerOnChangesA');
const controllerOnChangesB = jasmine.createSpy('controllerOnChangesB');
let ng2ComponentInstance: Ng2Component;
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: '',
scope: {inputA: '<'},
bindToController: false,
controllerAs: '$ctrl',
controller: class {
$onChanges(changes: SimpleChanges) {
controllerOnChangesA(changes);
}
},
};
const ng1DirectiveB: angular.IDirective = {
template: '',
scope: {inputB: '<'},
bindToController: true,
controllerAs: '$ctrl',
controller: class {
$onChanges(changes: SimpleChanges) {
controllerOnChangesB(changes);
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
@Input() inputA: any;
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
@Input() inputB: any;
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A [inputA]="data"></ng1A> | <ng1B [inputB]="data"></ng1B>',
standalone: false,
})
class Ng2Component {
data = {foo: 'bar'};
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}))
.run(($rootScope: angular.IRootScopeService) => {
Object.getPrototypeOf($rootScope)['$onChanges'] = scopeOnChanges;
});
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
// Initial change
expect(scopeOnChanges.calls.count()).toBe(1);
expect(controllerOnChangesA).not.toHaveBeenCalled();
expect(controllerOnChangesB.calls.count()).toBe(1);
expect(scopeOnChanges.calls.argsFor(0)[0]).toEqual({inputA: jasmine.any(Object)});
expect(scopeOnChanges.calls.argsFor(0)[0].inputA.currentValue).toEqual({foo: 'bar'});
expect(scopeOnChanges.calls.argsFor(0)[0].inputA.isFirstChange()).toBe(true);
expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.currentValue).toEqual({
foo: 'bar',
});
expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.isFirstChange()).toBe(true);
// Change: Re-assign `data`
ng2ComponentInstance.data = {foo: 'baz'};
$digest(adapter);
tick();
expect(scopeOnChanges.calls.count()).toBe(2);
expect(controllerOnChangesA).not.toHaveBeenCalled();
expect(controllerOnChangesB.calls.count()).toBe(2);
expect(scopeOnChanges.calls.argsFor(1)[0]).toEqual({inputA: jasmine.any(Object)});
expect(scopeOnChanges.calls.argsFor(1)[0].inputA.previousValue).toEqual({foo: 'bar'});
expect(scopeOnChanges.calls.argsFor(1)[0].inputA.currentValue).toEqual({foo: 'baz'});
expect(scopeOnChanges.calls.argsFor(1)[0].inputA.isFirstChange()).toBe(false);
expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.previousValue).toEqual({
foo: 'bar',
});
expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.currentValue).toEqual({
foo: 'baz',
});
expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.isFirstChange()).toBe(false);
// No change: Update internal property
ng2ComponentInstance.data.foo = 'qux';
$digest(adapter);
tick();
expect(scopeOnChanges.calls.count()).toBe(2);
expect(controllerOnChangesA).not.toHaveBeenCalled();
expect(controllerOnChangesB.calls.count()).toBe(2);
// Change: Re-assign `data` (even if it looks the same)
ng2ComponentInstance.data = {foo: 'qux'};
$digest(adapter);
tick();
expect(scopeOnChanges.calls.count()).toBe(3);
expect(controllerOnChangesA).not.toHaveBeenCalled();
expect(controllerOnChangesB.calls.count()).toBe(3);
expect(scopeOnChanges.calls.argsFor(2)[0]).toEqual({inputA: jasmine.any(Object)});
expect(scopeOnChanges.calls.argsFor(2)[0].inputA.previousValue).toEqual({foo: 'qux'});
expect(scopeOnChanges.calls.argsFor(2)[0].inputA.currentValue).toEqual({foo: 'qux'});
expect(scopeOnChanges.calls.argsFor(2)[0].inputA.isFirstChange()).toBe(false);
expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.previousValue).toEqual({
foo: 'qux',
});
expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.currentValue).toEqual({
foo: 'qux',
});
expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.isFirstChange()).toBe(false);
});
})); | {
"end_byte": 99663,
"start_byte": 93481,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_99671_105842 | it('should call `$onChanges()` on binding destination (instance)', fakeAsync(() => {
const scopeOnChangesA = jasmine.createSpy('scopeOnChangesA');
const scopeOnChangesB = jasmine.createSpy('scopeOnChangesB');
const controllerOnChangesA = jasmine.createSpy('controllerOnChangesA');
const controllerOnChangesB = jasmine.createSpy('controllerOnChangesB');
let ng2ComponentInstance: Ng2Component;
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: '',
scope: {inputA: '<'},
bindToController: false,
controllerAs: '$ctrl',
controller: class {
constructor($scope: angular.IScope) {
$scope['$onChanges'] = scopeOnChangesA;
(this as any).$onChanges = controllerOnChangesA;
}
},
};
const ng1DirectiveB: angular.IDirective = {
template: '',
scope: {inputB: '<'},
bindToController: true,
controllerAs: '$ctrl',
controller: class {
constructor($scope: angular.IScope) {
$scope['$onChanges'] = scopeOnChangesB;
(this as any).$onChanges = controllerOnChangesB;
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
@Input() inputA: any;
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
@Input() inputB: any;
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A [inputA]="data"></ng1A> | <ng1B [inputB]="data"></ng1B>',
standalone: false,
})
class Ng2Component {
data = {foo: 'bar'};
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
// Initial change
expect(scopeOnChangesA.calls.count()).toBe(1);
expect(scopeOnChangesB).not.toHaveBeenCalled();
expect(controllerOnChangesA).not.toHaveBeenCalled();
expect(controllerOnChangesB.calls.count()).toBe(1);
expect(scopeOnChangesA.calls.argsFor(0)[0].inputA.currentValue).toEqual({foo: 'bar'});
expect(scopeOnChangesA.calls.argsFor(0)[0].inputA.isFirstChange()).toBe(true);
expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.currentValue).toEqual({
foo: 'bar',
});
expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.isFirstChange()).toBe(true);
// Change: Re-assign `data`
ng2ComponentInstance.data = {foo: 'baz'};
$digest(adapter);
tick();
expect(scopeOnChangesA.calls.count()).toBe(2);
expect(scopeOnChangesB).not.toHaveBeenCalled();
expect(controllerOnChangesA).not.toHaveBeenCalled();
expect(controllerOnChangesB.calls.count()).toBe(2);
expect(scopeOnChangesA.calls.argsFor(1)[0].inputA.previousValue).toEqual({foo: 'bar'});
expect(scopeOnChangesA.calls.argsFor(1)[0].inputA.currentValue).toEqual({foo: 'baz'});
expect(scopeOnChangesA.calls.argsFor(1)[0].inputA.isFirstChange()).toBe(false);
expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.previousValue).toEqual({
foo: 'bar',
});
expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.currentValue).toEqual({
foo: 'baz',
});
expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.isFirstChange()).toBe(false);
// No change: Update internal property
ng2ComponentInstance.data.foo = 'qux';
$digest(adapter);
tick();
expect(scopeOnChangesA.calls.count()).toBe(2);
expect(scopeOnChangesB).not.toHaveBeenCalled();
expect(controllerOnChangesA).not.toHaveBeenCalled();
expect(controllerOnChangesB.calls.count()).toBe(2);
// Change: Re-assign `data` (even if it looks the same)
ng2ComponentInstance.data = {foo: 'qux'};
$digest(adapter);
tick();
expect(scopeOnChangesA.calls.count()).toBe(3);
expect(scopeOnChangesB).not.toHaveBeenCalled();
expect(controllerOnChangesA).not.toHaveBeenCalled();
expect(controllerOnChangesB.calls.count()).toBe(3);
expect(scopeOnChangesA.calls.argsFor(2)[0].inputA.previousValue).toEqual({foo: 'qux'});
expect(scopeOnChangesA.calls.argsFor(2)[0].inputA.currentValue).toEqual({foo: 'qux'});
expect(scopeOnChangesA.calls.argsFor(2)[0].inputA.isFirstChange()).toBe(false);
expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.previousValue).toEqual({
foo: 'qux',
});
expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.currentValue).toEqual({
foo: 'qux',
});
expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.isFirstChange()).toBe(false);
});
})); | {
"end_byte": 105842,
"start_byte": 99671,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_105850_113412 | it('should call `$onInit()` on controller', waitForAsync(() => {
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: 'Called: {{ called }}',
bindToController: false,
controller: class {
constructor(private $scope: angular.IScope) {
$scope['called'] = 'no';
}
$onInit() {
this.$scope['called'] = 'yes';
}
},
};
const ng1DirectiveB: angular.IDirective = {
template: 'Called: {{ called }}',
bindToController: true,
controller: class {
constructor($scope: angular.IScope) {
$scope['called'] = 'no';
(this as any)['$onInit'] = () => ($scope['called'] = 'yes');
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A></ng1A> | <ng1B></ng1B>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('Called: yes | Called: yes');
});
}));
it('should not call `$onInit()` on scope', waitForAsync(() => {
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: 'Called: {{ called }}',
bindToController: false,
controller: class {
constructor($scope: angular.IScope) {
$scope['called'] = 'no';
$scope['$onInit'] = () => ($scope['called'] = 'yes');
Object.getPrototypeOf($scope)['$onInit'] = () => ($scope['called'] = 'yes');
}
},
};
const ng1DirectiveB: angular.IDirective = {
template: 'Called: {{ called }}',
bindToController: true,
controller: class {
constructor($scope: angular.IScope) {
$scope['called'] = 'no';
$scope['$onInit'] = () => ($scope['called'] = 'yes');
Object.getPrototypeOf($scope)['$onInit'] = () => ($scope['called'] = 'yes');
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A></ng1A> | <ng1B></ng1B>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('Called: no | Called: no');
});
}));
it('should call `$postLink()` on controller', waitForAsync(() => {
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: 'Called: {{ called }}',
bindToController: false,
controller: class {
constructor(private $scope: angular.IScope) {
$scope['called'] = 'no';
}
$postLink() {
this.$scope['called'] = 'yes';
}
},
};
const ng1DirectiveB: angular.IDirective = {
template: 'Called: {{ called }}',
bindToController: true,
controller: class {
constructor($scope: angular.IScope) {
$scope['called'] = 'no';
(this as any)['$postLink'] = () => ($scope['called'] = 'yes');
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A></ng1A> | <ng1B></ng1B>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('Called: yes | Called: yes');
});
})); | {
"end_byte": 113412,
"start_byte": 105850,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_113420_121763 | it('should not call `$postLink()` on scope', waitForAsync(() => {
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: 'Called: {{ called }}',
bindToController: false,
controller: class {
constructor($scope: angular.IScope) {
$scope['called'] = 'no';
$scope['$postLink'] = () => ($scope['called'] = 'yes');
Object.getPrototypeOf($scope)['$postLink'] = () => ($scope['called'] = 'yes');
}
},
};
const ng1DirectiveB: angular.IDirective = {
template: 'Called: {{ called }}',
bindToController: true,
controller: class {
constructor($scope: angular.IScope) {
$scope['called'] = 'no';
$scope['$postLink'] = () => ($scope['called'] = 'yes');
Object.getPrototypeOf($scope)['$postLink'] = () => ($scope['called'] = 'yes');
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A></ng1A> | <ng1B></ng1B>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe('Called: no | Called: no');
});
}));
it('should call `$doCheck()` on controller', waitForAsync(() => {
const controllerDoCheckA = jasmine.createSpy('controllerDoCheckA');
const controllerDoCheckB = jasmine.createSpy('controllerDoCheckB');
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: 'ng1A',
bindToController: false,
controller: class {
$doCheck() {
controllerDoCheckA();
}
},
};
const ng1DirectiveB: angular.IDirective = {
template: 'ng1B',
bindToController: true,
controller: class {
constructor() {
(this as any)['$doCheck'] = controllerDoCheckB;
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A></ng1A> | <ng1B></ng1B>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
// Get to a stable `$digest` state.
$digest(adapter);
// Initial change.
// (Do not use a specific number due to differences between AngularJS 1.5/1.6.)
expect(controllerDoCheckA.calls.count()).toBeGreaterThan(0);
expect(controllerDoCheckB.calls.count()).toBeGreaterThan(0);
controllerDoCheckA.calls.reset();
controllerDoCheckB.calls.reset();
// Run a `$digest`
$digest(adapter);
expect(controllerDoCheckA.calls.count()).toBe(1);
expect(controllerDoCheckB.calls.count()).toBe(1);
// Run another `$digest`
$digest(adapter);
expect(controllerDoCheckA.calls.count()).toBe(2);
expect(controllerDoCheckB.calls.count()).toBe(2);
});
}));
it('should not call `$doCheck()` on scope', waitForAsync(() => {
const scopeDoCheck = jasmine.createSpy('scopeDoCheck');
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: 'ng1A',
bindToController: false,
controller: class {
constructor(private $scope: angular.IScope) {
$scope['$doCheck'] = scopeDoCheck;
}
},
};
const ng1DirectiveB: angular.IDirective = {
template: 'ng1B',
bindToController: true,
controller: class {
constructor(private $scope: angular.IScope) {
$scope['$doCheck'] = scopeDoCheck;
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1A></ng1A> | <ng1B></ng1B>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
// Initial change
expect(scopeDoCheck).not.toHaveBeenCalled();
// Run a `$digest`
$digest(adapter);
expect(scopeDoCheck).not.toHaveBeenCalled();
// Run another `$digest`
$digest(adapter);
expect(scopeDoCheck).not.toHaveBeenCalled();
});
})); | {
"end_byte": 121763,
"start_byte": 113420,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_121771_128917 | it('should call `$onDestroy()` on controller', waitForAsync(() => {
const controllerOnDestroyA = jasmine.createSpy('controllerOnDestroyA');
const controllerOnDestroyB = jasmine.createSpy('controllerOnDestroyB');
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: 'ng1A',
scope: {},
bindToController: false,
controllerAs: '$ctrl',
controller: class {
$onDestroy() {
controllerOnDestroyA();
}
},
};
const ng1DirectiveB: angular.IDirective = {
template: 'ng1B',
scope: {},
bindToController: true,
controllerAs: '$ctrl',
controller: class {
constructor() {
(this as any)['$onDestroy'] = controllerOnDestroyB;
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<div *ngIf="show"><ng1A></ng1A> | <ng1B></ng1B></div>',
standalone: false,
})
class Ng2Component {
@Input() show: boolean = false;
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html('<ng2 [show]="!destroyFromNg2" ng-if="!destroyFromNg1"></ng2>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
const $rootScope = adapter.$injector.get('$rootScope') as angular.IRootScopeService;
expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B');
expect(controllerOnDestroyA).not.toHaveBeenCalled();
expect(controllerOnDestroyB).not.toHaveBeenCalled();
$rootScope.$apply('destroyFromNg1 = true');
expect(multiTrim(document.body.textContent)).toBe('');
expect(controllerOnDestroyA).toHaveBeenCalled();
expect(controllerOnDestroyB).toHaveBeenCalled();
controllerOnDestroyA.calls.reset();
controllerOnDestroyB.calls.reset();
$rootScope.$apply('destroyFromNg1 = false');
expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B');
expect(controllerOnDestroyA).not.toHaveBeenCalled();
expect(controllerOnDestroyB).not.toHaveBeenCalled();
$rootScope.$apply('destroyFromNg2 = true');
expect(multiTrim(document.body.textContent)).toBe('');
expect(controllerOnDestroyA).toHaveBeenCalled();
expect(controllerOnDestroyB).toHaveBeenCalled();
});
}));
it('should not call `$onDestroy()` on scope', waitForAsync(() => {
const scopeOnDestroy = jasmine.createSpy('scopeOnDestroy');
// Define `ng1Directive`
const ng1DirectiveA: angular.IDirective = {
template: 'ng1A',
scope: {},
bindToController: false,
controllerAs: '$ctrl',
controller: class {
constructor($scope: angular.IScope) {
$scope['$onDestroy'] = scopeOnDestroy;
Object.getPrototypeOf($scope)['$onDestroy'] = scopeOnDestroy;
}
},
};
const ng1DirectiveB: angular.IDirective = {
template: 'ng1B',
scope: {},
bindToController: true,
controllerAs: '$ctrl',
controller: class {
constructor($scope: angular.IScope) {
$scope['$onDestroy'] = scopeOnDestroy;
Object.getPrototypeOf($scope)['$onDestroy'] = scopeOnDestroy;
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<div *ngIf="show"><ng1A></ng1A> | <ng1B></ng1B></div>',
standalone: false,
})
class Ng2Component {
@Input() show: boolean = false;
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.directive('ng1A', () => ng1DirectiveA)
.directive('ng1B', () => ng1DirectiveB)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html('<ng2 [show]="!destroyFromNg2" ng-if="!destroyFromNg1"></ng2>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
const $rootScope = adapter.$injector.get('$rootScope') as angular.IRootScopeService;
expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B');
expect(scopeOnDestroy).not.toHaveBeenCalled();
$rootScope.$apply('destroyFromNg1 = true');
expect(multiTrim(document.body.textContent)).toBe('');
expect(scopeOnDestroy).not.toHaveBeenCalled();
$rootScope.$apply('destroyFromNg1 = false');
expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B');
expect(scopeOnDestroy).not.toHaveBeenCalled();
$rootScope.$apply('destroyFromNg2 = true');
expect(multiTrim(document.body.textContent)).toBe('');
expect(scopeOnDestroy).not.toHaveBeenCalled();
});
})); | {
"end_byte": 128917,
"start_byte": 121771,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_128925_131150 | it('should be called in order `$onChanges()` > `$onInit()` > `$doCheck()` > `$postLink()`', waitForAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {
// `$doCheck()` will keep getting called as long as the interpolated value keeps
// changing (by appending `> $doCheck`). Only care about the first 4 values.
template: '{{ $ctrl.calls.slice(0, 4).join(" > ") }}',
bindings: {value: '<'},
controller: class {
calls: string[] = [];
$onChanges() {
this.calls.push('$onChanges');
}
$onInit() {
this.calls.push('$onInit');
}
$doCheck() {
this.calls.push('$doCheck');
}
$postLink() {
this.calls.push('$postLink');
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
@Input() value: any;
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1 value="foo"></ng1>',
standalone: false,
})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe(
'$onChanges > $onInit > $doCheck > $postLink',
);
});
}));
}); | {
"end_byte": 131150,
"start_byte": 128925,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_131156_138305 | describe('destroying the upgraded component', () => {
it('should destroy `$componentScope`', waitForAsync(() => {
const scopeDestroyListener = jasmine.createSpy('scopeDestroyListener');
let ng2ComponentAInstance: Ng2ComponentA;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
controller: class {
constructor($scope: angular.IScope) {
$scope.$on('$destroy', scopeDestroyListener);
}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2A',
template: '<ng2B *ngIf="!destroyIt"></ng2B>',
standalone: false,
})
class Ng2ComponentA {
destroyIt = false;
constructor() {
ng2ComponentAInstance = this;
}
}
@Component({
selector: 'ng2B',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2ComponentB {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2A', downgradeComponent({component: Ng2ComponentA}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2ComponentA, Ng2ComponentB],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2-a></ng2-a>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
expect(scopeDestroyListener).not.toHaveBeenCalled();
ng2ComponentAInstance.destroyIt = true;
$digest(adapter);
expect(scopeDestroyListener).toHaveBeenCalledTimes(1);
});
}));
it('should emit `$destroy` on `$element` and descendants', waitForAsync(() => {
const elementDestroyListener = jasmine.createSpy('elementDestroyListener');
const descendantDestroyListener = jasmine.createSpy('descendantDestroyListener');
let ng2ComponentAInstance: Ng2ComponentA;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
controller: class {
constructor($element: angular.IAugmentedJQuery) {
$element.on!('$destroy', elementDestroyListener);
$element.contents!().on!('$destroy', descendantDestroyListener);
}
},
template: '<div></div>',
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2A',
template: '<ng2B *ngIf="!destroyIt"></ng2B>',
standalone: false,
})
class Ng2ComponentA {
destroyIt = false;
constructor() {
ng2ComponentAInstance = this;
}
}
@Component({
selector: 'ng2B',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2ComponentB {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2A', downgradeComponent({component: Ng2ComponentA}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2ComponentA, Ng2ComponentB],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2-a></ng2-a>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
expect(elementDestroyListener).not.toHaveBeenCalled();
expect(descendantDestroyListener).not.toHaveBeenCalled();
ng2ComponentAInstance.destroyIt = true;
$digest(adapter);
expect(elementDestroyListener).toHaveBeenCalledTimes(1);
expect(descendantDestroyListener).toHaveBeenCalledTimes(1);
});
}));
it('should clear data on `$element` and descendants`', waitForAsync(() => {
let ng1ComponentElement: angular.IAugmentedJQuery;
let ng2ComponentAInstance: Ng2ComponentA;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
controller: class {
constructor($element: angular.IAugmentedJQuery) {
$element.data!('test', 1);
$element.contents!().data!('test', 2);
ng1ComponentElement = $element;
}
},
template: '<div></div>',
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2A',
template: '<ng2B *ngIf="!destroyIt"></ng2B>',
standalone: false,
})
class Ng2ComponentA {
destroyIt = false;
constructor() {
ng2ComponentAInstance = this;
}
}
@Component({
selector: 'ng2B',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2ComponentB {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2A', downgradeComponent({component: Ng2ComponentA}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2ComponentA, Ng2ComponentB],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2-a></ng2-a>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
expect(ng1ComponentElement.data!('test')).toBe(1);
expect(ng1ComponentElement.contents!().data!('test')).toBe(2);
ng2ComponentAInstance.destroyIt = true;
$digest(adapter);
expect(ng1ComponentElement.data!('test')).toBeUndefined();
expect(ng1ComponentElement.contents!().data!('test')).toBeUndefined();
});
})); | {
"end_byte": 138305,
"start_byte": 131156,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_138313_145184 | it('should clear dom listeners on `$element` and descendants`', waitForAsync(() => {
const elementClickListener = jasmine.createSpy('elementClickListener');
const descendantClickListener = jasmine.createSpy('descendantClickListener');
let ng1DescendantElement: angular.IAugmentedJQuery;
let ng2ComponentAInstance: Ng2ComponentA;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
controller: class {
constructor($element: angular.IAugmentedJQuery) {
ng1DescendantElement = $element.contents!();
$element.on!('click', elementClickListener);
ng1DescendantElement.on!('click', descendantClickListener);
}
},
template: '<div></div>',
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2A',
template: '<ng2B *ngIf="!destroyIt"></ng2B>',
standalone: false,
})
class Ng2ComponentA {
destroyIt = false;
constructor() {
ng2ComponentAInstance = this;
}
}
@Component({
selector: 'ng2B',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2ComponentB {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2A', downgradeComponent({component: Ng2ComponentA}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2ComponentA, Ng2ComponentB],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2-a></ng2-a>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
(ng1DescendantElement[0] as HTMLElement).click();
expect(elementClickListener).toHaveBeenCalledTimes(1);
expect(descendantClickListener).toHaveBeenCalledTimes(1);
ng2ComponentAInstance.destroyIt = true;
$digest(adapter);
(ng1DescendantElement[0] as HTMLElement).click();
expect(elementClickListener).toHaveBeenCalledTimes(1);
expect(descendantClickListener).toHaveBeenCalledTimes(1);
});
}));
it('should clean up `$doCheck()` watchers from the parent scope', waitForAsync(() => {
let ng2Component: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'ng1',
controller: class {
$doCheck() {}
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: '<ng1 *ngIf="doShow"></ng1>',
standalone: false,
})
class Ng2Component {
doShow: boolean = false;
constructor(@Inject($SCOPE) public $scope: angular.IScope) {
ng2Component = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
imports: [BrowserModule, UpgradeModule],
declarations: [Ng1ComponentFacade, Ng2Component],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
const getWatcherCount: () => number = () =>
(ng2Component.$scope as any).$$watchers.length;
const baseWatcherCount = getWatcherCount();
expect(multiTrim(document.body.textContent)).toBe('');
ng2Component.doShow = true;
$digest(adapter);
expect(multiTrim(document.body.textContent)).toBe('ng1');
expect(getWatcherCount()).toBe(baseWatcherCount + 1);
ng2Component.doShow = false;
$digest(adapter);
expect(multiTrim(document.body.textContent)).toBe('');
expect(getWatcherCount()).toBe(baseWatcherCount);
ng2Component.doShow = true;
$digest(adapter);
expect(multiTrim(document.body.textContent)).toBe('ng1');
expect(getWatcherCount()).toBe(baseWatcherCount + 1);
});
}));
});
it('should support ng2 > ng1 > ng2 (no inputs/outputs)', waitForAsync(() => {
// Define `ng1Component`
const ng1Component: angular.IComponent = {template: 'ng1X(<ng2-b></ng2-b>)'};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1X',
standalone: false,
})
class Ng1ComponentFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1X', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2-a',
template: 'ng2A(<ng1X></ng1X>)',
standalone: false,
})
class Ng2ComponentA {}
@Component({
selector: 'ng2-b',
template: 'ng2B',
standalone: false,
})
class Ng2ComponentB {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1', [])
.component('ng1X', ng1Component)
.directive('ng2A', downgradeComponent({component: Ng2ComponentA}))
.directive('ng2B', downgradeComponent({component: Ng2ComponentB}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentFacade, Ng2ComponentA, Ng2ComponentB],
imports: [BrowserModule, UpgradeModule],
schemas: [NO_ERRORS_SCHEMA],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2-a></ng2-a>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(document.body.textContent)).toBe('ng2A(ng1X(ng2B))');
});
})); | {
"end_byte": 145184,
"start_byte": 138313,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_145190_152100 | it('should support ng2 > ng1 > ng2 (with inputs/outputs)', fakeAsync(() => {
let ng2ComponentAInstance: Ng2ComponentA;
let ng2ComponentBInstance: Ng2ComponentB;
let ng1ControllerXInstance: Ng1ControllerX;
// Define `ng1Component`
class Ng1ControllerX {
ng1XInputA: string = '';
ng1XInputB: any;
ng1XInputC: any;
constructor() {
ng1ControllerXInstance = this;
}
}
const ng1Component: angular.IComponent = {
template: `
ng1X({{ $ctrl.ng1XInputA }}, {{ $ctrl.ng1XInputB.value }}, {{ $ctrl.ng1XInputC.value }}) |
<ng2-b
[ng2-b-input1]="$ctrl.ng1XInputA"
[ng2-b-input-c]="$ctrl.ng1XInputC.value"
(ng2-b-output-c)="$ctrl.ng1XInputC = {value: $event}">
</ng2-b>
`,
bindings: {
ng1XInputA: '@',
ng1XInputB: '<',
ng1XInputC: '=',
ng1XOutputA: '&',
ng1XOutputB: '&',
},
controller: Ng1ControllerX,
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1X',
standalone: false,
})
class Ng1ComponentXFacade extends UpgradeComponent {
@Input() ng1XInputA: string = '';
@Input() ng1XInputB: any;
@Input() ng1XInputC: any;
@Output() ng1XInputCChange = new EventEmitter();
@Output() ng1XOutputA = new EventEmitter();
@Output() ng1XOutputB = new EventEmitter();
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1X', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2-a',
template: `
ng2A({{ ng2ADataA.value }}, {{ ng2ADataB.value }}, {{ ng2ADataC.value }}) |
<ng1X
ng1XInputA="{{ ng2ADataA.value }}"
bind-ng1XInputB="ng2ADataB"
[(ng1XInputC)]="ng2ADataC"
(ng1XOutputA)="ng2ADataA = $event"
on-ng1XOutputB="ng2ADataB.value = $event"
>
</ng1X>
`,
standalone: false,
})
class Ng2ComponentA {
ng2ADataA = {value: 'foo'};
ng2ADataB = {value: 'bar'};
ng2ADataC = {value: 'baz'};
constructor() {
ng2ComponentAInstance = this;
}
}
@Component({
selector: 'ng2-b',
template: 'ng2B({{ ng2BInputA }}, {{ ng2BInputC }})',
standalone: false,
})
class Ng2ComponentB {
@Input('ng2BInput1') ng2BInputA: any;
@Input() ng2BInputC: any;
@Output() ng2BOutputC = new EventEmitter();
constructor() {
ng2ComponentBInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1', [])
.component('ng1X', ng1Component)
.directive('ng2A', downgradeComponent({component: Ng2ComponentA}))
.directive('ng2B', downgradeComponent({component: Ng2ComponentB}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentXFacade, Ng2ComponentA, Ng2ComponentB],
imports: [BrowserModule, UpgradeModule],
schemas: [NO_ERRORS_SCHEMA],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2-a></ng2-a>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => {
// Initial value propagation.
// (ng2A > ng1X > ng2B)
expect(multiTrim(document.body.textContent)).toBe(
'ng2A(foo, bar, baz) | ng1X(foo, bar, baz) | ng2B(foo, baz)',
);
// Update `ng2BInputA`/`ng2BInputC`.
// (Should not propagate upwards.)
ng2ComponentBInstance.ng2BInputA = 'foo2';
ng2ComponentBInstance.ng2BInputC = 'baz2';
$digest(adapter);
tick();
expect(multiTrim(document.body.textContent)).toBe(
'ng2A(foo, bar, baz) | ng1X(foo, bar, baz) | ng2B(foo2, baz2)',
);
// Emit from `ng2BOutputC`.
// (Should propagate all the way up to `ng1ADataC` and back all the way down to
// `ng2BInputC`.)
ng2ComponentBInstance.ng2BOutputC.emit('baz3');
$digest(adapter);
tick();
expect(multiTrim(document.body.textContent)).toBe(
'ng2A(foo, bar, baz3) | ng1X(foo, bar, baz3) | ng2B(foo2, baz3)',
);
// Update `ng1XInputA`/`ng1XInputB`.
// (Should not propagate upwards, only downwards.)
ng1ControllerXInstance.ng1XInputA = 'foo4';
ng1ControllerXInstance.ng1XInputB = {value: 'bar4'};
$digest(adapter);
tick();
expect(multiTrim(document.body.textContent)).toBe(
'ng2A(foo, bar, baz3) | ng1X(foo4, bar4, baz3) | ng2B(foo4, baz3)',
);
// Update `ng1XInputC`.
// (Should propagate upwards and downwards.)
ng1ControllerXInstance.ng1XInputC = {value: 'baz5'};
$digest(adapter);
tick();
expect(multiTrim(document.body.textContent)).toBe(
'ng2A(foo, bar, baz5) | ng1X(foo4, bar4, baz5) | ng2B(foo4, baz5)',
);
// Update a property on `ng1XInputC`.
// (Should propagate upwards and downwards.)
ng1ControllerXInstance.ng1XInputC.value = 'baz6';
$digest(adapter);
tick();
expect(multiTrim(document.body.textContent)).toBe(
'ng2A(foo, bar, baz6) | ng1X(foo4, bar4, baz6) | ng2B(foo4, baz6)',
);
// Emit from `ng1XOutputA`.
// (Should propagate upwards to `ng1ADataA` and back all the way down to
// `ng2BInputA`.)
(ng1ControllerXInstance as any).ng1XOutputA({value: 'foo7'});
$digest(adapter);
tick();
expect(multiTrim(document.body.textContent)).toBe(
'ng2A(foo7, bar, baz6) | ng1X(foo7, bar4, baz6) | ng2B(foo7, baz6)',
);
// Emit from `ng1XOutputB`.
// (Should propagate upwards to `ng1ADataB`, but not downwards,
// since `ng1XInputB` has been re-assigned (i.e. `ng2ADataB !== ng1XInputB`).)
(ng1ControllerXInstance as any).ng1XOutputB('bar8');
$digest(adapter);
tick();
expect(multiTrim(document.body.textContent)).toBe(
'ng2A(foo7, bar8, baz6) | ng1X(foo7, bar4, baz6) | ng2B(foo7, baz6)',
);
// Update `ng2ADataA`/`ng2ADataB`/`ng2ADataC`.
// (Should propagate everywhere.)
ng2ComponentAInstance.ng2ADataA = {value: 'foo9'};
ng2ComponentAInstance.ng2ADataB = {value: 'bar9'};
ng2ComponentAInstance.ng2ADataC = {value: 'baz9'};
$digest(adapter);
tick();
expect(multiTrim(document.body.textContent)).toBe(
'ng2A(foo9, bar9, baz9) | ng1X(foo9, bar9, baz9) | ng2B(foo9, baz9)',
);
});
})); | {
"end_byte": 152100,
"start_byte": 145190,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_component_spec.ts_152106_156003 | it('should support ng2 > ng1 > ng2 > ng1 (with `require`)', waitForAsync(() => {
// Define `ng1Component`
const ng1ComponentA: angular.IComponent = {
template: 'ng1A(<ng2-b></ng2-b>)',
controller: class {
value = 'ng1A';
},
};
const ng1ComponentB: angular.IComponent = {
template:
'ng1B(^^ng1A: {{ $ctrl.ng1A.value }} | ?^^ng1B: {{ $ctrl.ng1B.value }} | ^ng1B: {{ $ctrl.ng1BSelf.value }})',
require: {ng1A: '^^', ng1B: '?^^', ng1BSelf: '^ng1B'},
controller: class {
value = 'ng1B';
},
};
// Define `Ng1ComponentFacade`
@Directive({
selector: 'ng1A',
standalone: false,
})
class Ng1ComponentAFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1A', elementRef, injector);
}
}
@Directive({
selector: 'ng1B',
standalone: false,
})
class Ng1ComponentBFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1B', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({
selector: 'ng2-a',
template: 'ng2A(<ng1A></ng1A>)',
standalone: false,
})
class Ng2ComponentA {}
@Component({
selector: 'ng2-b',
template: 'ng2B(<ng1B></ng1B>)',
standalone: false,
})
class Ng2ComponentB {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1', [])
.component('ng1A', ng1ComponentA)
.component('ng1B', ng1ComponentB)
.directive('ng2A', downgradeComponent({component: Ng2ComponentA}))
.directive('ng2B', downgradeComponent({component: Ng2ComponentB}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng1ComponentAFacade, Ng1ComponentBFacade, Ng2ComponentA, Ng2ComponentB],
imports: [BrowserModule, UpgradeModule],
schemas: [NO_ERRORS_SCHEMA],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2-a></ng2-a>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(document.body.textContent)).toBe(
'ng2A(ng1A(ng2B(ng1B(^^ng1A: ng1A | ?^^ng1B: | ^ng1B: ng1B))))',
);
});
}));
describe('standalone', () => {
it('should upgrade to a standalone component in NgModule-bootstrapped application', waitForAsync(() => {
const ng1Component: angular.IComponent = {template: `I'm from AngularJS!`};
// Define `Ng1ComponentFacade` (standalone)
@Directive({selector: 'ng1', standalone: true})
class Ng1ComponentStandaloneFacade extends UpgradeComponent {
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// Define `Ng2Component`
@Component({selector: 'ng2', template: '<ng1></ng1>', standalone: false})
class Ng2Component {}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', downgradeComponent({component: Ng2Component}));
// Define `Ng2Module`
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule, UpgradeModule, Ng1ComponentStandaloneFacade],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap
const element = html(`<ng2></ng2>`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => {
expect(multiTrim(element.textContent)).toBe(`I'm from AngularJS!`);
});
}));
});
});
}); | {
"end_byte": 156003,
"start_byte": 152106,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_component_spec.ts"
} |
angular/packages/upgrade/static/test/integration/injection_spec.ts_0_4476 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {destroyPlatform, InjectionToken, Injector, NgModule} from '@angular/core';
import {waitForAsync} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import * as angular from '../../../src/common/src/angular1';
import {$INJECTOR, INJECTOR_KEY} from '../../../src/common/src/constants';
import {html, withEachNg1Version} from '../../../src/common/test/helpers/common_test_helpers';
import {
downgradeInjectable,
getAngularJSGlobal,
setAngularJSGlobal,
UpgradeModule,
} from '../../index';
import {bootstrap} from './static_test_helpers';
withEachNg1Version(() => {
describe('injection', () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
it('should downgrade ng2 service to ng1', waitForAsync(() => {
// Tokens used in ng2 to identify services
const Ng2Service = new InjectionToken('ng2-service');
// Sample ng1 NgModule for tests
@NgModule({
imports: [BrowserModule, UpgradeModule],
providers: [{provide: Ng2Service, useValue: 'ng2 service value'}],
})
class Ng2Module {
ngDoBootstrap() {}
}
// create the ng1 module that will import an ng2 service
const ng1Module = angular
.module_('ng1Module', [])
.factory('ng2Service', downgradeInjectable(Ng2Service));
bootstrap(platformBrowserDynamic(), Ng2Module, html('<div>'), ng1Module).then((upgrade) => {
const ng1Injector = upgrade.$injector;
expect(ng1Injector.get('ng2Service')).toBe('ng2 service value');
});
}));
it('should upgrade ng1 service to ng2', waitForAsync(() => {
// Tokens used in ng2 to identify services
const Ng1Service = new InjectionToken('ng1-service');
// Sample ng1 NgModule for tests
@NgModule({
imports: [BrowserModule, UpgradeModule],
providers: [
// the following line is the "upgrade" of an AngularJS service
{
provide: Ng1Service,
useFactory: (i: angular.IInjectorService) => i.get('ng1Service'),
deps: ['$injector'],
},
],
})
class Ng2Module {
ngDoBootstrap() {}
}
// create the ng1 module that will import an ng2 service
const ng1Module = angular.module_('ng1Module', []).value('ng1Service', 'ng1 service value');
bootstrap(platformBrowserDynamic(), Ng2Module, html('<div>'), ng1Module).then((upgrade) => {
const ng2Injector = upgrade.injector;
expect(ng2Injector.get(Ng1Service)).toBe('ng1 service value');
});
}));
it('should initialize the upgraded injector before application run blocks are executed', waitForAsync(() => {
let runBlockTriggered = false;
const ng1Module = angular.module_('ng1Module', []).run([
INJECTOR_KEY,
function (injector: Injector) {
runBlockTriggered = true;
expect(injector.get($INJECTOR)).toBeDefined();
},
]);
@NgModule({imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
bootstrap(platformBrowserDynamic(), Ng2Module, html('<div>'), ng1Module).then(() => {
expect(runBlockTriggered).toBeTruthy();
});
}));
it('should allow resetting angular at runtime', waitForAsync(() => {
let wrappedBootstrapCalled = false;
const n: any = getAngularJSGlobal();
setAngularJSGlobal({
bootstrap: (...args: any[]) => {
wrappedBootstrapCalled = true;
n.bootstrap(...args);
},
module: n.module,
element: n.element,
version: n.version,
resumeBootstrap: n.resumeBootstrap,
getTestability: n.getTestability,
});
@NgModule({imports: [BrowserModule, UpgradeModule]})
class Ng2Module {
ngDoBootstrap() {}
}
const ng1Module = angular.module_('ng1Module', []);
bootstrap(platformBrowserDynamic(), Ng2Module, html('<div>'), ng1Module)
.then((upgrade) => expect(wrappedBootstrapCalled).toBe(true))
.then(() => setAngularJSGlobal(n)); // Reset the AngularJS global.
}));
});
});
| {
"end_byte": 4476,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/injection_spec.ts"
} |
angular/packages/upgrade/static/test/integration/upgrade_module_spec.ts_0_5025 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {destroyPlatform, NgModule, NgZone} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {
getAngularJSGlobal,
IAngularBootstrapConfig,
module_,
} from '../../../src/common/src/angular1';
import {html, withEachNg1Version} from '../../../src/common/test/helpers/common_test_helpers';
import {UpgradeModule} from '../../index';
withEachNg1Version(() => {
describe('UpgradeModule', () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
describe('$injector', () => {
it('should not be set initially', async () => {
// Define `Ng2Module`.
@NgModule({
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap the ng2 app.
const appRef = await platformBrowserDynamic().bootstrapModule(Ng2Module);
const upgrade = appRef.injector.get(UpgradeModule);
expect(upgrade.$injector).toBeUndefined();
});
it('should be set after calling `.bootstrap()`', async () => {
// Define `ng1Module`.
const ng1Module = module_('ng1Module', []).value('foo', 'ng1Foo');
// Define `Ng2Module`.
@NgModule({
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap the ng2 app.
const appRef = await platformBrowserDynamic().bootstrapModule(Ng2Module);
const upgrade = appRef.injector.get(UpgradeModule);
// Bootstrap the hybrid app.
const element = html(`<ng2></ng2>`);
upgrade.bootstrap(element, [ng1Module.name]);
expect(upgrade.$injector).toBeDefined();
expect(upgrade.$injector.get('foo')).toBe('ng1Foo');
});
});
describe('injector', () => {
it('should be set initially', async () => {
// Define `Ng2Module`.
@NgModule({
imports: [BrowserModule, UpgradeModule],
providers: [{provide: 'foo', useValue: 'ng2Foo'}],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap the ng2 app.
const appRef = await platformBrowserDynamic().bootstrapModule(Ng2Module);
const upgrade = appRef.injector.get(UpgradeModule);
expect(upgrade.injector).toBeDefined();
expect(upgrade.injector.get('foo')).toBe('ng2Foo');
});
});
describe('ngZone', () => {
it('should be set initially', async () => {
// Define `Ng2Module`.
@NgModule({
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap the ng2 app.
const appRef = await platformBrowserDynamic().bootstrapModule(Ng2Module);
const upgrade = appRef.injector.get(UpgradeModule);
expect(upgrade.ngZone).toBeDefined();
expect(upgrade.ngZone).toBe(appRef.injector.get(NgZone));
});
});
describe('bootstrap()', () => {
it('should call `angular.bootstrap()`', async () => {
// Set up spies.
const bootstrapSpy = spyOn(getAngularJSGlobal(), 'bootstrap').and.callThrough();
// Define `Ng2Module`.
@NgModule({
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap the ng2 app.
const appRef = await platformBrowserDynamic().bootstrapModule(Ng2Module);
const upgrade = appRef.injector.get(UpgradeModule);
// Bootstrap the hybrid app.
const element = html(`<ng2></ng2>`);
const config: IAngularBootstrapConfig = {strictDi: true};
upgrade.bootstrap(element, [], config);
expect(bootstrapSpy).toHaveBeenCalledOnceWith(element, jasmine.any(Array), config);
});
it('should forward the return value of `angular.bootstrap()`', async () => {
// Set up spies.
const bootstrapSpy = spyOn(getAngularJSGlobal(), 'bootstrap').and.callThrough();
// Define `Ng2Module`.
@NgModule({
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
// Bootstrap the ng2 app.
const appRef = await platformBrowserDynamic().bootstrapModule(Ng2Module);
const upgrade = appRef.injector.get(UpgradeModule);
// Bootstrap the hybrid app.
const retValue = upgrade.bootstrap(html(`<ng2></ng2>`), []);
expect(retValue).toBe(bootstrapSpy.calls.mostRecent().returnValue);
expect(retValue).toBe(upgrade.$injector); // In most cases, it will be the ng1 injector.
});
});
});
});
| {
"end_byte": 5025,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/upgrade_module_spec.ts"
} |
angular/packages/upgrade/static/test/integration/examples_spec.ts_0_3322 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
destroyPlatform,
Directive,
ElementRef,
Injector,
Input,
NgModule,
} from '@angular/core';
import {waitForAsync} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {downgradeComponent, UpgradeComponent, UpgradeModule} from '@angular/upgrade/static';
import * as angular from '../../../src/common/src/angular1';
import {
html,
multiTrim,
withEachNg1Version,
} from '../../../src/common/test/helpers/common_test_helpers';
import {bootstrap} from './static_test_helpers';
withEachNg1Version(() => {
describe('examples', () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
it('should have AngularJS loaded', () =>
expect(angular.getAngularJSGlobal().version.major).toBe(1));
it('should verify UpgradeAdapter example', waitForAsync(() => {
// This is wrapping (upgrading) an AngularJS component to be used in an Angular
// component
@Directive({
selector: 'ng1',
standalone: false,
})
class Ng1Component extends UpgradeComponent {
@Input() title: string = '';
constructor(elementRef: ElementRef, injector: Injector) {
super('ng1', elementRef, injector);
}
}
// This is an Angular component that will be downgraded
@Component({
selector: 'ng2',
template: 'ng2[<ng1 [title]="nameProp">transclude</ng1>](<ng-content></ng-content>)',
standalone: false,
})
class Ng2Component {
@Input('name') nameProp: string = '';
}
// This module represents the Angular pieces of the application
@NgModule({
declarations: [Ng1Component, Ng2Component],
imports: [BrowserModule, UpgradeModule],
})
class Ng2Module {
ngDoBootstrap() {
/* this is a placeholder to stop the bootstrapper from
complaining */
}
}
// This module represents the AngularJS pieces of the application
const ng1Module = angular
.module_('myExample', [])
// This is an AngularJS component that will be upgraded
.directive('ng1', () => {
return {
scope: {title: '='},
transclude: true,
template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)',
};
})
// This is wrapping (downgrading) an Angular component to be used in
// AngularJS
.directive('ng2', downgradeComponent({component: Ng2Component}));
// This is the (AngularJS) application bootstrap element
// Notice that it is actually a downgraded Angular component
const element = html('<ng2 name="World">project</ng2>');
// Let's use a helper function to make this simpler
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(multiTrim(element.textContent)).toBe('ng2[ng1[Hello World!](transclude)](project)');
});
}));
});
});
| {
"end_byte": 3322,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/test/integration/examples_spec.ts"
} |
angular/packages/upgrade/static/testing/PACKAGE.md_0_69 | Supplies testing functions for the AngularJS-to-Angular upgrade path. | {
"end_byte": 69,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/testing/PACKAGE.md"
} |
angular/packages/upgrade/static/testing/BUILD.bazel_0_745 | load("//tools:defaults.bzl", "generate_api_docs", "ng_module")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "testing",
srcs = glob(
[
"*.ts",
"src/*.ts",
],
),
deps = [
"//packages/core/testing",
"//packages/upgrade/static",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "upgrade_static_testing_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/upgrade/static/testing",
)
| {
"end_byte": 745,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/testing/BUILD.bazel"
} |
angular/packages/upgrade/static/testing/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public_api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/testing/index.ts"
} |
angular/packages/upgrade/static/testing/public_api.ts_0_368 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {createAngularTestingModule} from './src/create_angular_testing_module';
export {createAngularJSTestingModule} from './src/create_angularjs_testing_module';
| {
"end_byte": 368,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/testing/public_api.ts"
} |
angular/packages/upgrade/static/testing/test/mocks.ts_0_1979 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Inject, Injectable, NgModule} from '@angular/core';
import {downgradeInjectable} from '@angular/upgrade/static';
import * as ng from '../../../src/common/src/angular1';
/*
* This mock application code contains the following services and their dependencies:
*
* shoppingCart (AngularJS)
* -> Inventory (Angular - downgraded)
* -> serverRequest (AngularJS - upgraded)
* -> Logger (Angular - downgraded)
*
* This allows us to test two scenarios:
* * AngularJS -> Angular -> AngularJS
* * Angular -> AngularJS -> Angular
*/
/* START: Angular bits */
@Injectable()
export class Logger {
warn() {}
}
@Injectable()
export class Inventory {
constructor(@Inject('serverRequest') public serverRequest: any) {}
}
export function serverRequestFactory(i: ng.IInjectorService) {
return i.get('serverRequest');
}
@NgModule({
providers: [
Logger,
Inventory,
{provide: 'serverRequest', useFactory: serverRequestFactory, deps: ['$injector']},
],
})
export class AppModule {}
/* END: Angular bits */
/* START: AngularJS bits */
export const serverRequestInstance: {logger?: Logger} = {};
export const shoppingCartInstance: {inventory?: Inventory} = {};
export function defineAppModule() {
ng.module_('app', [])
.factory('logger', downgradeInjectable(Logger))
.factory('inventory', downgradeInjectable(Inventory))
.factory('serverRequest', [
'logger',
function (logger: Logger) {
serverRequestInstance.logger = logger;
return serverRequestInstance;
},
])
.factory('shoppingCart', [
'inventory',
function (inventory: Inventory) {
shoppingCartInstance.inventory = inventory;
return shoppingCartInstance;
},
]);
}
/* END: AngularJS bits */
| {
"end_byte": 1979,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/testing/test/mocks.ts"
} |
angular/packages/upgrade/static/testing/test/create_angularjs_testing_module_spec.ts_0_1419 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getAngularJSGlobal} from '../../../src/common/src/angular1';
import {withEachNg1Version} from '../../../src/common/test/helpers/common_test_helpers';
import {createAngularJSTestingModule} from '../src/create_angularjs_testing_module';
import {AppModule, defineAppModule, Inventory} from './mocks';
withEachNg1Version(() => {
describe('AngularJS entry point', () => {
it('should allow us to get a downgraded Angular service from an AngularJS service', () => {
defineAppModule();
// We have to get the `mock` object from the global `angular` variable, rather than trying to
// import it from `@angular/upgrade/src/common/angular1`, because that file doesn't export
// `ngMock` helpers.
const {inject, module} = getAngularJSGlobal().mock;
// Load the AngularJS bits of the application
module('app');
// Configure an AngularJS module that has the AngularJS and Angular injector wired up
module(createAngularJSTestingModule([AppModule]));
let inventory: any = undefined;
inject(function (shoppingCart: any) {
inventory = shoppingCart.inventory;
});
expect(inventory).toEqual(jasmine.any(Inventory));
});
});
});
| {
"end_byte": 1419,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/testing/test/create_angularjs_testing_module_spec.ts"
} |
angular/packages/upgrade/static/testing/test/create_angular_testing_module_spec.ts_0_2001 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injector} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {$INJECTOR} from '../../../src/common/src/constants';
import {withEachNg1Version} from '../../../src/common/test/helpers/common_test_helpers';
import {createAngularTestingModule} from '../src/create_angular_testing_module';
import {AppModule, defineAppModule, Inventory, serverRequestInstance} from './mocks';
withEachNg1Version(() => {
describe('Angular entry point', () => {
it('should allow us to get an upgraded AngularJS service from an Angular service', () => {
defineAppModule();
// Configure an NgModule that has the Angular and AngularJS injectors wired up
TestBed.configureTestingModule({imports: [createAngularTestingModule(['app']), AppModule]});
const inventory = TestBed.inject(Inventory);
expect(inventory.serverRequest).toBe(serverRequestInstance);
});
it('should create new injectors when we re-use the helper', () => {
defineAppModule();
TestBed.configureTestingModule({imports: [createAngularTestingModule(['app']), AppModule]});
// Check that the injectors are wired up correctly
TestBed.inject(Inventory);
// Grab references to the current injectors
const injector = TestBed.inject(Injector);
const $injector = TestBed.inject($INJECTOR as any);
TestBed.resetTestingModule();
TestBed.configureTestingModule({imports: [createAngularTestingModule(['app']), AppModule]});
// Check that the injectors are wired up correctly
TestBed.inject(Inventory);
// Check that the new injectors are different to the previous ones.
expect(TestBed.inject(Injector)).not.toBe(injector);
expect(TestBed.inject($INJECTOR as any)).not.toBe($injector);
});
});
});
| {
"end_byte": 2001,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/testing/test/create_angular_testing_module_spec.ts"
} |
angular/packages/upgrade/static/testing/test/BUILD.bazel_0_892 | load("//tools:defaults.bzl", "karma_web_test_suite", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
package(default_visibility = ["//visibility:public"])
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/upgrade/static/testing/index.mjs",
deps = ["//packages/upgrade/static/testing"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob([
"**/*.ts",
]),
deps = [
"//packages/core",
"//packages/core/testing",
"//packages/upgrade/src/common",
"//packages/upgrade/src/common/test/helpers",
"//packages/upgrade/static",
"//packages/upgrade/static/testing",
],
)
karma_web_test_suite(
name = "test",
static_files = [
"//:angularjs_scripts",
],
deps = [
":test_lib",
],
)
| {
"end_byte": 892,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/testing/test/BUILD.bazel"
} |
angular/packages/upgrade/static/testing/src/create_angularjs_testing_module.ts_0_3629 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injector} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {ɵangular1 as ng, ɵconstants} from '@angular/upgrade/static';
import {UpgradeAppType} from '../../../src/common/src/util';
/**
* A helper function to use when unit testing AngularJS services that depend upon downgraded Angular
* services.
*
* This function returns an AngularJS module that is configured to wire up the AngularJS and Angular
* injectors without the need to actually bootstrap a hybrid application.
* This makes it simpler and faster to unit test services.
*
* Use the returned AngularJS module in a call to
* [`angular.mocks.module`](https://docs.angularjs.org/api/ngMock/function/angular.mock.module) to
* include this module in the unit test injector.
*
* In the following code snippet, we are configuring the `$injector` with two modules:
* The AngularJS `ng1AppModule`, which is the AngularJS part of our hybrid application and the
* `Ng2AppModule`, which is the Angular part.
*
* <code-example path="upgrade/static/ts/full/module.spec.ts"
* region="angularjs-setup"></code-example>
*
* Once this is done we can get hold of services via the AngularJS `$injector` as normal.
* Services that are (or have dependencies on) a downgraded Angular service, will be instantiated as
* needed by the Angular root `Injector`.
*
* In the following code snippet, `heroesService` is a downgraded Angular service that we are
* accessing from AngularJS.
*
* <code-example path="upgrade/static/ts/full/module.spec.ts"
* region="angularjs-spec"></code-example>
*
* <div class="alert is-important">
*
* This helper is for testing services not components.
* For Component testing you must still bootstrap a hybrid app. See `UpgradeModule` or
* `downgradeModule` for more information.
*
* </div>
*
* <div class="alert is-important">
*
* The resulting configuration does not wire up AngularJS digests to Zone hooks. It is the
* responsibility of the test writer to call `$rootScope.$apply`, as necessary, to trigger
* AngularJS handlers of async events from Angular.
*
* </div>
*
* <div class="alert is-important">
*
* The helper sets up global variables to hold the shared Angular and AngularJS injectors.
*
* * Only call this helper once per spec.
* * Do not use `createAngularJSTestingModule` in the same spec as `createAngularTestingModule`.
*
* </div>
*
* Here is the example application and its unit tests that use `createAngularTestingModule`
* and `createAngularJSTestingModule`.
*
* <code-tabs>
* <code-pane header="module.spec.ts" path="upgrade/static/ts/full/module.spec.ts"></code-pane>
* <code-pane header="module.ts" path="upgrade/static/ts/full/module.ts"></code-pane>
* </code-tabs>
*
*
* @param angularModules a collection of Angular modules to include in the configuration.
*
* @publicApi
*/
export function createAngularJSTestingModule(angularModules: any[]): string {
return ng
.module_('$$angularJSTestingModule', [])
.constant(ɵconstants.UPGRADE_APP_TYPE_KEY, UpgradeAppType.Static)
.factory(ɵconstants.INJECTOR_KEY, [
ɵconstants.$INJECTOR,
($injector: ng.IInjectorService) => {
TestBed.configureTestingModule({
imports: angularModules,
providers: [{provide: ɵconstants.$INJECTOR, useValue: $injector}],
});
return TestBed.inject(Injector);
},
]).name;
}
| {
"end_byte": 3629,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/testing/src/create_angularjs_testing_module.ts"
} |
angular/packages/upgrade/static/testing/src/create_angular_testing_module.ts_0_3738 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injector, NgModule, Type} from '@angular/core';
import {ɵangular1 as angular, ɵconstants} from '@angular/upgrade/static';
import {UpgradeAppType} from '../../../src/common/src/util';
let $injector: angular.IInjectorService | null = null;
let injector: Injector;
export function $injectorFactory() {
return $injector;
}
@NgModule({providers: [{provide: ɵconstants.$INJECTOR, useFactory: $injectorFactory}]})
export class AngularTestingModule {
constructor(i: Injector) {
injector = i;
}
}
/**
* A helper function to use when unit testing Angular services that depend upon upgraded AngularJS
* services.
*
* This function returns an `NgModule` decorated class that is configured to wire up the Angular
* and AngularJS injectors without the need to actually bootstrap a hybrid application.
* This makes it simpler and faster to unit test services.
*
* Use the returned class as an "import" when configuring the `TestBed`.
*
* In the following code snippet, we are configuring the TestBed with two imports.
* The `Ng2AppModule` is the Angular part of our hybrid application and the `ng1AppModule` is the
* AngularJS part.
*
* <code-example path="upgrade/static/ts/full/module.spec.ts" region="angular-setup"></code-example>
*
* Once this is done we can get hold of services via the Angular `Injector` as normal.
* Services that are (or have dependencies on) an upgraded AngularJS service, will be instantiated
* as needed by the AngularJS `$injector`.
*
* In the following code snippet, `HeroesService` is an Angular service that depends upon an
* AngularJS service, `titleCase`.
*
* <code-example path="upgrade/static/ts/full/module.spec.ts" region="angular-spec"></code-example>
*
* <div class="alert is-important">
*
* This helper is for testing services not Components.
* For Component testing you must still bootstrap a hybrid app. See `UpgradeModule` or
* `downgradeModule` for more information.
*
* </div>
*
* <div class="alert is-important">
*
* The resulting configuration does not wire up AngularJS digests to Zone hooks. It is the
* responsibility of the test writer to call `$rootScope.$apply`, as necessary, to trigger
* AngularJS handlers of async events from Angular.
*
* </div>
*
* <div class="alert is-important">
*
* The helper sets up global variables to hold the shared Angular and AngularJS injectors.
*
* * Only call this helper once per spec.
* * Do not use `createAngularTestingModule` in the same spec as `createAngularJSTestingModule`.
*
* </div>
*
* Here is the example application and its unit tests that use `createAngularTestingModule`
* and `createAngularJSTestingModule`.
*
* <code-tabs>
* <code-pane header="module.spec.ts" path="upgrade/static/ts/full/module.spec.ts"></code-pane>
* <code-pane header="module.ts" path="upgrade/static/ts/full/module.ts"></code-pane>
* </code-tabs>
*
*
* @param angularJSModules a collection of the names of AngularJS modules to include in the
* configuration.
* @param [strictDi] whether the AngularJS injector should have `strictDI` enabled.
*
* @publicApi
*/
export function createAngularTestingModule(
angularJSModules: string[],
strictDi?: boolean,
): Type<any> {
angular
.module_('$$angularJSTestingModule', angularJSModules)
.constant(ɵconstants.UPGRADE_APP_TYPE_KEY, UpgradeAppType.Static)
.factory(ɵconstants.INJECTOR_KEY, () => injector);
$injector = angular.injector(['ng', '$$angularJSTestingModule'], strictDi);
return AngularTestingModule;
}
| {
"end_byte": 3738,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/testing/src/create_angular_testing_module.ts"
} |
angular/packages/upgrade/static/src/upgrade_module.ts_0_6580 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injector, NgModule, NgZone, PlatformRef, Testability} from '@angular/core';
import {ɵangular1, ɵconstants, ɵutil} from '../common';
import {angular1Providers, setTempInjectorRef} from './angular1_providers';
import {NgAdapterInjector} from './util';
/**
* @description
*
* An `NgModule`, which you import to provide AngularJS core services,
* and has an instance method used to bootstrap the hybrid upgrade application.
*
* *Part of the [upgrade/static](api?query=upgrade/static)
* library for hybrid upgrade apps that support AOT compilation*
*
* The `upgrade/static` package contains helpers that allow AngularJS and Angular components
* to be used together inside a hybrid upgrade application, which supports AOT compilation.
*
* Specifically, the classes and functions in the `upgrade/static` module allow the following:
*
* 1. Creation of an Angular directive that wraps and exposes an AngularJS component so
* that it can be used in an Angular template. See `UpgradeComponent`.
* 2. Creation of an AngularJS directive that wraps and exposes an Angular component so
* that it can be used in an AngularJS template. See `downgradeComponent`.
* 3. Creation of an Angular root injector provider that wraps and exposes an AngularJS
* service so that it can be injected into an Angular context. See
* {@link UpgradeModule#upgrading-an-angular-1-service Upgrading an AngularJS service} below.
* 4. Creation of an AngularJS service that wraps and exposes an Angular injectable
* so that it can be injected into an AngularJS context. See `downgradeInjectable`.
* 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks
* coexisting in a single application.
*
* @usageNotes
*
* ```ts
* import {UpgradeModule} from '@angular/upgrade/static';
* ```
*
* See also the {@link UpgradeModule#examples examples} below.
*
* ### Mental Model
*
* When reasoning about how a hybrid application works it is useful to have a mental model which
* describes what is happening and explains what is happening at the lowest level.
*
* 1. There are two independent frameworks running in a single application, each framework treats
* the other as a black box.
* 2. Each DOM element on the page is owned exactly by one framework. Whichever framework
* instantiated the element is the owner. Each framework only updates/interacts with its own
* DOM elements and ignores others.
* 3. AngularJS directives always execute inside the AngularJS framework codebase regardless of
* where they are instantiated.
* 4. Angular components always execute inside the Angular framework codebase regardless of
* where they are instantiated.
* 5. An AngularJS component can be "upgraded"" to an Angular component. This is achieved by
* defining an Angular directive, which bootstraps the AngularJS component at its location
* in the DOM. See `UpgradeComponent`.
* 6. An Angular component can be "downgraded" to an AngularJS component. This is achieved by
* defining an AngularJS directive, which bootstraps the Angular component at its location
* in the DOM. See `downgradeComponent`.
* 7. Whenever an "upgraded"/"downgraded" component is instantiated the host element is owned by
* the framework doing the instantiation. The other framework then instantiates and owns the
* view for that component.
* 1. This implies that the component bindings will always follow the semantics of the
* instantiation framework.
* 2. The DOM attributes are parsed by the framework that owns the current template. So
* attributes in AngularJS templates must use kebab-case, while AngularJS templates must use
* camelCase.
* 3. However the template binding syntax will always use the Angular style, e.g. square
* brackets (`[...]`) for property binding.
* 8. Angular is bootstrapped first; AngularJS is bootstrapped second. AngularJS always owns the
* root component of the application.
* 9. The new application is running in an Angular zone, and therefore it no longer needs calls to
* `$apply()`.
*
* ### The `UpgradeModule` class
*
* This class is an `NgModule`, which you import to provide AngularJS core services,
* and has an instance method used to bootstrap the hybrid upgrade application.
*
* * Core AngularJS services<br />
* Importing this `NgModule` will add providers for the core
* [AngularJS services](https://docs.angularjs.org/api/ng/service) to the root injector.
*
* * Bootstrap<br />
* The runtime instance of this class contains a {@link UpgradeModule#bootstrap `bootstrap()`}
* method, which you use to bootstrap the top level AngularJS module onto an element in the
* DOM for the hybrid upgrade app.
*
* It also contains properties to access the {@link UpgradeModule#injector root injector}, the
* bootstrap `NgZone` and the
* [AngularJS $injector](https://docs.angularjs.org/api/auto/service/$injector).
*
* ### Examples
*
* Import the `UpgradeModule` into your top level {@link NgModule Angular `NgModule`}.
*
* {@example upgrade/static/ts/full/module.ts region='ng2-module'}
*
* Then inject `UpgradeModule` into your Angular `NgModule` and use it to bootstrap the top level
* [AngularJS module](https://docs.angularjs.org/api/ng/type/angular.Module) in the
* `ngDoBootstrap()` method.
*
* {@example upgrade/static/ts/full/module.ts region='bootstrap-ng1'}
*
* Finally, kick off the whole process, by bootstrapping your top level Angular `NgModule`.
*
* {@example upgrade/static/ts/full/module.ts region='bootstrap-ng2'}
*
* {@a upgrading-an-angular-1-service}
* ### Upgrading an AngularJS service
*
* There is no specific API for upgrading an AngularJS service. Instead you should just follow the
* following recipe:
*
* Let's say you have an AngularJS service:
*
* {@example upgrade/static/ts/full/module.ts region="ng1-text-formatter-service"}
*
* Then you should define an Angular provider to be included in your `NgModule` `providers`
* property.
*
* {@example upgrade/static/ts/full/module.ts region="upgrade-ng1-service"}
*
* Then you can use the "upgraded" AngularJS service by injecting it into an Angular component
* or service.
*
* {@example upgrade/static/ts/full/module.ts region="use-ng1-upgraded-service"}
*
* @publicApi
*/
@N | {
"end_byte": 6580,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/src/upgrade_module.ts"
} |
angular/packages/upgrade/static/src/upgrade_module.ts_6581_14713 | Module({providers: [angular1Providers]})
export class UpgradeModule {
/**
* The AngularJS `$injector` for the upgrade application.
*/
public $injector: any /*angular.IInjectorService*/;
/** The Angular Injector **/
public injector: Injector;
constructor(
/** The root `Injector` for the upgrade application. */
injector: Injector,
/** The bootstrap zone for the upgrade application */
public ngZone: NgZone,
/**
* The owning `NgModuleRef`s `PlatformRef` instance.
* This is used to tie the lifecycle of the bootstrapped AngularJS apps to that of the Angular
* `PlatformRef`.
*/
private platformRef: PlatformRef,
) {
this.injector = new NgAdapterInjector(injector);
}
/**
* Bootstrap an AngularJS application from this NgModule
* @param element the element on which to bootstrap the AngularJS application
* @param [modules] the AngularJS modules to bootstrap for this application
* @param [config] optional extra AngularJS bootstrap configuration
* @return The value returned by
* [angular.bootstrap()](https://docs.angularjs.org/api/ng/function/angular.bootstrap).
*/
bootstrap(
element: Element,
modules: string[] = [],
config?: any /*angular.IAngularBootstrapConfig*/,
): any /*ReturnType<typeof angular.bootstrap>*/ {
const INIT_MODULE_NAME = ɵconstants.UPGRADE_MODULE_NAME + '.init';
// Create an ng1 module to bootstrap
ɵangular1
.module_(INIT_MODULE_NAME, [])
.constant(ɵconstants.UPGRADE_APP_TYPE_KEY, ɵutil.UpgradeAppType.Static)
.value(ɵconstants.INJECTOR_KEY, this.injector)
.factory(ɵconstants.LAZY_MODULE_REF, [
ɵconstants.INJECTOR_KEY,
(injector: Injector) => ({injector}) as ɵutil.LazyModuleRef,
])
.config([
ɵconstants.$PROVIDE,
ɵconstants.$INJECTOR,
($provide: ɵangular1.IProvideService, $injector: ɵangular1.IInjectorService) => {
if ($injector.has(ɵconstants.$$TESTABILITY)) {
$provide.decorator(ɵconstants.$$TESTABILITY, [
ɵconstants.$DELEGATE,
(testabilityDelegate: ɵangular1.ITestabilityService) => {
const originalWhenStable: Function = testabilityDelegate.whenStable;
const injector = this.injector;
// Cannot use arrow function below because we need the context
const newWhenStable = function (callback: Function) {
originalWhenStable.call(testabilityDelegate, function () {
const ng2Testability: Testability = injector.get(Testability);
if (ng2Testability.isStable()) {
callback();
} else {
ng2Testability.whenStable(newWhenStable.bind(testabilityDelegate, callback));
}
});
};
testabilityDelegate.whenStable = newWhenStable;
return testabilityDelegate;
},
]);
}
if ($injector.has(ɵconstants.$INTERVAL)) {
$provide.decorator(ɵconstants.$INTERVAL, [
ɵconstants.$DELEGATE,
(intervalDelegate: ɵangular1.IIntervalService) => {
// Wrap the $interval service so that setInterval is called outside NgZone,
// but the callback is still invoked within it. This is so that $interval
// won't block stability, which preserves the behavior from AngularJS.
let wrappedInterval = (
fn: Function,
delay: number,
count?: number,
invokeApply?: boolean,
...pass: any[]
) => {
return this.ngZone.runOutsideAngular(() => {
return intervalDelegate(
(...args: any[]) => {
// Run callback in the next VM turn - $interval calls
// $rootScope.$apply, and running the callback in NgZone will
// cause a '$digest already in progress' error if it's in the
// same vm turn.
setTimeout(() => {
this.ngZone.run(() => fn(...args));
});
},
delay,
count,
invokeApply,
...pass,
);
});
};
(Object.keys(intervalDelegate) as (keyof ɵangular1.IIntervalService)[]).forEach(
(prop) => ((wrappedInterval as any)[prop] = intervalDelegate[prop]),
);
// the `flush` method will be present when ngMocks is used
if (intervalDelegate.hasOwnProperty('flush')) {
(wrappedInterval as any)['flush'] = () => {
(intervalDelegate as any)['flush']();
return wrappedInterval;
};
}
return wrappedInterval;
},
]);
}
},
])
.run([
ɵconstants.$INJECTOR,
($injector: ɵangular1.IInjectorService) => {
this.$injector = $injector;
const $rootScope = $injector.get('$rootScope');
// Initialize the ng1 $injector provider
setTempInjectorRef($injector);
this.injector.get(ɵconstants.$INJECTOR);
// Put the injector on the DOM, so that it can be "required"
ɵangular1.element(element).data!(
ɵutil.controllerKey(ɵconstants.INJECTOR_KEY),
this.injector,
);
// Destroy the AngularJS app once the Angular `PlatformRef` is destroyed.
// This does not happen in a typical SPA scenario, but it might be useful for
// other use-cases where disposing of an Angular/AngularJS app is necessary
// (such as Hot Module Replacement (HMR)).
// See https://github.com/angular/angular/issues/39935.
this.platformRef.onDestroy(() => ɵutil.destroyApp($injector));
// Wire up the ng1 rootScope to run a digest cycle whenever the zone settles
// We need to do this in the next tick so that we don't prevent the bootup stabilizing
setTimeout(() => {
const subscription = this.ngZone.onMicrotaskEmpty.subscribe(() => {
if ($rootScope.$$phase) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
console.warn(
'A digest was triggered while one was already in progress. This may mean that something is triggering digests outside the Angular zone.',
);
}
return $rootScope.$evalAsync();
}
return $rootScope.$digest();
});
$rootScope.$on('$destroy', () => {
subscription.unsubscribe();
});
}, 0);
},
]);
const upgradeModule = ɵangular1.module_(
ɵconstants.UPGRADE_MODULE_NAME,
[INIT_MODULE_NAME].concat(modules),
);
// Make sure resumeBootstrap() only exists if the current bootstrap is deferred
const windowAngular = (window as any)['angular'];
windowAngular.resumeBootstrap = undefined;
// Bootstrap the AngularJS application inside our zone
const returnValue = this.ngZone.run(() =>
ɵangular1.bootstrap(element, [upgradeModule.name], config),
);
// Patch resumeBootstrap() to run inside the ngZone
if (windowAngular.resumeBootstrap) {
const originalResumeBootstrap: () => void = windowAngular.resumeBootstrap;
const ngZone = this.ngZone;
windowAngular.resumeBootstrap = function () {
let args = arguments;
windowAngular.resumeBootstrap = originalResumeBootstrap;
return ngZone.run(() => windowAngular.resumeBootstrap.apply(this, args));
};
}
return returnValue;
}
}
| {
"end_byte": 14713,
"start_byte": 6581,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/src/upgrade_module.ts"
} |
angular/packages/upgrade/static/src/downgrade_module.ts_0_6602 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Injector,
NgModuleFactory,
NgModuleRef,
PlatformRef,
StaticProvider,
Type,
} from '@angular/core';
import {platformBrowser} from '@angular/platform-browser';
import {ɵangular1, ɵconstants, ɵutil} from '../common';
import {angular1Providers, setTempInjectorRef} from './angular1_providers';
import {NgAdapterInjector} from './util';
let moduleUid = 0;
/**
* @description
*
* A helper function for creating an AngularJS module that can bootstrap an Angular module
* "on-demand" (possibly lazily) when a {@link downgradeComponent downgraded component} needs to be
* instantiated.
*
* *Part of the [upgrade/static](api?query=upgrade/static) library for hybrid upgrade apps that
* support AOT compilation.*
*
* It allows loading/bootstrapping the Angular part of a hybrid application lazily and not having to
* pay the cost up-front. For example, you can have an AngularJS application that uses Angular for
* specific routes and only instantiate the Angular modules if/when the user visits one of these
* routes.
*
* The Angular module will be bootstrapped once (when requested for the first time) and the same
* reference will be used from that point onwards.
*
* `downgradeModule()` requires either an `NgModuleFactory`, `NgModule` class or a function:
* - `NgModuleFactory`: If you pass an `NgModuleFactory`, it will be used to instantiate a module
* using `platformBrowser`'s {@link PlatformRef#bootstrapModuleFactory bootstrapModuleFactory()}.
* NOTE: this type of the argument is deprecated. Please either provide an `NgModule` class or a
* bootstrap function instead.
* - `NgModule` class: If you pass an NgModule class, it will be used to instantiate a module
* using `platformBrowser`'s {@link PlatformRef#bootstrapModule bootstrapModule()}.
* - `Function`: If you pass a function, it is expected to return a promise resolving to an
* `NgModuleRef`. The function is called with an array of extra {@link StaticProvider Providers}
* that are expected to be available from the returned `NgModuleRef`'s `Injector`.
*
* `downgradeModule()` returns the name of the created AngularJS wrapper module. You can use it to
* declare a dependency in your main AngularJS module.
*
* {@example upgrade/static/ts/lite/module.ts region="basic-how-to"}
*
* For more details on how to use `downgradeModule()` see
* [Upgrading for Performance](https://angular.io/guide/upgrade).
*
* @usageNotes
*
* Apart from `UpgradeModule`, you can use the rest of the `upgrade/static` helpers as usual to
* build a hybrid application. Note that the Angular pieces (e.g. downgraded services) will not be
* available until the downgraded module has been bootstrapped, i.e. by instantiating a downgraded
* component.
*
* <div class="alert is-important">
*
* You cannot use `downgradeModule()` and `UpgradeModule` in the same hybrid application.<br />
* Use one or the other.
*
* </div>
*
* ### Differences with `UpgradeModule`
*
* Besides their different API, there are two important internal differences between
* `downgradeModule()` and `UpgradeModule` that affect the behavior of hybrid applications:
*
* 1. Unlike `UpgradeModule`, `downgradeModule()` does not bootstrap the main AngularJS module
* inside the {@link NgZone Angular zone}.
* 2. Unlike `UpgradeModule`, `downgradeModule()` does not automatically run a
* [$digest()](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest) when changes are
* detected in the Angular part of the application.
*
* What this means is that applications using `UpgradeModule` will run change detection more
* frequently in order to ensure that both frameworks are properly notified about possible changes.
* This will inevitably result in more change detection runs than necessary.
*
* `downgradeModule()`, on the other side, does not try to tie the two change detection systems as
* tightly, restricting the explicit change detection runs only to cases where it knows it is
* necessary (e.g. when the inputs of a downgraded component change). This improves performance,
* especially in change-detection-heavy applications, but leaves it up to the developer to manually
* notify each framework as needed.
*
* For a more detailed discussion of the differences and their implications, see
* [Upgrading for Performance](https://angular.io/guide/upgrade).
*
* <div class="alert is-helpful">
*
* You can manually trigger a change detection run in AngularJS using
* [scope.$apply(...)](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply) or
* [$rootScope.$digest()](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest).
*
* You can manually trigger a change detection run in Angular using {@link NgZone#run
* ngZone.run(...)}.
*
* </div>
*
* ### Downgrading multiple modules
*
* It is possible to downgrade multiple modules and include them in an AngularJS application. In
* that case, each downgraded module will be bootstrapped when an associated downgraded component or
* injectable needs to be instantiated.
*
* Things to keep in mind, when downgrading multiple modules:
*
* - Each downgraded component/injectable needs to be explicitly associated with a downgraded
* module. See `downgradeComponent()` and `downgradeInjectable()` for more details.
*
* - If you want some injectables to be shared among all downgraded modules, you can provide them as
* `StaticProvider`s, when creating the `PlatformRef` (e.g. via `platformBrowser` or
* `platformBrowserDynamic`).
*
* - When using {@link PlatformRef#bootstrapmodule `bootstrapModule()`} or
* {@link PlatformRef#bootstrapmodulefactory `bootstrapModuleFactory()`} to bootstrap the
* downgraded modules, each one is considered a "root" module. As a consequence, a new instance
* will be created for every injectable provided in `"root"` (via
* {@link Injectable#providedIn `providedIn`}).
* If this is not your intention, you can have a shared module (that will act as act as the "root"
* module) and create all downgraded modules using that module's injector:
*
* {@example upgrade/static/ts/lite-multi-shared/module.ts region="shared-root-module"}
*
* @publicApi
*/
export function downgradeModule<T>(
moduleOrBootstrapFn: Type<T> | ((extraProviders: StaticProvider[]) => Promise<NgModuleRef<T>>),
): string;
/* | {
"end_byte": 6602,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/src/downgrade_module.ts"
} |
angular/packages/upgrade/static/src/downgrade_module.ts_6603_12720 |
* @description
*
* A helper function for creating an AngularJS module that can bootstrap an Angular module
* "on-demand" (possibly lazily) when a {@link downgradeComponent downgraded component} needs to be
* instantiated.
*
* *Part of the [upgrade/static](api?query=upgrade/static) library for hybrid upgrade apps that
* support AOT compilation.*
*
* It allows loading/bootstrapping the Angular part of a hybrid application lazily and not having to
* pay the cost up-front. For example, you can have an AngularJS application that uses Angular for
* specific routes and only instantiate the Angular modules if/when the user visits one of these
* routes.
*
* The Angular module will be bootstrapped once (when requested for the first time) and the same
* reference will be used from that point onwards.
*
* `downgradeModule()` requires either an `NgModuleFactory`, `NgModule` class or a function:
* - `NgModuleFactory`: If you pass an `NgModuleFactory`, it will be used to instantiate a module
* using `platformBrowser`'s {@link PlatformRef#bootstrapModuleFactory bootstrapModuleFactory()}.
* NOTE: this type of the argument is deprecated. Please either provide an `NgModule` class or a
* bootstrap function instead.
* - `NgModule` class: If you pass an NgModule class, it will be used to instantiate a module
* using `platformBrowser`'s {@link PlatformRef#bootstrapModule bootstrapModule()}.
* - `Function`: If you pass a function, it is expected to return a promise resolving to an
* `NgModuleRef`. The function is called with an array of extra {@link StaticProvider Providers}
* that are expected to be available from the returned `NgModuleRef`'s `Injector`.
*
* `downgradeModule()` returns the name of the created AngularJS wrapper module. You can use it to
* declare a dependency in your main AngularJS module.
*
* {@example upgrade/static/ts/lite/module.ts region="basic-how-to"}
*
* For more details on how to use `downgradeModule()` see
* [Upgrading for Performance](https://angular.io/guide/upgrade).
*
* @usageNotes
*
* Apart from `UpgradeModule`, you can use the rest of the `upgrade/static` helpers as usual to
* build a hybrid application. Note that the Angular pieces (e.g. downgraded services) will not be
* available until the downgraded module has been bootstrapped, i.e. by instantiating a downgraded
* component.
*
* <div class="alert is-important">
*
* You cannot use `downgradeModule()` and `UpgradeModule` in the same hybrid application.<br />
* Use one or the other.
*
* </div>
*
* ### Differences with `UpgradeModule`
*
* Besides their different API, there are two important internal differences between
* `downgradeModule()` and `UpgradeModule` that affect the behavior of hybrid applications:
*
* 1. Unlike `UpgradeModule`, `downgradeModule()` does not bootstrap the main AngularJS module
* inside the {@link NgZone Angular zone}.
* 2. Unlike `UpgradeModule`, `downgradeModule()` does not automatically run a
* [$digest()](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest) when changes are
* detected in the Angular part of the application.
*
* What this means is that applications using `UpgradeModule` will run change detection more
* frequently in order to ensure that both frameworks are properly notified about possible changes.
* This will inevitably result in more change detection runs than necessary.
*
* `downgradeModule()`, on the other side, does not try to tie the two change detection systems as
* tightly, restricting the explicit change detection runs only to cases where it knows it is
* necessary (e.g. when the inputs of a downgraded component change). This improves performance,
* especially in change-detection-heavy applications, but leaves it up to the developer to manually
* notify each framework as needed.
*
* For a more detailed discussion of the differences and their implications, see
* [Upgrading for Performance](https://angular.io/guide/upgrade).
*
* <div class="alert is-helpful">
*
* You can manually trigger a change detection run in AngularJS using
* [scope.$apply(...)](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply) or
* [$rootScope.$digest()](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest).
*
* You can manually trigger a change detection run in Angular using {@link NgZone#run
* ngZone.run(...)}.
*
* </div>
*
* ### Downgrading multiple modules
*
* It is possible to downgrade multiple modules and include them in an AngularJS application. In
* that case, each downgraded module will be bootstrapped when an associated downgraded component or
* injectable needs to be instantiated.
*
* Things to keep in mind, when downgrading multiple modules:
*
* - Each downgraded component/injectable needs to be explicitly associated with a downgraded
* module. See `downgradeComponent()` and `downgradeInjectable()` for more details.
*
* - If you want some injectables to be shared among all downgraded modules, you can provide them as
* `StaticProvider`s, when creating the `PlatformRef` (e.g. via `platformBrowser` or
* `platformBrowserDynamic`).
*
* - When using {@link PlatformRef#bootstrapmodule `bootstrapModule()`} or
* {@link PlatformRef#bootstrapmodulefactory `bootstrapModuleFactory()`} to bootstrap the
* downgraded modules, each one is considered a "root" module. As a consequence, a new instance
* will be created for every injectable provided in `"root"` (via
* {@link Injectable#providedIn `providedIn`}).
* If this is not your intention, you can have a shared module (that will act as act as the "root"
* module) and create all downgraded modules using that module's injector:
*
* {@example upgrade/static/ts/lite-multi-shared/module.ts region="shared-root-module"}
*
* @publicApi
*
* @deprecated Passing `NgModuleFactory` as the `downgradeModule` function argument is deprecated,
* please pass an NgModule class reference instead.
*/
export function downgradeModule<T>(moduleOrBootstrapFn: NgModuleFactory<T>): string;
/* | {
"end_byte": 12720,
"start_byte": 6603,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/src/downgrade_module.ts"
} |
angular/packages/upgrade/static/src/downgrade_module.ts_12721_18595 |
* @description
*
* A helper function for creating an AngularJS module that can bootstrap an Angular module
* "on-demand" (possibly lazily) when a {@link downgradeComponent downgraded component} needs to be
* instantiated.
*
* *Part of the [upgrade/static](api?query=upgrade/static) library for hybrid upgrade apps that
* support AOT compilation.*
*
* It allows loading/bootstrapping the Angular part of a hybrid application lazily and not having to
* pay the cost up-front. For example, you can have an AngularJS application that uses Angular for
* specific routes and only instantiate the Angular modules if/when the user visits one of these
* routes.
*
* The Angular module will be bootstrapped once (when requested for the first time) and the same
* reference will be used from that point onwards.
*
* `downgradeModule()` requires either an `NgModuleFactory`, `NgModule` class or a function:
* - `NgModuleFactory`: If you pass an `NgModuleFactory`, it will be used to instantiate a module
* using `platformBrowser`'s {@link PlatformRef#bootstrapModuleFactory bootstrapModuleFactory()}.
* NOTE: this type of the argument is deprecated. Please either provide an `NgModule` class or a
* bootstrap function instead.
* - `NgModule` class: If you pass an NgModule class, it will be used to instantiate a module
* using `platformBrowser`'s {@link PlatformRef#bootstrapModule bootstrapModule()}.
* - `Function`: If you pass a function, it is expected to return a promise resolving to an
* `NgModuleRef`. The function is called with an array of extra {@link StaticProvider Providers}
* that are expected to be available from the returned `NgModuleRef`'s `Injector`.
*
* `downgradeModule()` returns the name of the created AngularJS wrapper module. You can use it to
* declare a dependency in your main AngularJS module.
*
* {@example upgrade/static/ts/lite/module.ts region="basic-how-to"}
*
* For more details on how to use `downgradeModule()` see
* [Upgrading for Performance](https://angular.io/guide/upgrade).
*
* @usageNotes
*
* Apart from `UpgradeModule`, you can use the rest of the `upgrade/static` helpers as usual to
* build a hybrid application. Note that the Angular pieces (e.g. downgraded services) will not be
* available until the downgraded module has been bootstrapped, i.e. by instantiating a downgraded
* component.
*
* <div class="alert is-important">
*
* You cannot use `downgradeModule()` and `UpgradeModule` in the same hybrid application.<br />
* Use one or the other.
*
* </div>
*
* ### Differences with `UpgradeModule`
*
* Besides their different API, there are two important internal differences between
* `downgradeModule()` and `UpgradeModule` that affect the behavior of hybrid applications:
*
* 1. Unlike `UpgradeModule`, `downgradeModule()` does not bootstrap the main AngularJS module
* inside the {@link NgZone Angular zone}.
* 2. Unlike `UpgradeModule`, `downgradeModule()` does not automatically run a
* [$digest()](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest) when changes are
* detected in the Angular part of the application.
*
* What this means is that applications using `UpgradeModule` will run change detection more
* frequently in order to ensure that both frameworks are properly notified about possible changes.
* This will inevitably result in more change detection runs than necessary.
*
* `downgradeModule()`, on the other side, does not try to tie the two change detection systems as
* tightly, restricting the explicit change detection runs only to cases where it knows it is
* necessary (e.g. when the inputs of a downgraded component change). This improves performance,
* especially in change-detection-heavy applications, but leaves it up to the developer to manually
* notify each framework as needed.
*
* For a more detailed discussion of the differences and their implications, see
* [Upgrading for Performance](https://angular.io/guide/upgrade).
*
* <div class="alert is-helpful">
*
* You can manually trigger a change detection run in AngularJS using
* [scope.$apply(...)](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply) or
* [$rootScope.$digest()](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest).
*
* You can manually trigger a change detection run in Angular using {@link NgZone#run
* ngZone.run(...)}.
*
* </div>
*
* ### Downgrading multiple modules
*
* It is possible to downgrade multiple modules and include them in an AngularJS application. In
* that case, each downgraded module will be bootstrapped when an associated downgraded component or
* injectable needs to be instantiated.
*
* Things to keep in mind, when downgrading multiple modules:
*
* - Each downgraded component/injectable needs to be explicitly associated with a downgraded
* module. See `downgradeComponent()` and `downgradeInjectable()` for more details.
*
* - If you want some injectables to be shared among all downgraded modules, you can provide them as
* `StaticProvider`s, when creating the `PlatformRef` (e.g. via `platformBrowser` or
* `platformBrowserDynamic`).
*
* - When using {@link PlatformRef#bootstrapmodule `bootstrapModule()`} or
* {@link PlatformRef#bootstrapmodulefactory `bootstrapModuleFactory()`} to bootstrap the
* downgraded modules, each one is considered a "root" module. As a consequence, a new instance
* will be created for every injectable provided in `"root"` (via
* {@link Injectable#providedIn `providedIn`}).
* If this is not your intention, you can have a shared module (that will act as act as the "root"
* module) and create all downgraded modules using that module's injector:
*
* {@example upgrade/static/ts/lite-multi-shared/module.ts region="shared-root-module"}
*
* @publicApi
*/
ex | {
"end_byte": 18595,
"start_byte": 12721,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/src/downgrade_module.ts"
} |
angular/packages/upgrade/static/src/downgrade_module.ts_18596_21549 | ort function downgradeModule<T>(
moduleOrBootstrapFn:
| Type<T>
| NgModuleFactory<T>
| ((extraProviders: StaticProvider[]) => Promise<NgModuleRef<T>>),
): string {
const lazyModuleName = `${ɵconstants.UPGRADE_MODULE_NAME}.lazy${++moduleUid}`;
const lazyModuleRefKey = `${ɵconstants.LAZY_MODULE_REF}${lazyModuleName}`;
const lazyInjectorKey = `${ɵconstants.INJECTOR_KEY}${lazyModuleName}`;
let bootstrapFn: (extraProviders: StaticProvider[]) => Promise<NgModuleRef<T>>;
if (ɵutil.isNgModuleType(moduleOrBootstrapFn)) {
// NgModule class
bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowser(extraProviders).bootstrapModule(moduleOrBootstrapFn);
} else if (!ɵutil.isFunction(moduleOrBootstrapFn)) {
// NgModule factory
bootstrapFn = (extraProviders: StaticProvider[]) =>
platformBrowser(extraProviders).bootstrapModuleFactory(moduleOrBootstrapFn);
} else {
// bootstrap function
bootstrapFn = moduleOrBootstrapFn;
}
let injector: Injector;
// Create an ng1 module to bootstrap.
ɵangular1
.module_(lazyModuleName, [])
.constant(ɵconstants.UPGRADE_APP_TYPE_KEY, ɵutil.UpgradeAppType.Lite)
.factory(ɵconstants.INJECTOR_KEY, [lazyInjectorKey, identity])
.factory(lazyInjectorKey, () => {
if (!injector) {
throw new Error(
'Trying to get the Angular injector before bootstrapping the corresponding ' +
'Angular module.',
);
}
return injector;
})
.factory(ɵconstants.LAZY_MODULE_REF, [lazyModuleRefKey, identity])
.factory(lazyModuleRefKey, [
ɵconstants.$INJECTOR,
($injector: ɵangular1.IInjectorService) => {
setTempInjectorRef($injector);
const result: ɵutil.LazyModuleRef = {
promise: bootstrapFn(angular1Providers).then((ref) => {
injector = result.injector = new NgAdapterInjector(ref.injector);
injector.get(ɵconstants.$INJECTOR);
// Destroy the AngularJS app once the Angular `PlatformRef` is destroyed.
// This does not happen in a typical SPA scenario, but it might be useful for
// other use-cases where disposing of an Angular/AngularJS app is necessary
// (such as Hot Module Replacement (HMR)).
// See https://github.com/angular/angular/issues/39935.
injector.get(PlatformRef).onDestroy(() => ɵutil.destroyApp($injector));
return injector;
}),
};
return result;
},
])
.config([
ɵconstants.$INJECTOR,
ɵconstants.$PROVIDE,
($injector: ɵangular1.IInjectorService, $provide: ɵangular1.IProvideService) => {
$provide.constant(
ɵconstants.DOWNGRADED_MODULE_COUNT_KEY,
ɵutil.getDowngradedModuleCount($injector) + 1,
);
},
]);
return lazyModuleName;
}
function identity<T = any>(x: T): T {
return x;
}
| {
"end_byte": 21549,
"start_byte": 18596,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/src/downgrade_module.ts"
} |
angular/packages/upgrade/static/src/util.ts_0_942 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Injector,
ɵNOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR as NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR,
} from '@angular/core';
export class NgAdapterInjector implements Injector {
constructor(private modInjector: Injector) {}
// When Angular locate a service in the component injector tree, the not found value is set to
// `NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR`. In such a case we should not walk up to the module
// injector.
// AngularJS only supports a single tree and should always check the module injector.
get(token: any, notFoundValue?: any): any {
if (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {
return notFoundValue;
}
return this.modInjector.get(token, notFoundValue);
}
}
| {
"end_byte": 942,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/src/util.ts"
} |
angular/packages/upgrade/static/src/upgrade_component.ts_0_2217 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
DoCheck,
ElementRef,
EventEmitter,
Injector,
OnChanges,
OnDestroy,
OnInit,
SimpleChanges,
} from '@angular/core';
import {ɵangular1, ɵconstants, ɵupgradeHelper, ɵutil} from '../common';
const NOT_SUPPORTED: any = 'NOT_SUPPORTED';
const INITIAL_VALUE = {
__UNINITIALIZED__: true,
};
class Bindings {
twoWayBoundProperties: string[] = [];
twoWayBoundLastValues: any[] = [];
expressionBoundProperties: string[] = [];
propertyToOutputMap: {[propName: string]: string} = {};
}
/**
* @description
*
* A helper class that allows an AngularJS component to be used from Angular.
*
* *Part of the [upgrade/static](api?query=upgrade%2Fstatic)
* library for hybrid upgrade apps that support AOT compilation.*
*
* This helper class should be used as a base class for creating Angular directives
* that wrap AngularJS components that need to be "upgraded".
*
* @usageNotes
* ### Examples
*
* Let's assume that you have an AngularJS component called `ng1Hero` that needs
* to be made available in Angular templates.
*
* {@example upgrade/static/ts/full/module.ts region="ng1-hero"}
*
* We must create a `Directive` that will make this AngularJS component
* available inside Angular templates.
*
* {@example upgrade/static/ts/full/module.ts region="ng1-hero-wrapper"}
*
* In this example you can see that we must derive from the `UpgradeComponent`
* base class but also provide an {@link Directive `@Directive`} decorator. This is
* because the AOT compiler requires that this information is statically available at
* compile time.
*
* Note that we must do the following:
* * specify the directive's selector (`ng1-hero`)
* * specify all inputs and outputs that the AngularJS component expects
* * derive from `UpgradeComponent`
* * call the base class from the constructor, passing
* * the AngularJS name of the component (`ng1Hero`)
* * the `ElementRef` and `Injector` for the component wrapper
*
* @publicApi
* @extensible
*/
@Di | {
"end_byte": 2217,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/src/upgrade_component.ts"
} |
angular/packages/upgrade/static/src/upgrade_component.ts_2218_10917 | ective()
export class UpgradeComponent implements OnInit, OnChanges, DoCheck, OnDestroy {
private helper: ɵupgradeHelper.UpgradeHelper;
private $element: ɵangular1.IAugmentedJQuery;
private $componentScope: ɵangular1.IScope;
private directive: ɵangular1.IDirective;
private bindings: Bindings;
private controllerInstance?: ɵupgradeHelper.IControllerInstance;
private bindingDestination?: ɵupgradeHelper.IBindingDestination;
// We will be instantiating the controller in the `ngOnInit` hook, when the
// first `ngOnChanges` will have been already triggered. We store the
// `SimpleChanges` and "play them back" later.
private pendingChanges: SimpleChanges | null = null;
private unregisterDoCheckWatcher?: Function;
/**
* Create a new `UpgradeComponent` instance. You should not normally need to do this.
* Instead you should derive a new class from this one and call the super constructor
* from the base class.
*
* {@example upgrade/static/ts/full/module.ts region="ng1-hero-wrapper" }
*
* * The `name` parameter should be the name of the AngularJS directive.
* * The `elementRef` and `injector` parameters should be acquired from Angular by dependency
* injection into the base class constructor.
*/
constructor(name: string, elementRef: ElementRef, injector: Injector) {
this.helper = new ɵupgradeHelper.UpgradeHelper(injector, name, elementRef);
this.$element = this.helper.$element;
this.directive = this.helper.directive;
this.bindings = this.initializeBindings(this.directive, name);
// We ask for the AngularJS scope from the Angular injector, since
// we will put the new component scope onto the new injector for each component
const $parentScope = injector.get(ɵconstants.$SCOPE);
// QUESTION 1: Should we create an isolated scope if the scope is only true?
// QUESTION 2: Should we make the scope accessible through `$element.scope()/isolateScope()`?
this.$componentScope = $parentScope.$new(!!this.directive.scope);
this.initializeOutputs();
}
/** @nodoc */
ngOnInit() {
// Collect contents, insert and compile template
const attachChildNodes: ɵangular1.ILinkFn | undefined = this.helper.prepareTransclusion();
const linkFn = this.helper.compileTemplate();
// Instantiate controller
const controllerType = this.directive.controller;
const bindToController = this.directive.bindToController;
let controllerInstance = controllerType
? this.helper.buildController(controllerType, this.$componentScope)
: undefined;
let bindingDestination: ɵupgradeHelper.IBindingDestination;
if (!bindToController) {
bindingDestination = this.$componentScope;
} else if (controllerType && controllerInstance) {
bindingDestination = controllerInstance;
} else {
throw new Error(
`Upgraded directive '${this.directive.name}' specifies 'bindToController' but no controller.`,
);
}
this.controllerInstance = controllerInstance;
this.bindingDestination = bindingDestination;
// Set up outputs
this.bindOutputs(bindingDestination);
// Require other controllers
const requiredControllers = this.helper.resolveAndBindRequiredControllers(controllerInstance);
// Hook: $onChanges
if (this.pendingChanges) {
this.forwardChanges(this.pendingChanges, bindingDestination);
this.pendingChanges = null;
}
// Hook: $onInit
if (this.controllerInstance && ɵutil.isFunction(this.controllerInstance.$onInit)) {
this.controllerInstance.$onInit();
}
// Hook: $doCheck
if (controllerInstance && ɵutil.isFunction(controllerInstance.$doCheck)) {
const callDoCheck = () => controllerInstance?.$doCheck?.();
this.unregisterDoCheckWatcher = this.$componentScope.$parent.$watch(callDoCheck);
callDoCheck();
}
// Linking
const link = this.directive.link;
const preLink = typeof link == 'object' && link.pre;
const postLink = typeof link == 'object' ? link.post : link;
const attrs: ɵangular1.IAttributes = NOT_SUPPORTED;
const transcludeFn: ɵangular1.ITranscludeFunction = NOT_SUPPORTED;
if (preLink) {
preLink(this.$componentScope, this.$element, attrs, requiredControllers, transcludeFn);
}
linkFn(this.$componentScope, null!, {parentBoundTranscludeFn: attachChildNodes});
if (postLink) {
postLink(this.$componentScope, this.$element, attrs, requiredControllers, transcludeFn);
}
// Hook: $postLink
if (this.controllerInstance && ɵutil.isFunction(this.controllerInstance.$postLink)) {
this.controllerInstance.$postLink();
}
}
/** @nodoc */
ngOnChanges(changes: SimpleChanges) {
if (!this.bindingDestination) {
this.pendingChanges = changes;
} else {
this.forwardChanges(changes, this.bindingDestination);
}
}
/** @nodoc */
ngDoCheck() {
const twoWayBoundProperties = this.bindings.twoWayBoundProperties;
const twoWayBoundLastValues = this.bindings.twoWayBoundLastValues;
const propertyToOutputMap = this.bindings.propertyToOutputMap;
twoWayBoundProperties.forEach((propName, idx) => {
const newValue = this.bindingDestination?.[propName];
const oldValue = twoWayBoundLastValues[idx];
if (!Object.is(newValue, oldValue)) {
const outputName = propertyToOutputMap[propName];
const eventEmitter: EventEmitter<any> = (this as any)[outputName];
eventEmitter.emit(newValue);
twoWayBoundLastValues[idx] = newValue;
}
});
}
/** @nodoc */
ngOnDestroy() {
if (ɵutil.isFunction(this.unregisterDoCheckWatcher)) {
this.unregisterDoCheckWatcher();
}
this.helper.onDestroy(this.$componentScope, this.controllerInstance);
}
private initializeBindings(directive: ɵangular1.IDirective, name: string) {
const btcIsObject = typeof directive.bindToController === 'object';
if (btcIsObject && Object.keys(directive.scope!).length) {
throw new Error(
`Binding definitions on scope and controller at the same time is not supported.`,
);
}
const context = btcIsObject ? directive.bindToController : directive.scope;
const bindings = new Bindings();
if (typeof context == 'object') {
Object.keys(context).forEach((propName) => {
const definition = context[propName];
const bindingType = definition.charAt(0);
// QUESTION: What about `=*`? Ignore? Throw? Support?
switch (bindingType) {
case '@':
case '<':
// We don't need to do anything special. They will be defined as inputs on the
// upgraded component facade and the change propagation will be handled by
// `ngOnChanges()`.
break;
case '=':
bindings.twoWayBoundProperties.push(propName);
bindings.twoWayBoundLastValues.push(INITIAL_VALUE);
bindings.propertyToOutputMap[propName] = propName + 'Change';
break;
case '&':
bindings.expressionBoundProperties.push(propName);
bindings.propertyToOutputMap[propName] = propName;
break;
default:
let json = JSON.stringify(context);
throw new Error(
`Unexpected mapping '${bindingType}' in '${json}' in '${name}' directive.`,
);
}
});
}
return bindings;
}
private initializeOutputs() {
// Initialize the outputs for `=` and `&` bindings
this.bindings.twoWayBoundProperties
.concat(this.bindings.expressionBoundProperties)
.forEach((propName) => {
const outputName = this.bindings.propertyToOutputMap[propName];
(this as any)[outputName] = new EventEmitter();
});
}
private bindOutputs(bindingDestination: ɵupgradeHelper.IBindingDestination) {
// Bind `&` bindings to the corresponding outputs
this.bindings.expressionBoundProperties.forEach((propName) => {
const outputName = this.bindings.propertyToOutputMap[propName];
const emitter: EventEmitter<any> = (this as any)[outputName];
bindingDestination[propName] = (value: any) => emitter.emit(value);
});
}
private forwardChanges(
changes: SimpleChanges,
bindingDestination: ɵupgradeHelper.IBindingDestination,
) {
// Forward input changes to `bindingDestination`
Object.keys(changes).forEach(
(propName) => (bindingDestination[propName] = changes[propName].currentValue),
);
if (ɵutil.isFunction(bindingDestination.$onChanges)) {
bindingDestination.$onChanges(changes);
}
}
}
| {
"end_byte": 10917,
"start_byte": 2218,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/src/upgrade_component.ts"
} |
angular/packages/upgrade/static/src/angular1_providers.ts_0_1919 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {IInjectorService} from '../../src/common/src/angular1';
// We have to do a little dance to get the ng1 injector into the module injector.
// We store the ng1 injector so that the provider in the module injector can access it
// Then we "get" the ng1 injector from the module injector, which triggers the provider to read
// the stored injector and release the reference to it.
let tempInjectorRef: IInjectorService | null = null;
export function setTempInjectorRef(injector: IInjectorService) {
tempInjectorRef = injector;
}
export function injectorFactory() {
if (!tempInjectorRef) {
throw new Error('Trying to get the AngularJS injector before it being set.');
}
const injector: IInjectorService = tempInjectorRef;
tempInjectorRef = null; // clear the value to prevent memory leaks
return injector;
}
export function rootScopeFactory(i: IInjectorService) {
return i.get('$rootScope');
}
export function compileFactory(i: IInjectorService) {
return i.get('$compile');
}
export function parseFactory(i: IInjectorService) {
return i.get('$parse');
}
export const angular1Providers = [
// We must use exported named functions for the ng2 factories to keep the compiler happy:
// > Metadata collected contains an error that will be reported at runtime:
// > Function calls are not supported.
// > Consider replacing the function or lambda with a reference to an exported function
{provide: '$injector', useFactory: injectorFactory, deps: []},
{provide: '$rootScope', useFactory: rootScopeFactory, deps: ['$injector']},
{provide: '$compile', useFactory: compileFactory, deps: ['$injector']},
{provide: '$parse', useFactory: parseFactory, deps: ['$injector']},
];
| {
"end_byte": 1919,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/static/src/angular1_providers.ts"
} |
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_0_1034 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ChangeDetectorRef,
Component,
destroyPlatform,
EventEmitter,
forwardRef,
Input,
NgModule,
NgModuleFactory,
NgZone,
NO_ERRORS_SCHEMA,
OnChanges,
OnDestroy,
Output,
SimpleChange,
SimpleChanges,
Testability,
} from '@angular/core';
import {fakeAsync, flushMicrotasks, TestBed, tick, waitForAsync} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import * as angular from '../../common/src/angular1';
import {$EXCEPTION_HANDLER, $ROOT_SCOPE} from '../../common/src/constants';
import {html, multiTrim, withEachNg1Version} from '../../common/test/helpers/common_test_helpers';
import {UpgradeAdapter, UpgradeAdapterRef} from '../src/upgrade_adapter';
declare var inject: Function; | {
"end_byte": 1034,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts"
} |
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_1036_8864 | withEachNg1Version(() => {
describe('adapter: ng1 to ng2', () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
describe('(basic use)', () => {
it('should have AngularJS loaded', () =>
expect(angular.getAngularJSGlobal().version.major).toBe(1));
it('should instantiate ng2 in ng1 template and project content', waitForAsync(() => {
const ng1Module = angular.module_('ng1', []);
@Component({
selector: 'ng2',
template: `{{ 'NG2' }}(<ng-content></ng-content>)`,
standalone: false,
})
class Ng2 {}
@NgModule({declarations: [Ng2], imports: [BrowserModule]})
class Ng2Module {}
const element = html("<div>{{ 'ng1[' }}<ng2>~{{ 'ng-content' }}~</ng2>{{ ']' }}</div>");
const adapter: UpgradeAdapter = new UpgradeAdapter(Ng2Module);
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(document.body.textContent).toEqual('ng1[NG2(~ng-content~)]');
ref.dispose();
});
}));
it('should instantiate ng1 in ng2 template and project content', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
@Component({
selector: 'ng2',
template: `{{ 'ng2(' }}<ng1>{{ 'transclude' }}</ng1
>{{ ')' }}`,
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng1', () => {
return {transclude: true, template: '{{ "ng1" }}(<ng-transclude></ng-transclude>)'};
});
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html("<div>{{'ng1('}}<ng2></ng2>{{')'}}</div>");
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(document.body.textContent).toEqual('ng1(ng2(ng1(transclude)))');
ref.dispose();
});
}));
it('should support the compilerOptions argument', waitForAsync(() => {
const platformRef = platformBrowserDynamic();
spyOn(platformRef, 'bootstrapModule').and.callThrough();
spyOn(platformRef, 'bootstrapModuleFactory').and.callThrough();
const ng1Module = angular.module_('ng1', []);
@Component({
selector: 'ng2',
template: `{{ 'NG2' }}(<ng-content></ng-content>)`,
standalone: false,
})
class Ng2 {}
const element = html("<div>{{ 'ng1[' }}<ng2>~{{ 'ng-content' }}~</ng2>{{ ']' }}</div>");
@NgModule({
declarations: [Ng2],
imports: [BrowserModule],
})
class Ng2AppModule {
ngDoBootstrap() {}
}
const adapter: UpgradeAdapter = new UpgradeAdapter(Ng2AppModule, {providers: []});
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(platformRef.bootstrapModule).toHaveBeenCalledWith(jasmine.any(Function), [
{providers: []},
jasmine.any(Object) as any,
]);
expect(platformRef.bootstrapModuleFactory).toHaveBeenCalledWith(
jasmine.any(NgModuleFactory),
jasmine.objectContaining({ngZone: jasmine.any(NgZone), providers: []}),
);
ref.dispose();
});
}));
it('should destroy the AngularJS app when `PlatformRef` is destroyed', waitForAsync(() => {
const platformRef = platformBrowserDynamic();
const adapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
@Component({
selector: 'ng2',
template: '<span>NG2</span>',
standalone: false,
})
class Ng2Component {}
@NgModule({
declarations: [Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {
ngDoBootstrap() {}
}
ng1Module.component('ng1', {template: '<ng2></ng2>'});
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
const element = html('<div><ng1></ng1></div>');
adapter.bootstrap(element, [ng1Module.name]).ready((ref) => {
const $rootScope: angular.IRootScopeService = ref.ng1Injector.get($ROOT_SCOPE);
const rootScopeDestroySpy = spyOn($rootScope, '$destroy');
const appElem = angular.element(element);
const ng1Elem = angular.element(element.querySelector('ng1') as Element);
const ng2Elem = angular.element(element.querySelector('ng2') as Element);
const ng2ChildElem = angular.element(element.querySelector('ng2 span') as Element);
// Attach data to all elements.
appElem.data!('testData', 1);
ng1Elem.data!('testData', 2);
ng2Elem.data!('testData', 3);
ng2ChildElem.data!('testData', 4);
// Verify data can be retrieved.
expect(appElem.data!('testData')).toBe(1);
expect(ng1Elem.data!('testData')).toBe(2);
expect(ng2Elem.data!('testData')).toBe(3);
expect(ng2ChildElem.data!('testData')).toBe(4);
expect(rootScopeDestroySpy).not.toHaveBeenCalled();
// Destroy `PlatformRef`.
platformRef.destroy();
// Verify `$rootScope` has been destroyed and data has been cleaned up.
expect(rootScopeDestroySpy).toHaveBeenCalled();
expect(appElem.data!('testData')).toBeUndefined();
expect(ng1Elem.data!('testData')).toBeUndefined();
expect(ng2Elem.data!('testData')).toBeUndefined();
expect(ng2ChildElem.data!('testData')).toBeUndefined();
});
}));
});
describe('bootstrap errors', () => {
let adapter: UpgradeAdapter;
let zone: NgZone;
beforeEach(() => {
angular.module_('ng1', []);
@Component({
selector: 'ng2',
template: `<BAD TEMPLATE div></div>`,
standalone: false,
})
class ng2Component {}
@NgModule({
declarations: [ng2Component],
imports: [BrowserModule],
})
class Ng2Module {}
zone = TestBed.inject(NgZone);
adapter = new UpgradeAdapter(Ng2Module);
});
it('should throw an uncaught error', fakeAsync(() => {
const resolveSpy = jasmine.createSpy('resolveSpy');
spyOn(console, 'error');
expect(() => {
// Needs to be run inside the `NgZone` in order
// for the promises to be flushed correctly.
zone.run(() => {
adapter.bootstrap(html('<ng2></ng2>'), ['ng1']).ready(resolveSpy);
flushMicrotasks();
});
}).toThrowError();
expect(resolveSpy).not.toHaveBeenCalled();
}));
it('should output an error message to the console and re-throw', fakeAsync(() => {
const consoleErrorSpy: jasmine.Spy = spyOn(console, 'error');
expect(() => {
// Needs to be run inside the `NgZone` in order
// for the promises to be flushed correctly.
zone.run(() => {
adapter.bootstrap(html('<ng2></ng2>'), ['ng1']);
flushMicrotasks();
});
}).toThrowError();
const args: any[] = consoleErrorSpy.calls.mostRecent().args;
expect(consoleErrorSpy).toHaveBeenCalled();
expect(args.length).toBeGreaterThan(0);
expect(args[0]).toEqual(jasmine.any(Error));
}));
}); | {
"end_byte": 8864,
"start_byte": 1036,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts"
} |
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_8870_15287 | describe('change-detection', () => {
it('should not break if a $digest is already in progress', waitForAsync(() => {
@Component({
selector: 'my-app',
template: '',
standalone: false,
})
class AppComponent {}
@NgModule({declarations: [AppComponent], imports: [BrowserModule]})
class Ng2Module {}
const ng1Module = angular.module_('ng1', []);
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const element = html('<my-app></my-app>');
adapter.bootstrap(element, [ng1Module.name]).ready((ref) => {
const $rootScope: any = ref.ng1RootScope;
const ngZone: NgZone = ref.ng2ModuleRef.injector.get<NgZone>(NgZone);
const digestSpy = spyOn($rootScope, '$digest').and.callThrough();
// Step 1: Ensure `$digest` is run on `onMicrotaskEmpty`.
ngZone.onMicrotaskEmpty.emit(null);
expect(digestSpy).toHaveBeenCalledTimes(1);
digestSpy.calls.reset();
// Step 2: Cause the issue.
$rootScope.$apply(() => ngZone.onMicrotaskEmpty.emit(null));
// With the fix, `$digest` will only be run once (for `$apply()`).
// Without the fix, `$digest()` would have been run an extra time (`onMicrotaskEmpty`).
expect(digestSpy).toHaveBeenCalledTimes(1);
digestSpy.calls.reset();
// Step 3: Ensure that `$digest()` is still executed on `onMicrotaskEmpty`.
ngZone.onMicrotaskEmpty.emit(null);
expect(digestSpy).toHaveBeenCalledTimes(1);
});
}));
it('should interleave scope and component expressions', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const log: string[] = [];
const l = (value: string) => {
log.push(value);
return value + ';';
};
ng1Module.directive('ng1a', () => ({template: "{{ l('ng1a') }}"}));
ng1Module.directive('ng1b', () => ({template: "{{ l('ng1b') }}"}));
ng1Module.run(($rootScope: any) => {
$rootScope.l = l;
$rootScope.reset = () => (log.length = 0);
});
@Component({
selector: 'ng2',
template: `{{ l('2A') }}<ng1a></ng1a>{{ l('2B') }}<ng1b></ng1b>{{ l('2C') }}`,
standalone: false,
})
class Ng2 {
l: any;
constructor() {
this.l = l;
}
}
@NgModule({
declarations: [
adapter.upgradeNg1Component('ng1a'),
adapter.upgradeNg1Component('ng1b'),
Ng2,
],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html("<div>{{reset(); l('1A');}}<ng2>{{l('1B')}}</ng2>{{l('1C')}}</div>");
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(document.body.textContent).toEqual('1A;2A;ng1a;2B;ng1b;2C;1C;');
// https://github.com/angular/angular.js/issues/12983
expect(log).toEqual(['1A', '1C', '2A', '2B', '2C', 'ng1a', 'ng1b']);
ref.dispose();
});
}));
it('should propagate changes to a downgraded component inside the ngZone', waitForAsync(() => {
let appComponent: AppComponent;
let upgradeRef: UpgradeAdapterRef;
@Component({
selector: 'my-app',
template: '<my-child [value]="value"></my-child>',
standalone: false,
})
class AppComponent {
value?: number;
constructor() {
appComponent = this;
}
}
@Component({
selector: 'my-child',
template: '<div>{{valueFromPromise}}',
standalone: false,
})
class ChildComponent {
valueFromPromise?: number;
@Input()
set value(v: number) {
expect(NgZone.isInAngularZone()).toBe(true);
}
constructor(private zone: NgZone) {}
ngOnChanges(changes: SimpleChanges) {
if (changes['value'].isFirstChange()) return;
this.zone.onMicrotaskEmpty.subscribe(() => {
expect(element.textContent).toEqual('5');
upgradeRef.dispose();
});
queueMicrotask(() => (this.valueFromPromise = changes['value'].currentValue));
}
}
@NgModule({declarations: [AppComponent, ChildComponent], imports: [BrowserModule]})
class Ng2Module {}
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular
.module_('ng1', [])
.directive('myApp', adapter.downgradeNg2Component(AppComponent));
const element = html('<my-app></my-app>');
adapter.bootstrap(element, ['ng1']).ready((ref) => {
upgradeRef = ref;
appComponent.value = 5;
});
}));
// This test demonstrates https://github.com/angular/angular/issues/6385
// which was invalidly fixed by https://github.com/angular/angular/pull/6386
// it('should not trigger $digest from an async operation in a watcher', async(() => {
// @Component({selector: 'my-app', template: ''})
// class AppComponent {
// }
// @NgModule({declarations: [AppComponent], imports: [BrowserModule]})
// class Ng2Module {
// }
// const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
// const ng1Module = angular.module_('ng1', []).directive(
// 'myApp', adapter.downgradeNg2Component(AppComponent));
// const element = html('<my-app></my-app>');
// adapter.bootstrap(element, ['ng1']).ready((ref) => {
// let doTimeout = false;
// let timeoutId: number;
// ref.ng1RootScope.$watch(() => {
// if (doTimeout && !timeoutId) {
// timeoutId = window.setTimeout(function() {
// timeoutId = null;
// }, 10);
// }
// });
// doTimeout = true;
// });
// }));
}); | {
"end_byte": 15287,
"start_byte": 8870,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts"
} |
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_15293_22972 | describe('downgrade ng2 component', () => {
it('should allow non-element selectors for downgraded components', waitForAsync(() => {
@Component({
selector: '[itWorks]',
template: 'It works',
standalone: false,
})
class WorksComponent {}
@NgModule({declarations: [WorksComponent], imports: [BrowserModule]})
class Ng2Module {}
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
ng1Module.directive('ng2', adapter.downgradeNg2Component(WorksComponent));
const element = html('<ng2></ng2>');
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent!)).toBe('It works');
});
}));
it('should bind properties, events', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []).value($EXCEPTION_HANDLER, (err: any) => {
throw err;
});
ng1Module.run(($rootScope: any) => {
$rootScope.name = 'world';
$rootScope.dataA = 'A';
$rootScope.dataB = 'B';
$rootScope.modelA = 'initModelA';
$rootScope.modelB = 'initModelB';
$rootScope.eventA = '?';
$rootScope.eventB = '?';
});
@Component({
selector: 'ng2',
inputs: ['literal', 'interpolate', 'oneWayA', 'oneWayB', 'twoWayA', 'twoWayB'],
outputs: [
'eventA',
'eventB',
'twoWayAEmitter: twoWayAChange',
'twoWayBEmitter: twoWayBChange',
],
template:
'ignore: {{ignore}}; ' +
'literal: {{literal}}; interpolate: {{interpolate}}; ' +
'oneWayA: {{oneWayA}}; oneWayB: {{oneWayB}}; ' +
'twoWayA: {{twoWayA}}; twoWayB: {{twoWayB}}; ({{ngOnChangesCount}})',
standalone: false,
})
class Ng2 {
ngOnChangesCount = 0;
ignore = '-';
literal = '?';
interpolate = '?';
oneWayA = '?';
oneWayB = '?';
twoWayA = '?';
twoWayB = '?';
eventA = new EventEmitter();
eventB = new EventEmitter();
twoWayAEmitter = new EventEmitter();
twoWayBEmitter = new EventEmitter();
ngOnChanges(changes: SimpleChanges) {
const assert = (prop: string, value: any) => {
if ((this as any)[prop] != value) {
throw new Error(
`Expected: '${prop}' to be '${value}' but was '${(this as any)[prop]}'`,
);
}
};
const assertChange = (prop: string, value: any) => {
assert(prop, value);
if (!changes[prop]) {
throw new Error(`Changes record for '${prop}' not found.`);
}
const actValue = changes[prop].currentValue;
if (actValue != value) {
throw new Error(
`Expected changes record for'${prop}' to be '${value}' but was '${actValue}'`,
);
}
};
switch (this.ngOnChangesCount++) {
case 0:
assert('ignore', '-');
assertChange('literal', 'Text');
assertChange('interpolate', 'Hello world');
assertChange('oneWayA', 'A');
assertChange('oneWayB', 'B');
assertChange('twoWayA', 'initModelA');
assertChange('twoWayB', 'initModelB');
this.twoWayAEmitter.emit('newA');
this.twoWayBEmitter.emit('newB');
this.eventA.emit('aFired');
this.eventB.emit('bFired');
break;
case 1:
assertChange('twoWayA', 'newA');
assertChange('twoWayB', 'newB');
break;
case 2:
assertChange('interpolate', 'Hello everyone');
break;
default:
throw new Error('Called too many times! ' + JSON.stringify(changes));
}
}
}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
@NgModule({
declarations: [Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
const element = html(`<div>
<ng2 literal="Text" interpolate="Hello {{name}}"
bind-one-way-a="dataA" [one-way-b]="dataB"
bindon-two-way-a="modelA" [(two-way-b)]="modelB"
on-event-a='eventA=$event' (event-b)="eventB=$event"></ng2>
| modelA: {{modelA}}; modelB: {{modelB}}; eventA: {{eventA}}; eventB: {{eventB}};
</div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent!)).toEqual(
'ignore: -; ' +
'literal: Text; interpolate: Hello world; ' +
'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (2) | ' +
'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;',
);
ref.ng1RootScope.$apply('name = "everyone"');
expect(multiTrim(document.body.textContent!)).toEqual(
'ignore: -; ' +
'literal: Text; interpolate: Hello everyone; ' +
'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (3) | ' +
'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;',
);
ref.dispose();
});
}));
it('should support two-way binding and event listener', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const listenerSpy = jasmine.createSpy('$rootScope.listener');
const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => {
$rootScope['value'] = 'world';
$rootScope['listener'] = listenerSpy;
});
@Component({
selector: 'ng2',
template: `model: {{ model }};`,
standalone: false,
})
class Ng2Component implements OnChanges {
ngOnChangesCount = 0;
@Input() model = '?';
@Output() modelChange = new EventEmitter();
ngOnChanges(changes: SimpleChanges) {
switch (this.ngOnChangesCount++) {
case 0:
expect(changes['model'].currentValue).toBe('world');
this.modelChange.emit('newC');
break;
case 1:
expect(changes['model'].currentValue).toBe('newC');
break;
default:
throw new Error('Called too many times! ' + JSON.stringify(changes));
}
}
}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
@NgModule({declarations: [Ng2Component], imports: [BrowserModule]})
class Ng2Module {
ngDoBootstrap() {}
}
const element = html(`
<div>
<ng2 [(model)]="value" (model-change)="listener($event)"></ng2>
| value: {{value}}
</div>
`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(element.textContent)).toEqual('model: newC; | value: newC');
expect(listenerSpy).toHaveBeenCalledWith('newC');
ref.dispose();
});
})); | {
"end_byte": 22972,
"start_byte": 15293,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts"
} |
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_22980_31476 | it('should initialize inputs in time for `ngOnChanges`', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
@Component({
selector: 'ng2',
template: ` ngOnChangesCount: {{ ngOnChangesCount }} | firstChangesCount:
{{ firstChangesCount }} | initialValue: {{ initialValue }}`,
standalone: false,
})
class Ng2Component implements OnChanges {
ngOnChangesCount = 0;
firstChangesCount = 0;
@Input() foo: string = '';
initialValue: string = this.foo;
ngOnChanges(changes: SimpleChanges) {
this.ngOnChangesCount++;
if (this.ngOnChangesCount === 1) {
this.initialValue = this.foo;
}
if (changes['foo'] && changes['foo'].isFirstChange()) {
this.firstChangesCount++;
}
}
}
@NgModule({imports: [BrowserModule], declarations: [Ng2Component]})
class Ng2Module {}
const ng1Module = angular
.module_('ng1', [])
.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
const element = html(`
<ng2 [foo]="'foo'"></ng2>
<ng2 foo="bar"></ng2>
<ng2 [foo]="'baz'" ng-if="true"></ng2>
<ng2 foo="qux" ng-if="true"></ng2>
`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
const nodes = element.querySelectorAll('ng2');
const expectedTextWith = (value: string) =>
`ngOnChangesCount: 1 | firstChangesCount: 1 | initialValue: ${value}`;
expect(multiTrim(nodes[0].textContent)).toBe(expectedTextWith('foo'));
expect(multiTrim(nodes[1].textContent)).toBe(expectedTextWith('bar'));
expect(multiTrim(nodes[2].textContent)).toBe(expectedTextWith('baz'));
expect(multiTrim(nodes[3].textContent)).toBe(expectedTextWith('qux'));
ref.dispose();
});
}));
it('should bind to ng-model', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
ng1Module.run(($rootScope: any) => {
$rootScope.modelA = 'A';
});
let ng2Instance: Ng2;
@Component({
selector: 'ng2',
template: '{{_value}}',
standalone: false,
})
class Ng2 {
private _value: any = '';
private _onChangeCallback: (_: any) => void = () => {};
private _onTouchedCallback: () => void = () => {};
constructor() {
ng2Instance = this;
}
writeValue(value: any) {
this._value = value;
}
registerOnChange(fn: any) {
this._onChangeCallback = fn;
}
registerOnTouched(fn: any) {
this._onTouchedCallback = fn;
}
doTouch() {
this._onTouchedCallback();
}
doChange(newValue: string) {
this._value = newValue;
this._onChangeCallback(newValue);
}
}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2 ng-model="modelA"></ng2> | {{modelA}}</div>`);
@NgModule({
declarations: [Ng2],
imports: [BrowserModule],
schemas: [NO_ERRORS_SCHEMA],
})
class Ng2Module {}
adapter.bootstrap(element, ['ng1']).ready((ref) => {
let $rootScope: any = ref.ng1RootScope;
expect(multiTrim(document.body.textContent)).toEqual('A | A');
$rootScope.modelA = 'B';
$rootScope.$apply();
expect(multiTrim(document.body.textContent)).toEqual('B | B');
ng2Instance.doChange('C');
expect($rootScope.modelA).toBe('C');
expect(multiTrim(document.body.textContent)).toEqual('C | C');
const downgradedElement = <Element>document.body.querySelector('ng2');
expect(downgradedElement.classList.contains('ng-touched')).toBe(false);
ng2Instance.doTouch();
$rootScope.$apply();
expect(downgradedElement.classList.contains('ng-touched')).toBe(true);
ref.dispose();
});
}));
it('should properly run cleanup when ng1 directive is destroyed', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
let ng2ComponentDestroyed = false;
ng1Module.directive('ng1', () => ({
template: '<div ng-if="!destroyIt"><ng2></ng2></div>',
}));
@Component({
selector: 'ng2',
template: '<ul><li>test1</li><li>test2</li></ul>',
standalone: false,
})
class Ng2 {
ngOnDestroy() {
ng2ComponentDestroyed = true;
}
}
@NgModule({
declarations: [Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html('<ng1></ng1>');
adapter.bootstrap(element, ['ng1']).ready((ref) => {
const ng2Element = angular.element(element.querySelector('ng2') as Element);
const ng2Descendants = Array.from(element.querySelectorAll('ng2 li')).map(
angular.element,
);
let ng2ElementDestroyed = false;
let ng2DescendantsDestroyed = ng2Descendants.map(() => false);
ng2Element.data!('test', 42);
ng2Descendants.forEach((elem, i) => elem.data!('test', i));
ng2Element.on!('$destroy', () => (ng2ElementDestroyed = true));
ng2Descendants.forEach((elem, i) =>
elem.on!('$destroy', () => (ng2DescendantsDestroyed[i] = true)),
);
expect(element.textContent).toBe('test1test2');
expect(ng2Element.data!('test')).toBe(42);
ng2Descendants.forEach((elem, i) => expect(elem.data!('test')).toBe(i));
expect(ng2ElementDestroyed).toBe(false);
expect(ng2DescendantsDestroyed).toEqual([false, false]);
expect(ng2ComponentDestroyed).toBe(false);
ref.ng1RootScope.$apply('destroyIt = true');
expect(element.textContent).toBe('');
expect(ng2Element.data!('test')).toBeUndefined();
ng2Descendants.forEach((elem) => expect(elem.data!('test')).toBeUndefined());
expect(ng2ElementDestroyed).toBe(true);
expect(ng2DescendantsDestroyed).toEqual([true, true]);
expect(ng2ComponentDestroyed).toBe(true);
ref.dispose();
});
}));
it('should properly run cleanup with multiple levels of nesting', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
let destroyed = false;
@Component({
selector: 'ng2-outer',
template: '<div *ngIf="!destroyIt"><ng1></ng1></div>',
standalone: false,
})
class Ng2OuterComponent {
@Input() destroyIt = false;
}
@Component({
selector: 'ng2-inner',
template: 'test',
standalone: false,
})
class Ng2InnerComponent implements OnDestroy {
ngOnDestroy() {
destroyed = true;
}
}
@NgModule({
imports: [BrowserModule],
declarations: [Ng2InnerComponent, Ng2OuterComponent, adapter.upgradeNg1Component('ng1')],
schemas: [NO_ERRORS_SCHEMA],
})
class Ng2Module {}
const ng1Module = angular
.module_('ng1', [])
.directive('ng1', () => ({template: '<ng2-inner></ng2-inner>'}))
.directive('ng2Inner', adapter.downgradeNg2Component(Ng2InnerComponent))
.directive('ng2Outer', adapter.downgradeNg2Component(Ng2OuterComponent));
const element = html('<ng2-outer [destroy-it]="destroyIt"></ng2-outer>');
adapter.bootstrap(element, [ng1Module.name]).ready((ref) => {
expect(element.textContent).toBe('test');
expect(destroyed).toBe(false);
$apply(ref, 'destroyIt = true');
expect(element.textContent).toBe('');
expect(destroyed).toBe(true);
});
})); | {
"end_byte": 31476,
"start_byte": 22980,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts"
} |
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_31484_36214 | it('should fallback to the root ng2.injector when compiled outside the dom', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
ng1Module.directive('ng1', [
'$compile',
($compile: Function) => {
return {
link: function ($scope: any, $element: any, $attrs: any) {
const compiled = $compile('<ng2></ng2>');
const template = compiled($scope);
$element.append(template);
},
};
},
]);
@Component({
selector: 'ng2',
template: 'test',
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html('<ng1></ng1>');
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('test');
ref.dispose();
});
}));
it('should support multi-slot projection', waitForAsync(() => {
const ng1Module = angular.module_('ng1', []);
@Component({
selector: 'ng2',
template:
'2a(<ng-content select=".ng1a"></ng-content>)' +
'2b(<ng-content select=".ng1b"></ng-content>)',
standalone: false,
})
class Ng2 {}
@NgModule({declarations: [Ng2], imports: [BrowserModule]})
class Ng2Module {}
// The ng-if on one of the projected children is here to make sure
// the correct slot is targeted even with structural directives in play.
const element = html(
'<ng2><div ng-if="true" class="ng1a">1a</div><div' + ' class="ng1b">1b</div></ng2>',
);
const adapter: UpgradeAdapter = new UpgradeAdapter(Ng2Module);
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(document.body.textContent).toEqual('2a(1a)2b(1b)');
ref.dispose();
});
}));
it('should correctly project structural directives', waitForAsync(() => {
@Component({
selector: 'ng2',
template: 'ng2-{{ itemId }}(<ng-content></ng-content>)',
standalone: false,
})
class Ng2Component {
@Input() itemId: string = '';
}
@NgModule({imports: [BrowserModule], declarations: [Ng2Component]})
class Ng2Module {}
const adapter: UpgradeAdapter = new UpgradeAdapter(Ng2Module);
const ng1Module = angular
.module_('ng1', [])
.directive('ng2', adapter.downgradeNg2Component(Ng2Component))
.run(($rootScope: angular.IRootScopeService) => {
$rootScope['items'] = [
{id: 'a', subitems: [1, 2, 3]},
{id: 'b', subitems: [4, 5, 6]},
{id: 'c', subitems: [7, 8, 9]},
];
});
const element = html(`
<ng2 ng-repeat="item in items" [item-id]="item.id">
<div ng-repeat="subitem in item.subitems">{{ subitem }}</div>
</ng2>
`);
adapter.bootstrap(element, [ng1Module.name]).ready((ref) => {
expect(multiTrim(document.body.textContent)).toBe('ng2-a( 123 )ng2-b( 456 )ng2-c( 789 )');
ref.dispose();
});
}));
it('should allow attribute selectors for components in ng2', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
const ng1Module = angular.module_('myExample', []);
@Component({
selector: '[works]',
template: 'works!',
standalone: false,
})
class WorksComponent {}
@Component({
selector: 'root-component',
template: 'It <div works></div>',
standalone: false,
})
class RootComponent {}
@NgModule({imports: [BrowserModule], declarations: [RootComponent, WorksComponent]})
class MyNg2Module {}
ng1Module.directive('rootComponent', adapter.downgradeNg2Component(RootComponent));
document.body.innerHTML = '<root-component></root-component>';
adapter.bootstrap(document.body.firstElementChild!, ['myExample']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('It works!');
ref.dispose();
});
}));
});
describe('upgrade ng1 component', | {
"end_byte": 36214,
"start_byte": 31484,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts"
} |
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_36215_44414 | () => {
it('should support `@` bindings', fakeAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
let ng2ComponentInstance: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'Inside: {{ $ctrl.inputA }}, {{ $ctrl.inputB }}',
bindings: {inputA: '@inputAttrA', inputB: '@'},
};
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1 inputAttrA="{{ dataA }}" inputB="{{ dataB }}"></ng1>
| Outside: {{ dataA }}, {{ dataB }}
`,
standalone: false,
})
class Ng2Component {
dataA = 'foo';
dataB = 'bar';
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
// Define `Ng2Module`
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {}
// Bootstrap
const element = html(`<ng2></ng2>`);
adapter.bootstrap(element, ['ng1Module']).ready((ref) => {
const ng1 = element.querySelector('ng1')!;
const ng1Controller = angular.element(ng1).controller!('ng1');
expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar');
ng1Controller.inputA = 'baz';
ng1Controller.inputB = 'qux';
$digest(ref);
expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: foo, bar');
ng2ComponentInstance.dataA = 'foo2';
ng2ComponentInstance.dataB = 'bar2';
$digest(ref);
expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2');
ref.dispose();
});
}));
it('should support `<` bindings', fakeAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
let ng2ComponentInstance: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'Inside: {{ $ctrl.inputA.value }}, {{ $ctrl.inputB.value }}',
bindings: {inputA: '<inputAttrA', inputB: '<'},
};
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1 [inputAttrA]="dataA" [inputB]="dataB"></ng1>
| Outside: {{ dataA.value }}, {{ dataB.value }}
`,
standalone: false,
})
class Ng2Component {
dataA = {value: 'foo'};
dataB = {value: 'bar'};
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
// Define `Ng2Module`
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {}
// Bootstrap
const element = html(`<ng2></ng2>`);
adapter.bootstrap(element, ['ng1Module']).ready((ref) => {
const ng1 = element.querySelector('ng1')!;
const ng1Controller = angular.element(ng1).controller!('ng1');
expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar');
ng1Controller.inputA = {value: 'baz'};
ng1Controller.inputB = {value: 'qux'};
$digest(ref);
expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: foo, bar');
ng2ComponentInstance.dataA = {value: 'foo2'};
ng2ComponentInstance.dataB = {value: 'bar2'};
$digest(ref);
expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2');
ref.dispose();
});
}));
it('should support `=` bindings', fakeAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
let ng2ComponentInstance: Ng2Component;
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'Inside: {{ $ctrl.inputA.value }}, {{ $ctrl.inputB.value }}',
bindings: {inputA: '=inputAttrA', inputB: '='},
};
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1 [(inputAttrA)]="dataA" [(inputB)]="dataB"></ng1>
| Outside: {{ dataA.value }}, {{ dataB.value }}
`,
standalone: false,
})
class Ng2Component {
dataA = {value: 'foo'};
dataB = {value: 'bar'};
constructor() {
ng2ComponentInstance = this;
}
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
// Define `Ng2Module`
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {}
// Bootstrap
const element = html(`<ng2></ng2>`);
adapter.bootstrap(element, ['ng1Module']).ready((ref) => {
const ng1 = element.querySelector('ng1')!;
const ng1Controller = angular.element(ng1).controller!('ng1');
expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar');
ng1Controller.inputA = {value: 'baz'};
ng1Controller.inputB = {value: 'qux'};
$digest(ref);
expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: baz, qux');
ng2ComponentInstance.dataA = {value: 'foo2'};
ng2ComponentInstance.dataB = {value: 'bar2'};
$digest(ref);
expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2');
ref.dispose();
});
}));
it('should support `&` bindings', fakeAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
// Define `ng1Component`
const ng1Component: angular.IComponent = {
template: 'Inside: -',
bindings: {outputA: '&outputAttrA', outputB: '&'},
};
// Define `Ng2Component`
@Component({
selector: 'ng2',
template: `
<ng1 (outputAttrA)="dataA = $event" (outputB)="dataB = $event"></ng1>
| Outside: {{ dataA }}, {{ dataB }}
`,
standalone: false,
})
class Ng2Component {
dataA = 'foo';
dataB = 'bar';
}
// Define `ng1Module`
const ng1Module = angular
.module_('ng1Module', [])
.component('ng1', ng1Component)
.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
// Define `Ng2Module`
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component],
imports: [BrowserModule],
})
class Ng2Module {}
// Bootstrap
const element = html(`<ng2></ng2>`);
adapter.bootstrap(element, ['ng1Module']).ready((ref) => {
const ng1 = element.querySelector('ng1')!;
const ng1Controller = angular.element(ng1).controller!('ng1');
expect(multiTrim(element.textContent)).toBe('Inside: - | Outside: foo, bar');
ng1Controller.outputA('baz');
ng1Controller.outputB('qux');
$digest(ref);
expect(multiTrim(element.textContent)).toBe('Inside: - | Outside: baz, qux');
ref.dispose();
});
})); | {
"end_byte": 44414,
"start_byte": 36215,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts"
} |
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_44422_51608 | it('should bind properties, events', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const ng1 = () => {
return {
template: 'Hello {{fullName}}; A: {{modelA}}; B: {{modelB}}; C: {{modelC}}; | ',
scope: {fullName: '@', modelA: '=dataA', modelB: '=dataB', modelC: '=', event: '&'},
link: function (scope: any) {
scope.$watch('modelB', (v: string) => {
if (v == 'Savkin') {
scope.modelB = 'SAVKIN';
scope.event('WORKS');
// Should not update because [model-a] is uni directional
scope.modelA = 'VICTOR';
}
});
},
};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template:
'<ng1 fullName="{{last}}, {{first}}, {{city}}" [dataA]="first" [(dataB)]="last" [modelC]="city" ' +
'(event)="event=$event"></ng1>' +
'<ng1 fullName="{{\'TEST\'}}" dataA="First" dataB="Last" modelC="City"></ng1>' +
'{{event}}-{{last}}, {{first}}, {{city}}',
standalone: false,
})
class Ng2 {
first = 'Victor';
last = 'Savkin';
city = 'SF';
event = '?';
}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
// we need to do setTimeout, because the EventEmitter uses setTimeout to schedule
// events, and so without this we would not see the events processed.
setTimeout(() => {
expect(multiTrim(document.body.textContent)).toEqual(
'Hello SAVKIN, Victor, SF; A: VICTOR; B: SAVKIN; C: SF; | Hello TEST; A: First; B: Last; C: City; | WORKS-SAVKIN, Victor, SF',
);
ref.dispose();
}, 0);
});
}));
it('should bind optional properties', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const ng1 = () => {
return {
template: 'Hello; A: {{modelA}}; B: {{modelB}}; | ',
scope: {modelA: '=?dataA', modelB: '=?'},
};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template:
'<ng1 [dataA]="first" [modelB]="last"></ng1>' +
'<ng1 dataA="First" modelB="Last"></ng1>' +
'<ng1></ng1>' +
'<ng1></ng1>',
standalone: false,
})
class Ng2 {
first = 'Victor';
last = 'Savkin';
}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
// we need to do setTimeout, because the EventEmitter uses setTimeout to schedule
// events, and so without this we would not see the events processed.
setTimeout(() => {
expect(multiTrim(document.body.textContent)).toEqual(
'Hello; A: Victor; B: Savkin; | Hello; A: First; B: Last; | Hello; A: ; B: ; | Hello; A: ; B: ; |',
);
ref.dispose();
}, 0);
});
}));
it('should bind properties, events in controller when bindToController is not used', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const ng1 = () => {
return {
restrict: 'E',
template: '{{someText}} - Length: {{data.length}}',
scope: {data: '='},
controller: function ($scope: any) {
$scope.someText = 'ng1 - Data: ' + $scope.data;
},
};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '{{someText}} - Length: {{dataList.length}} | <ng1 [(data)]="dataList"></ng1>',
standalone: false,
})
class Ng2 {
dataList = [1, 2, 3];
someText = 'ng2';
}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
// we need to do setTimeout, because the EventEmitter uses setTimeout to schedule
// events, and so without this we would not see the events processed.
setTimeout(() => {
expect(multiTrim(document.body.textContent)).toEqual(
'ng2 - Length: 3 | ng1 - Data: 1,2,3 - Length: 3',
);
ref.dispose();
}, 0);
});
}));
it('should bind properties, events in link function', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const ng1 = () => {
return {
restrict: 'E',
template: '{{someText}} - Length: {{data.length}}',
scope: {data: '='},
link: function ($scope: any) {
$scope.someText = 'ng1 - Data: ' + $scope.data;
},
};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '{{someText}} - Length: {{dataList.length}} | <ng1 [(data)]="dataList"></ng1>',
standalone: false,
})
class Ng2 {
dataList = [1, 2, 3];
someText = 'ng2';
}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
// we need to do setTimeout, because the EventEmitter uses setTimeout to schedule
// events, and so without this we would not see the events processed.
setTimeout(() => {
expect(multiTrim(document.body.textContent)).toEqual(
'ng2 - Length: 3 | ng1 - Data: 1,2,3 - Length: 3',
);
ref.dispose();
}, 0);
});
})); | {
"end_byte": 51608,
"start_byte": 44422,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts"
} |
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_51616_59968 | it('should support templateUrl fetched from $httpBackend', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
ng1Module.value(
'$httpBackend',
(method: string, url: string, post: any, cbFn: Function) => {
cbFn(200, `${method}:${url}`);
},
);
const ng1 = () => {
return {templateUrl: 'url.html'};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('GET:url.html');
ref.dispose();
});
}));
it('should support templateUrl as a function', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
ng1Module.value(
'$httpBackend',
(method: string, url: string, post: any, cbFn: Function) => {
cbFn(200, `${method}:${url}`);
},
);
const ng1 = () => {
return {
templateUrl() {
return 'url.html';
},
};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('GET:url.html');
ref.dispose();
});
}));
it('should support empty template', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const ng1 = () => {
return {template: ''};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('');
ref.dispose();
});
}));
it('should support template as a function', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const ng1 = () => {
return {
template() {
return '';
},
};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('');
ref.dispose();
});
}));
it('should support templateUrl fetched from $templateCache', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
ng1Module.run(($templateCache: any) => $templateCache.put('url.html', 'WORKS'));
const ng1 = () => {
return {templateUrl: 'url.html'};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('WORKS');
ref.dispose();
});
}));
it('should support controller with controllerAs', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const ng1 = () => {
return {
scope: true,
template: '{{ctl.scope}}; {{ctl.isClass}}; {{ctl.hasElement}}; {{ctl.isPublished()}}',
controllerAs: 'ctl',
controller: class {
scope: any;
hasElement: string;
$element: any;
isClass: any;
constructor($scope: any, $element: any) {
this.verifyIAmAClass();
this.scope = $scope.$parent.$parent == $scope.$root ? 'scope' : 'wrong-scope';
this.hasElement = $element[0].nodeName;
this.$element = $element;
}
verifyIAmAClass() {
this.isClass = 'isClass';
}
isPublished() {
return this.$element.controller('ng1') == this ? 'published' : 'not-published';
}
},
};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('scope; isClass; NG1; published');
ref.dispose();
});
}));
it('should support bindToController', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const ng1 = () => {
return {
scope: {title: '@'},
bindToController: true,
template: '{{ctl.title}}',
controllerAs: 'ctl',
controller: class {},
};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '<ng1 title="WORKS"></ng1>',
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('WORKS');
ref.dispose();
});
})); | {
"end_byte": 59968,
"start_byte": 51616,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts"
} |
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_59976_64510 | it('should support bindToController with bindings', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const ng1 = () => {
return {
scope: {},
bindToController: {title: '@'},
template: '{{ctl.title}}',
controllerAs: 'ctl',
controller: class {},
};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '<ng1 title="WORKS"></ng1>',
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('WORKS');
ref.dispose();
});
}));
it('should support single require in linking fn', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const ng1 = ($rootScope: any) => {
return {
scope: {title: '@'},
bindToController: true,
template: '{{ctl.status}}',
require: 'ng1',
controllerAs: 'ctrl',
controller: class {
status = 'WORKS';
},
link: function (scope: any, element: any, attrs: any, linkController: any) {
expect(scope.$root).toEqual($rootScope);
expect(element[0].nodeName).toEqual('NG1');
expect(linkController.status).toEqual('WORKS');
scope.ctl = linkController;
},
};
};
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('WORKS');
ref.dispose();
});
}));
it('should support array require in linking fn', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const ng1Module = angular.module_('ng1', []);
const parent = () => {
return {
controller: class {
parent = 'PARENT';
},
};
};
const ng1 = () => {
return {
scope: {title: '@'},
bindToController: true,
template: '{{parent.parent}}:{{ng1.status}}',
require: ['ng1', '^parent', '?^^notFound'],
controllerAs: 'ctrl',
controller: class {
status = 'WORKS';
},
link: function (scope: any, element: any, attrs: any, linkControllers: any) {
expect(linkControllers[0].status).toEqual('WORKS');
expect(linkControllers[1].parent).toEqual('PARENT');
expect(linkControllers[2]).toBe(undefined);
scope.ng1 = linkControllers[0];
scope.parent = linkControllers[1];
},
};
};
ng1Module.directive('parent', parent);
ng1Module.directive('ng1', ng1);
@Component({
selector: 'ng2',
template: '<ng1></ng1>',
standalone: false,
})
class Ng2 {}
@NgModule({
declarations: [adapter.upgradeNg1Component('ng1'), Ng2],
imports: [BrowserModule],
})
class Ng2Module {}
ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2));
const element = html(`<div><parent><ng2></ng2></parent></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect(multiTrim(document.body.textContent)).toEqual('PARENT:WORKS');
ref.dispose();
});
})); | {
"end_byte": 64510,
"start_byte": 59976,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts"
} |
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_64518_72288 | describe('with life-cycle hooks', () => {
it('should call `$onInit()` on controller', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const $onInitSpyA = jasmine.createSpy('$onInitA');
const $onInitSpyB = jasmine.createSpy('$onInitB');
@Component({
selector: 'ng2',
template: '<ng1-a></ng1-a> | <ng1-b></ng1-b>',
standalone: false,
})
class Ng2Component {}
angular
.module_('ng1', [])
.directive('ng1A', () => ({
template: '',
scope: {},
bindToController: true,
controllerAs: '$ctrl',
controller: class {
$onInit() {
$onInitSpyA();
}
},
}))
.directive('ng1B', () => ({
template: '',
scope: {},
bindToController: false,
controllerAs: '$ctrl',
controller: function (this: any) {
this.$onInit = $onInitSpyB;
},
}))
.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
@NgModule({
declarations: [
adapter.upgradeNg1Component('ng1A'),
adapter.upgradeNg1Component('ng1B'),
Ng2Component,
],
imports: [BrowserModule],
})
class Ng2Module {}
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect($onInitSpyA).toHaveBeenCalled();
expect($onInitSpyB).toHaveBeenCalled();
ref.dispose();
});
}));
it('should not call `$onInit()` on scope', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const $onInitSpy = jasmine.createSpy('$onInit');
@Component({
selector: 'ng2',
template: '<ng1-a></ng1-a> | <ng1-b></ng1-b>',
standalone: false,
})
class Ng2Component {}
angular
.module_('ng1', [])
.directive('ng1A', () => ({
template: '',
scope: {},
bindToController: true,
controllerAs: '$ctrl',
controller: function ($scope: angular.IScope) {
Object.getPrototypeOf($scope).$onInit = $onInitSpy;
},
}))
.directive('ng1B', () => ({
template: '',
scope: {},
bindToController: false,
controllerAs: '$ctrl',
controller: function ($scope: angular.IScope) {
$scope['$onInit'] = $onInitSpy;
},
}))
.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
@NgModule({
declarations: [
adapter.upgradeNg1Component('ng1A'),
adapter.upgradeNg1Component('ng1B'),
Ng2Component,
],
imports: [BrowserModule],
})
class Ng2Module {}
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect($onInitSpy).not.toHaveBeenCalled();
ref.dispose();
});
}));
it('should call `$doCheck()` on controller', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const $doCheckSpyA = jasmine.createSpy('$doCheckA');
const $doCheckSpyB = jasmine.createSpy('$doCheckB');
let changeDetector: ChangeDetectorRef;
@Component({
selector: 'ng2',
template: '<ng1-a></ng1-a> | <ng1-b></ng1-b>',
standalone: false,
})
class Ng2Component {
constructor(cd: ChangeDetectorRef) {
changeDetector = cd;
}
}
angular
.module_('ng1', [])
.directive('ng1A', () => ({
template: '',
scope: {},
bindToController: true,
controllerAs: '$ctrl',
controller: class {
$doCheck() {
$doCheckSpyA();
}
},
}))
.directive('ng1B', () => ({
template: '',
scope: {},
bindToController: false,
controllerAs: '$ctrl',
controller: function (this: any) {
this.$doCheck = $doCheckSpyB;
},
}))
.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
@NgModule({
declarations: [
adapter.upgradeNg1Component('ng1A'),
adapter.upgradeNg1Component('ng1B'),
Ng2Component,
],
imports: [BrowserModule],
})
class Ng2Module {}
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
expect($doCheckSpyA).toHaveBeenCalled();
expect($doCheckSpyB).toHaveBeenCalled();
$doCheckSpyA.calls.reset();
$doCheckSpyB.calls.reset();
changeDetector.detectChanges();
expect($doCheckSpyA).toHaveBeenCalled();
expect($doCheckSpyB).toHaveBeenCalled();
ref.dispose();
});
}));
it('should not call `$doCheck()` on scope', waitForAsync(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const $doCheckSpyA = jasmine.createSpy('$doCheckA');
const $doCheckSpyB = jasmine.createSpy('$doCheckB');
let changeDetector: ChangeDetectorRef;
@Component({
selector: 'ng2',
template: '<ng1-a></ng1-a> | <ng1-b></ng1-b>',
standalone: false,
})
class Ng2Component {
constructor(cd: ChangeDetectorRef) {
changeDetector = cd;
}
}
angular
.module_('ng1', [])
.directive('ng1A', () => ({
template: '',
scope: {},
bindToController: true,
controllerAs: '$ctrl',
controller: function ($scope: angular.IScope) {
Object.getPrototypeOf($scope).$doCheck = $doCheckSpyA;
},
}))
.directive('ng1B', () => ({
template: '',
scope: {},
bindToController: false,
controllerAs: '$ctrl',
controller: function ($scope: angular.IScope) {
$scope['$doCheck'] = $doCheckSpyB;
},
}))
.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
@NgModule({
declarations: [
adapter.upgradeNg1Component('ng1A'),
adapter.upgradeNg1Component('ng1B'),
Ng2Component,
],
imports: [BrowserModule],
})
class Ng2Module {}
const element = html(`<div><ng2></ng2></div>`);
adapter.bootstrap(element, ['ng1']).ready((ref) => {
$doCheckSpyA.calls.reset();
$doCheckSpyB.calls.reset();
changeDetector.detectChanges();
expect($doCheckSpyA).not.toHaveBeenCalled();
expect($doCheckSpyB).not.toHaveBeenCalled();
ref.dispose();
});
})); | {
"end_byte": 72288,
"start_byte": 64518,
"url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.