_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/core/src/util/performance.ts_0_766 | /**
* @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
*/
const markedFeatures = new Set<string>();
// tslint:disable:ban
/**
* A guarded `performance.mark` for feature marking.
*
* This method exists because while all supported browser and node.js version supported by Angular
* support performance.mark API. This is not the case for other environments such as JSDOM and
* Cloudflare workers.
*/
export function performanceMarkFeature(feature: string): void {
if (markedFeatures.has(feature)) {
return;
}
markedFeatures.add(feature);
performance?.mark?.('mark_feature_usage', {detail: {feature}});
}
| {
"end_byte": 766,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/performance.ts"
} |
angular/packages/core/src/util/noop.ts_0_267 | /**
* @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 function noop(...args: any[]): any {
// Do nothing.
}
| {
"end_byte": 267,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/noop.ts"
} |
angular/packages/core/src/util/ng_i18n_closure_mode.ts_0_1091 | /**
* @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 {global} from './global';
declare global {
const ngI18nClosureMode: boolean;
}
/**
* NOTE: changes to the `ngI18nClosureMode` name must be synced with `compiler-cli/src/tooling.ts`.
*/
if (typeof ngI18nClosureMode === 'undefined') {
// These property accesses can be ignored because ngI18nClosureMode will be set to false
// when optimizing code and the whole if statement will be dropped.
// Make sure to refer to ngI18nClosureMode as ['ngI18nClosureMode'] for closure.
// NOTE: we need to have it in IIFE so that the tree-shaker is happy.
(function () {
// tslint:disable-next-line:no-toplevel-property-access
global['ngI18nClosureMode'] =
// TODO(FW-1250): validate that this actually, you know, works.
// tslint:disable-next-line:no-toplevel-property-access
typeof goog !== 'undefined' && typeof goog.getMsg === 'function';
})();
}
| {
"end_byte": 1091,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/ng_i18n_closure_mode.ts"
} |
angular/packages/core/src/util/coercion.ts_0_1512 | /**
* @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
*/
/**
* Transforms a value (typically a string) to a boolean.
* Intended to be used as a transform function of an input.
*
* @usageNotes
* ```typescript
* @Input({ transform: booleanAttribute }) status!: boolean;
* ```
* @param value Value to be transformed.
*
* @publicApi
*/
export function booleanAttribute(value: unknown): boolean {
return typeof value === 'boolean' ? value : value != null && value !== 'false';
}
/**
* Transforms a value (typically a string) to a number.
* Intended to be used as a transform function of an input.
* @param value Value to be transformed.
* @param fallbackValue Value to use if the provided value can't be parsed as a number.
*
* @usageNotes
* ```typescript
* @Input({ transform: numberAttribute }) id!: number;
* ```
*
* @publicApi
*/
export function numberAttribute(value: unknown, fallbackValue = NaN): number {
// parseFloat(value) handles most of the cases we're interested in (it treats null, empty string,
// and other non-number values as NaN, where Number just uses 0) but it considers the string
// '123hello' to be a valid number. Therefore we also check if Number(value) is NaN.
const isNumberValue = !isNaN(parseFloat(value as any)) && !isNaN(Number(value));
return isNumberValue ? Number(value) : fallbackValue;
}
| {
"end_byte": 1512,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/coercion.ts"
} |
angular/packages/core/src/util/comparison.ts_0_860 | /**
* @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 {areIterablesEqual, isListLikeIterable} from './iterable';
export function devModeEqual(a: any, b: any): boolean {
const isListLikeIterableA = isListLikeIterable(a);
const isListLikeIterableB = isListLikeIterable(b);
if (isListLikeIterableA && isListLikeIterableB) {
return areIterablesEqual(a, b, devModeEqual);
} else {
const isAObject = a && (typeof a === 'object' || typeof a === 'function');
const isBObject = b && (typeof b === 'object' || typeof b === 'function');
if (!isListLikeIterableA && isAObject && !isListLikeIterableB && isBObject) {
return true;
} else {
return Object.is(a, b);
}
}
}
| {
"end_byte": 860,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/comparison.ts"
} |
angular/packages/core/src/util/assert.ts_0_4681 | /**
* @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
*/
// The functions in this file verify that the assumptions we are making
// about state in an instruction are correct before implementing any logic.
// They are meant only to be called in dev mode as sanity checks.
import {getActiveConsumer} from '@angular/core/primitives/signals';
import {stringify} from './stringify';
export function assertNumber(actual: any, msg: string): asserts actual is number {
if (!(typeof actual === 'number')) {
throwError(msg, typeof actual, 'number', '===');
}
}
export function assertNumberInRange(
actual: any,
minInclusive: number,
maxInclusive: number,
): asserts actual is number {
assertNumber(actual, 'Expected a number');
assertLessThanOrEqual(actual, maxInclusive, 'Expected number to be less than or equal to');
assertGreaterThanOrEqual(actual, minInclusive, 'Expected number to be greater than or equal to');
}
export function assertString(actual: any, msg: string): asserts actual is string {
if (!(typeof actual === 'string')) {
throwError(msg, actual === null ? 'null' : typeof actual, 'string', '===');
}
}
export function assertFunction(actual: any, msg: string): asserts actual is Function {
if (!(typeof actual === 'function')) {
throwError(msg, actual === null ? 'null' : typeof actual, 'function', '===');
}
}
export function assertEqual<T>(actual: T, expected: T, msg: string) {
if (!(actual == expected)) {
throwError(msg, actual, expected, '==');
}
}
export function assertNotEqual<T>(actual: T, expected: T, msg: string): asserts actual is T {
if (!(actual != expected)) {
throwError(msg, actual, expected, '!=');
}
}
export function assertSame<T>(actual: T, expected: T, msg: string): asserts actual is T {
if (!(actual === expected)) {
throwError(msg, actual, expected, '===');
}
}
export function assertNotSame<T>(actual: T, expected: T, msg: string) {
if (!(actual !== expected)) {
throwError(msg, actual, expected, '!==');
}
}
export function assertLessThan<T>(actual: T, expected: T, msg: string): asserts actual is T {
if (!(actual < expected)) {
throwError(msg, actual, expected, '<');
}
}
export function assertLessThanOrEqual<T>(actual: T, expected: T, msg: string): asserts actual is T {
if (!(actual <= expected)) {
throwError(msg, actual, expected, '<=');
}
}
export function assertGreaterThan<T>(actual: T, expected: T, msg: string): asserts actual is T {
if (!(actual > expected)) {
throwError(msg, actual, expected, '>');
}
}
export function assertGreaterThanOrEqual<T>(
actual: T,
expected: T,
msg: string,
): asserts actual is T {
if (!(actual >= expected)) {
throwError(msg, actual, expected, '>=');
}
}
export function assertNotDefined<T>(actual: T, msg: string) {
if (actual != null) {
throwError(msg, actual, null, '==');
}
}
export function assertDefined<T>(actual: T | null | undefined, msg: string): asserts actual is T {
if (actual == null) {
throwError(msg, actual, null, '!=');
}
}
export function throwError(msg: string): never;
export function throwError(msg: string, actual: any, expected: any, comparison: string): never;
export function throwError(msg: string, actual?: any, expected?: any, comparison?: string): never {
throw new Error(
`ASSERTION ERROR: ${msg}` +
(comparison == null ? '' : ` [Expected=> ${expected} ${comparison} ${actual} <=Actual]`),
);
}
export function assertDomNode(node: any): asserts node is Node {
if (!(node instanceof Node)) {
throwError(`The provided value must be an instance of a DOM Node but got ${stringify(node)}`);
}
}
export function assertElement(node: any): asserts node is Element {
if (!(node instanceof Element)) {
throwError(`The provided value must be an element but got ${stringify(node)}`);
}
}
export function assertIndexInRange(arr: any[], index: number) {
assertDefined(arr, 'Array must be defined.');
const maxLen = arr.length;
if (index < 0 || index >= maxLen) {
throwError(`Index expected to be less than ${maxLen} but got ${index}`);
}
}
export function assertOneOf(value: any, ...validValues: any[]) {
if (validValues.indexOf(value) !== -1) return true;
throwError(
`Expected value to be one of ${JSON.stringify(validValues)} but was ${JSON.stringify(value)}.`,
);
}
export function assertNotReactive(fn: string): void {
if (getActiveConsumer() !== null) {
throwError(`${fn}() should never be called in a reactive context.`);
}
}
| {
"end_byte": 4681,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/assert.ts"
} |
angular/packages/core/src/util/empty.ts_0_1108 | /**
* @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 {initNgDevMode} from './ng_dev_mode';
/**
* This file contains reuseable "empty" symbols that can be used as default return values
* in different parts of the rendering code. Because the same symbols are returned, this
* allows for identity checks against these values to be consistently used by the framework
* code.
*/
export const EMPTY_OBJ: never = {} as never;
export const EMPTY_ARRAY: any[] = [];
// freezing the values prevents any code from accidentally inserting new values in
if ((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode()) {
// These property accesses can be ignored because ngDevMode will be set to false
// when optimizing code and the whole if statement will be dropped.
// tslint:disable-next-line:no-toplevel-property-access
Object.freeze(EMPTY_OBJ);
// tslint:disable-next-line:no-toplevel-property-access
Object.freeze(EMPTY_ARRAY);
}
| {
"end_byte": 1108,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/empty.ts"
} |
angular/packages/core/src/util/stringify.ts_0_1791 | /**
* @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 function stringify(token: any): string {
if (typeof token === 'string') {
return token;
}
if (Array.isArray(token)) {
return '[' + token.map(stringify).join(', ') + ']';
}
if (token == null) {
return '' + token;
}
if (token.overriddenName) {
return `${token.overriddenName}`;
}
if (token.name) {
return `${token.name}`;
}
const res = token.toString();
if (res == null) {
return '' + res;
}
const newLineIndex = res.indexOf('\n');
return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}
/**
* Concatenates two strings with separator, allocating new strings only when necessary.
*
* @param before before string.
* @param separator separator string.
* @param after after string.
* @returns concatenated string.
*/
export function concatStringsWithSpace(before: string | null, after: string | null): string {
return before == null || before === ''
? after === null
? ''
: after
: after == null || after === ''
? before
: before + ' ' + after;
}
/**
* Ellipses the string in the middle when longer than the max length
*
* @param string
* @param maxLength of the output string
* @returns ellipsed string with ... in the middle
*/
export function truncateMiddle(str: string, maxLength = 100): string {
if (!str || maxLength < 1 || str.length <= maxLength) return str;
if (maxLength == 1) return str.substring(0, 1) + '...';
const halfLimit = Math.round(maxLength / 2);
return str.substring(0, halfLimit) + '...' + str.substring(str.length - halfLimit);
}
| {
"end_byte": 1791,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/stringify.ts"
} |
angular/packages/core/src/util/ng_reflect.ts_0_936 | /**
* @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 function normalizeDebugBindingName(name: string) {
// Attribute names with `$` (eg `x-y$`) are valid per spec, but unsupported by some browsers
name = camelCaseToDashCase(name.replace(/[$@]/g, '_'));
return `ng-reflect-${name}`;
}
const CAMEL_CASE_REGEXP = /([A-Z])/g;
function camelCaseToDashCase(input: string): string {
return input.replace(CAMEL_CASE_REGEXP, (...m: any[]) => '-' + m[1].toLowerCase());
}
export function normalizeDebugBindingValue(value: any): string {
try {
// Limit the size of the value as otherwise the DOM just gets polluted.
return value != null ? value.toString().slice(0, 30) : value;
} catch (e) {
return '[ERROR] Exception while trying to serialize the value';
}
}
| {
"end_byte": 936,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/ng_reflect.ts"
} |
angular/packages/core/src/util/BUILD.bazel_0_765 | load("//tools:defaults.bzl", "ts_library", "tsec_test")
package(default_visibility = [
"//devtools:__subpackages__",
"//packages:__pkg__",
"//packages/core:__subpackages__",
"//tools/public_api_guard:__pkg__",
])
ts_library(
name = "util",
srcs = glob(
[
"**/*.ts",
],
),
deps = [
"//packages:types",
"//packages/core/primitives/signals",
"//packages/core/src/interface",
"//packages/zone.js/lib:zone_d_ts",
"@npm//rxjs",
],
)
tsec_test(
name = "tsec_test",
target = "util",
tsconfig = "//packages:tsec_config",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"**/*.ts",
]),
visibility = ["//visibility:public"],
)
| {
"end_byte": 765,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/BUILD.bazel"
} |
angular/packages/core/src/util/array_utils.ts_0_7536 | /**
* @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 {assertEqual, assertLessThanOrEqual} from './assert';
/**
* Determines if the contents of two arrays is identical
*
* @param a first array
* @param b second array
* @param identityAccessor Optional function for extracting stable object identity from a value in
* the array.
*/
export function arrayEquals<T>(a: T[], b: T[], identityAccessor?: (value: T) => unknown): boolean {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
let valueA = a[i];
let valueB = b[i];
if (identityAccessor) {
valueA = identityAccessor(valueA) as any;
valueB = identityAccessor(valueB) as any;
}
if (valueB !== valueA) {
return false;
}
}
return true;
}
/**
* Flattens an array.
*/
export function flatten(list: any[]): any[] {
return list.flat(Number.POSITIVE_INFINITY);
}
export function deepForEach<T>(input: (T | any[])[], fn: (value: T) => void): void {
input.forEach((value) => (Array.isArray(value) ? deepForEach(value, fn) : fn(value)));
}
export function addToArray(arr: any[], index: number, value: any): void {
// perf: array.push is faster than array.splice!
if (index >= arr.length) {
arr.push(value);
} else {
arr.splice(index, 0, value);
}
}
export function removeFromArray(arr: any[], index: number): any {
// perf: array.pop is faster than array.splice!
if (index >= arr.length - 1) {
return arr.pop();
} else {
return arr.splice(index, 1)[0];
}
}
export function newArray<T = any>(size: number): T[];
export function newArray<T>(size: number, value: T): T[];
export function newArray<T>(size: number, value?: T): T[] {
const list: T[] = [];
for (let i = 0; i < size; i++) {
list.push(value!);
}
return list;
}
/**
* Remove item from array (Same as `Array.splice()` but faster.)
*
* `Array.splice()` is not as fast because it has to allocate an array for the elements which were
* removed. This causes memory pressure and slows down code when most of the time we don't
* care about the deleted items array.
*
* https://jsperf.com/fast-array-splice (About 20x faster)
*
* @param array Array to splice
* @param index Index of element in array to remove.
* @param count Number of items to remove.
*/
export function arraySplice(array: any[], index: number, count: number): void {
const length = array.length - count;
while (index < length) {
array[index] = array[index + count];
index++;
}
while (count--) {
array.pop(); // shrink the array
}
}
/**
* Same as `Array.splice(index, 0, value)` but faster.
*
* `Array.splice()` is not fast because it has to allocate an array for the elements which were
* removed. This causes memory pressure and slows down code when most of the time we don't
* care about the deleted items array.
*
* @param array Array to splice.
* @param index Index in array where the `value` should be added.
* @param value Value to add to array.
*/
export function arrayInsert(array: any[], index: number, value: any): void {
ngDevMode && assertLessThanOrEqual(index, array.length, "Can't insert past array end.");
let end = array.length;
while (end > index) {
const previousEnd = end - 1;
array[end] = array[previousEnd];
end = previousEnd;
}
array[index] = value;
}
/**
* Same as `Array.splice2(index, 0, value1, value2)` but faster.
*
* `Array.splice()` is not fast because it has to allocate an array for the elements which were
* removed. This causes memory pressure and slows down code when most of the time we don't
* care about the deleted items array.
*
* @param array Array to splice.
* @param index Index in array where the `value` should be added.
* @param value1 Value to add to array.
* @param value2 Value to add to array.
*/
export function arrayInsert2(array: any[], index: number, value1: any, value2: any): void {
ngDevMode && assertLessThanOrEqual(index, array.length, "Can't insert past array end.");
let end = array.length;
if (end == index) {
// inserting at the end.
array.push(value1, value2);
} else if (end === 1) {
// corner case when we have less items in array than we have items to insert.
array.push(value2, array[0]);
array[0] = value1;
} else {
end--;
array.push(array[end - 1], array[end]);
while (end > index) {
const previousEnd = end - 2;
array[end] = array[previousEnd];
end--;
}
array[index] = value1;
array[index + 1] = value2;
}
}
/**
* Get an index of an `value` in a sorted `array`.
*
* NOTE:
* - This uses binary search algorithm for fast removals.
*
* @param array A sorted array to binary search.
* @param value The value to look for.
* @returns index of the value.
* - positive index if value found.
* - negative index if value not found. (`~index` to get the value where it should have been
* located)
*/
export function arrayIndexOfSorted(array: string[], value: string): number {
return _arrayIndexOfSorted(array, value, 0);
}
/**
* `KeyValueArray` is an array where even positions contain keys and odd positions contain values.
*
* `KeyValueArray` provides a very efficient way of iterating over its contents. For small
* sets (~10) the cost of binary searching an `KeyValueArray` has about the same performance
* characteristics that of a `Map` with significantly better memory footprint.
*
* If used as a `Map` the keys are stored in alphabetical order so that they can be binary searched
* for retrieval.
*
* See: `keyValueArraySet`, `keyValueArrayGet`, `keyValueArrayIndexOf`, `keyValueArrayDelete`.
*/
export interface KeyValueArray<VALUE> extends Array<VALUE | string> {
__brand__: 'array-map';
}
/**
* Set a `value` for a `key`.
*
* @param keyValueArray to modify.
* @param key The key to locate or create.
* @param value The value to set for a `key`.
* @returns index (always even) of where the value vas set.
*/
export function keyValueArraySet<V>(
keyValueArray: KeyValueArray<V>,
key: string,
value: V,
): number {
let index = keyValueArrayIndexOf(keyValueArray, key);
if (index >= 0) {
// if we found it set it.
keyValueArray[index | 1] = value;
} else {
index = ~index;
arrayInsert2(keyValueArray, index, key, value);
}
return index;
}
/**
* Retrieve a `value` for a `key` (on `undefined` if not found.)
*
* @param keyValueArray to search.
* @param key The key to locate.
* @return The `value` stored at the `key` location or `undefined if not found.
*/
export function keyValueArrayGet<V>(keyValueArray: KeyValueArray<V>, key: string): V | undefined {
const index = keyValueArrayIndexOf(keyValueArray, key);
if (index >= 0) {
// if we found it retrieve it.
return keyValueArray[index | 1] as V;
}
return undefined;
}
/**
* Retrieve a `key` index value in the array or `-1` if not found.
*
* @param keyValueArray to search.
* @param key The key to locate.
* @returns index of where the key is (or should have been.)
* - positive (even) index if key found.
* - negative index if key not found. (`~index` (even) to get the index where it should have
* been inserted.)
*/
export function keyValueArrayIndexOf<V>(keyValueArray: KeyValueArray<V>, key: string): number {
return _arrayIndexOfSorted(keyValueArray as string[], key, 1);
} | {
"end_byte": 7536,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/array_utils.ts"
} |
angular/packages/core/src/util/array_utils.ts_7538_9441 | /**
* Delete a `key` (and `value`) from the `KeyValueArray`.
*
* @param keyValueArray to modify.
* @param key The key to locate or delete (if exist).
* @returns index of where the key was (or should have been.)
* - positive (even) index if key found and deleted.
* - negative index if key not found. (`~index` (even) to get the index where it should have
* been.)
*/
export function keyValueArrayDelete<V>(keyValueArray: KeyValueArray<V>, key: string): number {
const index = keyValueArrayIndexOf(keyValueArray, key);
if (index >= 0) {
// if we found it remove it.
arraySplice(keyValueArray, index, 2);
}
return index;
}
/**
* INTERNAL: Get an index of an `value` in a sorted `array` by grouping search by `shift`.
*
* NOTE:
* - This uses binary search algorithm for fast removals.
*
* @param array A sorted array to binary search.
* @param value The value to look for.
* @param shift grouping shift.
* - `0` means look at every location
* - `1` means only look at every other (even) location (the odd locations are to be ignored as
* they are values.)
* @returns index of the value.
* - positive index if value found.
* - negative index if value not found. (`~index` to get the value where it should have been
* inserted)
*/
function _arrayIndexOfSorted(array: string[], value: string, shift: number): number {
ngDevMode && assertEqual(Array.isArray(array), true, 'Expecting an array');
let start = 0;
let end = array.length >> shift;
while (end !== start) {
const middle = start + ((end - start) >> 1); // find the middle.
const current = array[middle << shift];
if (value === current) {
return middle << shift;
} else if (current > value) {
end = middle;
} else {
start = middle + 1; // We already searched middle so make it non-inclusive by adding 1
}
}
return ~(end << shift);
} | {
"end_byte": 9441,
"start_byte": 7538,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/array_utils.ts"
} |
angular/packages/core/src/util/ng_jit_mode.ts_0_328 | /**
* @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
*/
declare global {
const ngJitMode: boolean;
}
// Make this an ES module to be able to augment the global scope
export {};
| {
"end_byte": 328,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/ng_jit_mode.ts"
} |
angular/packages/core/src/util/global.ts_0_452 | /**
* @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
*/
const _global: any = globalThis;
/**
* Attention: whenever providing a new value, be sure to add an
* entry into the corresponding `....externs.js` file,
* so that closure won't use that global for its purposes.
*/
export {_global as global};
| {
"end_byte": 452,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/global.ts"
} |
angular/packages/core/src/util/property.ts_0_1006 | /**
* @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 function getClosureSafeProperty<T>(objWithPropertyToExtract: T): string {
for (let key in objWithPropertyToExtract) {
if (objWithPropertyToExtract[key] === (getClosureSafeProperty as any)) {
return key;
}
}
throw Error('Could not find renamed property on target object.');
}
/**
* Sets properties on a target object from a source object, but only if
* the property doesn't already exist on the target object.
* @param target The target to set properties on
* @param source The source of the property keys and values to set
*/
export function fillProperties(target: Record<string, unknown>, source: Record<string, unknown>) {
for (const key in source) {
if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
target[key] = source[key];
}
}
}
| {
"end_byte": 1006,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/property.ts"
} |
angular/packages/core/src/util/char_code.ts_0_1043 | /**
* @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
*/
/**
* List ASCII char codes to be used with `String.charCodeAt`
*/
export const enum CharCode {
UPPER_CASE = ~32, // & with this will make the char uppercase
SPACE = 32, // " "
DOUBLE_QUOTE = 34, // "\""
HASH = 35, // "#"
SINGLE_QUOTE = 39, // "'"
OPEN_PAREN = 40, // "("
CLOSE_PAREN = 41, // ")"
STAR = 42, // "*"
SLASH = 47, // "/"
_0 = 48, // "0"
_1 = 49, // "1"
_2 = 50, // "2"
_3 = 51, // "3"
_4 = 52, // "4"
_5 = 53, // "5"
_6 = 54, // "6"
_7 = 55, // "7"
_8 = 56, // "8"
_9 = 57, // "9"
COLON = 58, // ":"
DASH = 45, // "-"
UNDERSCORE = 95, // "_"
SEMI_COLON = 59, // ";"
BACK_SLASH = 92, // "\\"
AT_SIGN = 64, // "@"
ZERO = 48, // "0"
NINE = 57, // "9"
A = 65, // "A"
U = 85, // "U"
R = 82, // "R"
L = 76, // "L"
Z = 90, // "A"
a = 97, // "a"
z = 122, // "z"
}
| {
"end_byte": 1043,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/char_code.ts"
} |
angular/packages/core/src/util/is_dev_mode.ts_0_1360 | /**
* @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 {global} from './global';
/**
* Returns whether Angular is in development mode.
*
* By default, this is true, unless `enableProdMode` is invoked prior to calling this method or the
* application is built using the Angular CLI with the `optimization` option.
* @see {@link cli/build ng build}
*
* @publicApi
*/
export function isDevMode(): boolean {
return typeof ngDevMode === 'undefined' || !!ngDevMode;
}
/**
* Disable Angular's development mode, which turns off assertions and other
* checks within the framework.
*
* One important assertion this disables verifies that a change detection pass
* does not result in additional changes to any bindings (also known as
* unidirectional data flow).
*
* Using this method is discouraged as the Angular CLI will set production mode when using the
* `optimization` option.
* @see {@link cli/build ng build}
*
* @publicApi
*/
export function enableProdMode(): void {
// The below check is there so when ngDevMode is set via terser
// `global['ngDevMode'] = false;` is also dropped.
if (typeof ngDevMode === 'undefined' || ngDevMode) {
global['ngDevMode'] = false;
}
}
| {
"end_byte": 1360,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/is_dev_mode.ts"
} |
angular/packages/core/src/util/iterable.ts_0_1581 | /**
* @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 function isIterable(obj: any): obj is Iterable<any> {
return obj !== null && typeof obj === 'object' && obj[Symbol.iterator] !== undefined;
}
export function isListLikeIterable(obj: any): boolean {
if (!isJsObject(obj)) return false;
return (
Array.isArray(obj) ||
(!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v]
Symbol.iterator in obj)
); // JS Iterable have a Symbol.iterator prop
}
export function areIterablesEqual<T>(
a: Iterable<T>,
b: Iterable<T>,
comparator: (a: T, b: T) => boolean,
): boolean {
const iterator1 = a[Symbol.iterator]();
const iterator2 = b[Symbol.iterator]();
while (true) {
const item1 = iterator1.next();
const item2 = iterator2.next();
if (item1.done && item2.done) return true;
if (item1.done || item2.done) return false;
if (!comparator(item1.value, item2.value)) return false;
}
}
export function iterateListLike<T>(obj: Iterable<T>, fn: (p: T) => void) {
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
fn(obj[i]);
}
} else {
const iterator = obj[Symbol.iterator]();
let item: IteratorResult<T, any>;
while (!(item = iterator.next()).done) {
fn(item.value);
}
}
}
export function isJsObject(o: any): boolean {
return o !== null && (typeof o === 'function' || typeof o === 'object');
}
| {
"end_byte": 1581,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/iterable.ts"
} |
angular/packages/core/src/util/lang.ts_0_739 | /**
* @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 {Subscribable} from 'rxjs';
/**
* Determine if the argument is shaped like a Promise
*/
export function isPromise<T = any>(obj: any): obj is Promise<T> {
// allow any Promise/A+ compliant thenable.
// It's up to the caller to ensure that obj.then conforms to the spec
return !!obj && typeof obj.then === 'function';
}
/**
* Determine if the argument is a Subscribable
*/
export function isSubscribable<T>(obj: any | Subscribable<T>): obj is Subscribable<T> {
return !!obj && typeof obj.subscribe === 'function';
}
| {
"end_byte": 739,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/lang.ts"
} |
angular/packages/core/src/util/security/trusted_types.ts_0_5899 | /**
* @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
*/
/**
* @fileoverview
* A module to facilitate use of a Trusted Types policy internally within
* Angular. It lazily constructs the Trusted Types policy, providing helper
* utilities for promoting strings to Trusted Types. When Trusted Types are not
* available, strings are used as a fallback.
* @security All use of this module is security-sensitive and should go through
* security review.
*/
import {global} from '../global';
import {
TrustedHTML,
TrustedScript,
TrustedScriptURL,
TrustedTypePolicy,
TrustedTypePolicyFactory,
} from './trusted_type_defs';
/**
* The Trusted Types policy, or null if Trusted Types are not
* enabled/supported, or undefined if the policy has not been created yet.
*/
let policy: TrustedTypePolicy | null | undefined;
/**
* Returns the Trusted Types policy, or null if Trusted Types are not
* enabled/supported. The first call to this function will create the policy.
*/
function getPolicy(): TrustedTypePolicy | null {
if (policy === undefined) {
policy = null;
if (global.trustedTypes) {
try {
policy = (global.trustedTypes as TrustedTypePolicyFactory).createPolicy('angular', {
createHTML: (s: string) => s,
createScript: (s: string) => s,
createScriptURL: (s: string) => s,
});
} catch {
// trustedTypes.createPolicy throws if called with a name that is
// already registered, even in report-only mode. Until the API changes,
// catch the error not to break the applications functionally. In such
// cases, the code will fall back to using strings.
}
}
}
return policy;
}
/**
* Unsafely promote a string to a TrustedHTML, falling back to strings when
* Trusted Types are not available.
* @security This is a security-sensitive function; any use of this function
* must go through security review. In particular, it must be assured that the
* provided string will never cause an XSS vulnerability if used in a context
* that will be interpreted as HTML by a browser, e.g. when assigning to
* element.innerHTML.
*/
export function trustedHTMLFromString(html: string): TrustedHTML | string {
return getPolicy()?.createHTML(html) || html;
}
/**
* Unsafely promote a string to a TrustedScript, falling back to strings when
* Trusted Types are not available.
* @security In particular, it must be assured that the provided string will
* never cause an XSS vulnerability if used in a context that will be
* interpreted and executed as a script by a browser, e.g. when calling eval.
*/
export function trustedScriptFromString(script: string): TrustedScript | string {
return getPolicy()?.createScript(script) || script;
}
/**
* Unsafely promote a string to a TrustedScriptURL, falling back to strings
* when Trusted Types are not available.
* @security This is a security-sensitive function; any use of this function
* must go through security review. In particular, it must be assured that the
* provided string will never cause an XSS vulnerability if used in a context
* that will cause a browser to load and execute a resource, e.g. when
* assigning to script.src.
*/
export function trustedScriptURLFromString(url: string): TrustedScriptURL | string {
return getPolicy()?.createScriptURL(url) || url;
}
/**
* Unsafely call the Function constructor with the given string arguments. It
* is only available in development mode, and should be stripped out of
* production code.
* @security This is a security-sensitive function; any use of this function
* must go through security review. In particular, it must be assured that it
* is only called from development code, as use in production code can lead to
* XSS vulnerabilities.
*/
export function newTrustedFunctionForDev(...args: string[]): Function {
if (typeof ngDevMode === 'undefined') {
throw new Error('newTrustedFunctionForDev should never be called in production');
}
if (!global.trustedTypes) {
// In environments that don't support Trusted Types, fall back to the most
// straightforward implementation:
return new Function(...args);
}
// Chrome currently does not support passing TrustedScript to the Function
// constructor. The following implements the workaround proposed on the page
// below, where the Chromium bug is also referenced:
// https://github.com/w3c/webappsec-trusted-types/wiki/Trusted-Types-for-function-constructor
const fnArgs = args.slice(0, -1).join(',');
const fnBody = args[args.length - 1];
const body = `(function anonymous(${fnArgs}
) { ${fnBody}
})`;
// Using eval directly confuses the compiler and prevents this module from
// being stripped out of JS binaries even if not used. The global['eval']
// indirection fixes that.
const fn = global['eval'](trustedScriptFromString(body)) as Function;
if (fn.bind === undefined) {
// Workaround for a browser bug that only exists in Chrome 83, where passing
// a TrustedScript to eval just returns the TrustedScript back without
// evaluating it. In that case, fall back to the most straightforward
// implementation:
return new Function(...args);
}
// To completely mimic the behavior of calling "new Function", two more
// things need to happen:
// 1. Stringifying the resulting function should return its source code
fn.toString = () => body;
// 2. When calling the resulting function, `this` should refer to `global`
return fn.bind(global);
// When Trusted Types support in Function constructors is widely available,
// the implementation of this function can be simplified to:
// return new Function(...args.map(a => trustedScriptFromString(a)));
}
| {
"end_byte": 5899,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/security/trusted_types.ts"
} |
angular/packages/core/src/util/security/trusted_types_bypass.ts_0_3553 | /**
* @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
*/
/**
* @fileoverview
* A module to facilitate use of a Trusted Types policy internally within
* Angular specifically for bypassSecurityTrust* and custom sanitizers. It
* lazily constructs the Trusted Types policy, providing helper utilities for
* promoting strings to Trusted Types. When Trusted Types are not available,
* strings are used as a fallback.
* @security All use of this module is security-sensitive and should go through
* security review.
*/
import {global} from '../global';
import {
TrustedHTML,
TrustedScript,
TrustedScriptURL,
TrustedTypePolicy,
TrustedTypePolicyFactory,
} from './trusted_type_defs';
/**
* The Trusted Types policy, or null if Trusted Types are not
* enabled/supported, or undefined if the policy has not been created yet.
*/
let policy: TrustedTypePolicy | null | undefined;
/**
* Returns the Trusted Types policy, or null if Trusted Types are not
* enabled/supported. The first call to this function will create the policy.
*/
function getPolicy(): TrustedTypePolicy | null {
if (policy === undefined) {
policy = null;
if (global.trustedTypes) {
try {
policy = (global.trustedTypes as TrustedTypePolicyFactory).createPolicy(
'angular#unsafe-bypass',
{
createHTML: (s: string) => s,
createScript: (s: string) => s,
createScriptURL: (s: string) => s,
},
);
} catch {
// trustedTypes.createPolicy throws if called with a name that is
// already registered, even in report-only mode. Until the API changes,
// catch the error not to break the applications functionally. In such
// cases, the code will fall back to using strings.
}
}
}
return policy;
}
/**
* Unsafely promote a string to a TrustedHTML, falling back to strings when
* Trusted Types are not available.
* @security This is a security-sensitive function; any use of this function
* must go through security review. In particular, it must be assured that it
* is only passed strings that come directly from custom sanitizers or the
* bypassSecurityTrust* functions.
*/
export function trustedHTMLFromStringBypass(html: string): TrustedHTML | string {
return getPolicy()?.createHTML(html) || html;
}
/**
* Unsafely promote a string to a TrustedScript, falling back to strings when
* Trusted Types are not available.
* @security This is a security-sensitive function; any use of this function
* must go through security review. In particular, it must be assured that it
* is only passed strings that come directly from custom sanitizers or the
* bypassSecurityTrust* functions.
*/
export function trustedScriptFromStringBypass(script: string): TrustedScript | string {
return getPolicy()?.createScript(script) || script;
}
/**
* Unsafely promote a string to a TrustedScriptURL, falling back to strings
* when Trusted Types are not available.
* @security This is a security-sensitive function; any use of this function
* must go through security review. In particular, it must be assured that it
* is only passed strings that come directly from custom sanitizers or the
* bypassSecurityTrust* functions.
*/
export function trustedScriptURLFromStringBypass(url: string): TrustedScriptURL | string {
return getPolicy()?.createScriptURL(url) || url;
}
| {
"end_byte": 3553,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/security/trusted_types_bypass.ts"
} |
angular/packages/core/src/util/security/trusted_type_defs.ts_0_1863 | /**
* @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
*/
/**
* @fileoverview
* While Angular only uses Trusted Types internally for the time being,
* references to Trusted Types could leak into our core.d.ts, which would force
* anyone compiling against @angular/core to provide the @types/trusted-types
* package in their compilation unit.
*
* Until https://github.com/microsoft/TypeScript/issues/30024 is resolved, we
* will keep Angular's public API surface free of references to Trusted Types.
* For internal and semi-private APIs that need to reference Trusted Types, the
* minimal type definitions for the Trusted Types API provided by this module
* should be used instead. They are marked as "declare" to prevent them from
* being renamed by compiler optimization.
*
* Adapted from
* https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/trusted-types/index.d.ts
* but restricted to the API surface used within Angular.
*/
export type TrustedHTML = string & {
__brand__: 'TrustedHTML';
};
export type TrustedScript = string & {
__brand__: 'TrustedScript';
};
export type TrustedScriptURL = string & {
__brand__: 'TrustedScriptURL';
};
export interface TrustedTypePolicyFactory {
createPolicy(
policyName: string,
policyOptions: {
createHTML?: (input: string) => string;
createScript?: (input: string) => string;
createScriptURL?: (input: string) => string;
},
): TrustedTypePolicy;
getAttributeType(tagName: string, attribute: string): string | null;
}
export interface TrustedTypePolicy {
createHTML(input: string): TrustedHTML;
createScript(input: string): TrustedScript;
createScriptURL(input: string): TrustedScriptURL;
}
| {
"end_byte": 1863,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/util/security/trusted_type_defs.ts"
} |
angular/packages/core/src/linker/destroy_ref.ts_0_2323 | /**
* @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 {EnvironmentInjector} from '../di';
import {LView} from '../render3/interfaces/view';
import {getLView} from '../render3/state';
import {removeLViewOnDestroy, storeLViewOnDestroy} from '../render3/util/view_utils';
/**
* `DestroyRef` lets you set callbacks to run for any cleanup or destruction behavior.
* The scope of this destruction depends on where `DestroyRef` is injected. If `DestroyRef`
* is injected in a component or directive, the callbacks run when that component or
* directive is destroyed. Otherwise the callbacks run when a corresponding injector is destroyed.
*
* @publicApi
*/
export abstract class DestroyRef {
// Here the `DestroyRef` acts primarily as a DI token. There are (currently) types of objects that
// can be returned from the injector when asking for this token:
// - `NodeInjectorDestroyRef` when retrieved from a node injector;
// - `EnvironmentInjector` when retrieved from an environment injector
/**
* Registers a destroy callback in a given lifecycle scope. Returns a cleanup function that can
* be invoked to unregister the callback.
*
* @usageNotes
* ### Example
* ```typescript
* const destroyRef = inject(DestroyRef);
*
* // register a destroy callback
* const unregisterFn = destroyRef.onDestroy(() => doSomethingOnDestroy());
*
* // stop the destroy callback from executing if needed
* unregisterFn();
* ```
*/
abstract onDestroy(callback: () => void): () => void;
/**
* @internal
* @nocollapse
*/
static __NG_ELEMENT_ID__: () => DestroyRef = injectDestroyRef;
/**
* @internal
* @nocollapse
*/
static __NG_ENV_ID__: (injector: EnvironmentInjector) => DestroyRef = (injector) => injector;
}
export class NodeInjectorDestroyRef extends DestroyRef {
constructor(readonly _lView: LView) {
super();
}
override onDestroy(callback: () => void): () => void {
storeLViewOnDestroy(this._lView, callback);
return () => removeLViewOnDestroy(this._lView, callback);
}
}
function injectDestroyRef(): DestroyRef {
return new NodeInjectorDestroyRef(getLView());
}
| {
"end_byte": 2323,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/destroy_ref.ts"
} |
angular/packages/core/src/linker/view_ref.ts_0_2739 | /**
* @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} from '../change_detection/change_detector_ref';
/**
* Represents an Angular view.
*
* @see [Change detection usage](/api/core/ChangeDetectorRef?tab=usage-notes)
*
* @publicApi
*/
export abstract class ViewRef extends ChangeDetectorRef {
/**
* Destroys this view and all of the data structures associated with it.
*/
abstract destroy(): void;
/**
* Reports whether this view has been destroyed.
* @returns True after the `destroy()` method has been called, false otherwise.
*/
abstract get destroyed(): boolean;
/**
* A lifecycle hook that provides additional developer-defined cleanup
* functionality for views.
* @param callback A handler function that cleans up developer-defined data
* associated with a view. Called when the `destroy()` method is invoked.
*/
abstract onDestroy(callback: Function): void;
}
/**
* Represents an Angular view in a view container.
* An embedded view can be referenced from a component
* other than the hosting component whose template defines it, or it can be defined
* independently by a `TemplateRef`.
*
* Properties of elements in a view can change, but the structure (number and order) of elements in
* a view cannot. Change the structure of elements by inserting, moving, or
* removing nested views in a view container.
*
* @see {@link ViewContainerRef}
*
* @usageNotes
*
* The following template breaks down into two separate `TemplateRef` instances,
* an outer one and an inner one.
*
* ```
* Count: {{items.length}}
* <ul>
* <li *ngFor="let item of items">{{item}}</li>
* </ul>
* ```
*
* This is the outer `TemplateRef`:
*
* ```
* Count: {{items.length}}
* <ul>
* <ng-template ngFor let-item [ngForOf]="items"></ng-template>
* </ul>
* ```
*
* This is the inner `TemplateRef`:
*
* ```
* <li>{{item}}</li>
* ```
*
* The outer and inner `TemplateRef` instances are assembled into views as follows:
*
* ```
* <!-- ViewRef: outer-0 -->
* Count: 2
* <ul>
* <ng-template view-container-ref></ng-template>
* <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
* <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
* </ul>
* <!-- /ViewRef: outer-0 -->
* ```
* @publicApi
*/
export abstract class EmbeddedViewRef<C> extends ViewRef {
/**
* The context for this view, inherited from the anchor element.
*/
abstract context: C;
/**
* The root nodes for this embedded view.
*/
abstract get rootNodes(): any[];
}
| {
"end_byte": 2739,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/view_ref.ts"
} |
angular/packages/core/src/linker/view_container_ref.ts_0_4260 | /**
* @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 '../di/injector';
import {EnvironmentInjector} from '../di/r3_injector';
import {validateMatchingNode} from '../hydration/error_handling';
import {CONTAINERS} from '../hydration/interfaces';
import {isInSkipHydrationBlock} from '../hydration/skip_hydration';
import {
getSegmentHead,
isDisconnectedNode,
markRNodeAsClaimedByHydration,
} from '../hydration/utils';
import {findMatchingDehydratedView, locateDehydratedViewsInContainer} from '../hydration/views';
import {isType, Type} from '../interface/type';
import {assertNodeInjector} from '../render3/assert';
import {ComponentFactory as R3ComponentFactory} from '../render3/component_ref';
import {getComponentDef} from '../render3/def_getters';
import {getParentInjectorLocation, NodeInjector} from '../render3/di';
import {addToEndOfViewTree, createLContainer} from '../render3/instructions/shared';
import {
CONTAINER_HEADER_OFFSET,
DEHYDRATED_VIEWS,
LContainer,
NATIVE,
VIEW_REFS,
} from '../render3/interfaces/container';
import {NodeInjectorOffset} from '../render3/interfaces/injector';
import {
TContainerNode,
TDirectiveHostNode,
TElementContainerNode,
TElementNode,
TNode,
TNodeType,
} from '../render3/interfaces/node';
import {RComment, RNode} from '../render3/interfaces/renderer_dom';
import {isLContainer} from '../render3/interfaces/type_checks';
import {
HEADER_OFFSET,
HYDRATION,
LView,
PARENT,
RENDERER,
T_HOST,
TVIEW,
} from '../render3/interfaces/view';
import {assertTNodeType} from '../render3/node_assert';
import {
destroyLView,
detachView,
nativeInsertBefore,
nativeNextSibling,
nativeParentNode,
} from '../render3/node_manipulation';
import {getCurrentTNode, getLView} from '../render3/state';
import {
getParentInjectorIndex,
getParentInjectorView,
hasParentInjector,
} from '../render3/util/injector_utils';
import {getNativeByTNode, unwrapRNode, viewAttachedToContainer} from '../render3/util/view_utils';
import {addLViewToLContainer, shouldAddViewToDom} from '../render3/view_manipulation';
import {ViewRef as R3ViewRef} from '../render3/view_ref';
import {addToArray, removeFromArray} from '../util/array_utils';
import {
assertDefined,
assertEqual,
assertGreaterThan,
assertLessThan,
throwError,
} from '../util/assert';
import {ComponentFactory, ComponentRef} from './component_factory';
import {createElementRef, ElementRef} from './element_ref';
import {NgModuleRef} from './ng_module_factory';
import {TemplateRef} from './template_ref';
import {EmbeddedViewRef, ViewRef} from './view_ref';
/**
* Represents a container where one or more views can be attached to a component.
*
* Can contain *host views* (created by instantiating a
* component with the `createComponent()` method), and *embedded views*
* (created by instantiating a `TemplateRef` with the `createEmbeddedView()` method).
*
* A view container instance can contain other view containers,
* creating a view hierarchy.
*
* @usageNotes
*
* The example below demonstrates how the `createComponent` function can be used
* to create an instance of a ComponentRef dynamically and attach it to an ApplicationRef,
* so that it gets included into change detection cycles.
*
* Note: the example uses standalone components, but the function can also be used for
* non-standalone components (declared in an NgModule) as well.
*
* ```typescript
* @Component({
* standalone: true,
* selector: 'dynamic',
* template: `<span>This is a content of a dynamic component.</span>`,
* })
* class DynamicComponent {
* vcr = inject(ViewContainerRef);
* }
*
* @Component({
* standalone: true,
* selector: 'app',
* template: `<main>Hi! This is the main content.</main>`,
* })
* class AppComponent {
* vcr = inject(ViewContainerRef);
*
* ngAfterViewInit() {
* const compRef = this.vcr.createComponent(DynamicComponent);
* compRef.changeDetectorRef.detectChanges();
* }
* }
* ```
*
* @see {@link ComponentRef}
* @see {@link EmbeddedViewRef}
*
* @publicApi
*/ | {
"end_byte": 4260,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/view_container_ref.ts"
} |
angular/packages/core/src/linker/view_container_ref.ts_4261_12079 | export abstract class ViewContainerRef {
/**
* Anchor element that specifies the location of this container in the containing view.
* Each view container can have only one anchor element, and each anchor element
* can have only a single view container.
*
* Root elements of views attached to this container become siblings of the anchor element in
* the rendered view.
*
* Access the `ViewContainerRef` of an element by placing a `Directive` injected
* with `ViewContainerRef` on the element, or use a `ViewChild` query.
*
* <!-- TODO: rename to anchorElement -->
*/
abstract get element(): ElementRef;
/**
* The dependency injector for this view container.
*/
abstract get injector(): Injector;
/** @deprecated No replacement */
abstract get parentInjector(): Injector;
/**
* Destroys all views in this container.
*/
abstract clear(): void;
/**
* Retrieves a view from this container.
* @param index The 0-based index of the view to retrieve.
* @returns The `ViewRef` instance, or null if the index is out of range.
*/
abstract get(index: number): ViewRef | null;
/**
* Reports how many views are currently attached to this container.
* @returns The number of views.
*/
abstract get length(): number;
/**
* Instantiates an embedded view and inserts it
* into this container.
* @param templateRef The HTML template that defines the view.
* @param context The data-binding context of the embedded view, as declared
* in the `<ng-template>` usage.
* @param options Extra configuration for the created view. Includes:
* * index: The 0-based index at which to insert the new view into this container.
* If not specified, appends the new view as the last entry.
* * injector: Injector to be used within the embedded view.
*
* @returns The `ViewRef` instance for the newly created view.
*/
abstract createEmbeddedView<C>(
templateRef: TemplateRef<C>,
context?: C,
options?: {
index?: number;
injector?: Injector;
},
): EmbeddedViewRef<C>;
/**
* Instantiates an embedded view and inserts it
* into this container.
* @param templateRef The HTML template that defines the view.
* @param context The data-binding context of the embedded view, as declared
* in the `<ng-template>` usage.
* @param index The 0-based index at which to insert the new view into this container.
* If not specified, appends the new view as the last entry.
*
* @returns The `ViewRef` instance for the newly created view.
*/
abstract createEmbeddedView<C>(
templateRef: TemplateRef<C>,
context?: C,
index?: number,
): EmbeddedViewRef<C>;
/**
* Instantiates a single component and inserts its host view into this container.
*
* @param componentType Component Type to use.
* @param options An object that contains extra parameters:
* * index: the index at which to insert the new component's host view into this container.
* If not specified, appends the new view as the last entry.
* * injector: the injector to use as the parent for the new component.
* * ngModuleRef: an NgModuleRef of the component's NgModule, you should almost always provide
* this to ensure that all expected providers are available for the component
* instantiation.
* * environmentInjector: an EnvironmentInjector which will provide the component's environment.
* you should almost always provide this to ensure that all expected providers
* are available for the component instantiation. This option is intended to
* replace the `ngModuleRef` parameter.
* * projectableNodes: list of DOM nodes that should be projected through
* [`<ng-content>`](api/core/ng-content) of the new component instance.
*
* @returns The new `ComponentRef` which contains the component instance and the host view.
*/
abstract createComponent<C>(
componentType: Type<C>,
options?: {
index?: number;
injector?: Injector;
ngModuleRef?: NgModuleRef<unknown>;
environmentInjector?: EnvironmentInjector | NgModuleRef<unknown>;
projectableNodes?: Node[][];
},
): ComponentRef<C>;
/**
* Instantiates a single component and inserts its host view into this container.
*
* @param componentFactory Component factory to use.
* @param index The index at which to insert the new component's host view into this container.
* If not specified, appends the new view as the last entry.
* @param injector The injector to use as the parent for the new component.
* @param projectableNodes List of DOM nodes that should be projected through
* [`<ng-content>`](api/core/ng-content) of the new component instance.
* @param ngModuleRef An instance of the NgModuleRef that represent an NgModule.
* This information is used to retrieve corresponding NgModule injector.
*
* @returns The new `ComponentRef` which contains the component instance and the host view.
*
* @deprecated Angular no longer requires component factories to dynamically create components.
* Use different signature of the `createComponent` method, which allows passing
* Component class directly.
*/
abstract createComponent<C>(
componentFactory: ComponentFactory<C>,
index?: number,
injector?: Injector,
projectableNodes?: any[][],
environmentInjector?: EnvironmentInjector | NgModuleRef<any>,
): ComponentRef<C>;
/**
* Inserts a view into this container.
* @param viewRef The view to insert.
* @param index The 0-based index at which to insert the view.
* If not specified, appends the new view as the last entry.
* @returns The inserted `ViewRef` instance.
*
*/
abstract insert(viewRef: ViewRef, index?: number): ViewRef;
/**
* Moves a view to a new location in this container.
* @param viewRef The view to move.
* @param index The 0-based index of the new location.
* @returns The moved `ViewRef` instance.
*/
abstract move(viewRef: ViewRef, currentIndex: number): ViewRef;
/**
* Returns the index of a view within the current container.
* @param viewRef The view to query.
* @returns The 0-based index of the view's position in this container,
* or `-1` if this container doesn't contain the view.
*/
abstract indexOf(viewRef: ViewRef): number;
/**
* Destroys a view attached to this container
* @param index The 0-based index of the view to destroy.
* If not specified, the last view in the container is removed.
*/
abstract remove(index?: number): void;
/**
* Detaches a view from this container without destroying it.
* Use along with `insert()` to move a view within the current container.
* @param index The 0-based index of the view to detach.
* If not specified, the last view in the container is detached.
*/
abstract detach(index?: number): ViewRef | null;
/**
* @internal
* @nocollapse
*/
static __NG_ELEMENT_ID__: () => ViewContainerRef = injectViewContainerRef;
}
/**
* Creates a ViewContainerRef and stores it on the injector. Or, if the ViewContainerRef
* already exists, retrieves the existing ViewContainerRef.
*
* @returns The ViewContainerRef instance to use
*/
export function injectViewContainerRef(): ViewContainerRef {
const previousTNode = getCurrentTNode() as TElementNode | TElementContainerNode | TContainerNode;
return createContainerRef(previousTNode, getLView());
}
const VE_ViewContainerRef = ViewContainerRef;
// TODO(alxhub): cleaning up this indirection triggers a subtle bug in Closure in g3. Once the fix
// for that lands, this can be cleaned up. | {
"end_byte": 12079,
"start_byte": 4261,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/view_container_ref.ts"
} |
angular/packages/core/src/linker/view_container_ref.ts_12080_15508 | const R3ViewContainerRef = class ViewContainerRef extends VE_ViewContainerRef {
constructor(
private _lContainer: LContainer,
private _hostTNode: TElementNode | TContainerNode | TElementContainerNode,
private _hostLView: LView,
) {
super();
}
override get element(): ElementRef {
return createElementRef(this._hostTNode, this._hostLView);
}
override get injector(): Injector {
return new NodeInjector(this._hostTNode, this._hostLView);
}
/** @deprecated No replacement */
override get parentInjector(): Injector {
const parentLocation = getParentInjectorLocation(this._hostTNode, this._hostLView);
if (hasParentInjector(parentLocation)) {
const parentView = getParentInjectorView(parentLocation, this._hostLView);
const injectorIndex = getParentInjectorIndex(parentLocation);
ngDevMode && assertNodeInjector(parentView, injectorIndex);
const parentTNode = parentView[TVIEW].data[
injectorIndex + NodeInjectorOffset.TNODE
] as TElementNode;
return new NodeInjector(parentTNode, parentView);
} else {
return new NodeInjector(null, this._hostLView);
}
}
override clear(): void {
while (this.length > 0) {
this.remove(this.length - 1);
}
}
override get(index: number): ViewRef | null {
const viewRefs = getViewRefs(this._lContainer);
return (viewRefs !== null && viewRefs[index]) || null;
}
override get length(): number {
return this._lContainer.length - CONTAINER_HEADER_OFFSET;
}
override createEmbeddedView<C>(
templateRef: TemplateRef<C>,
context?: C,
options?: {
index?: number;
injector?: Injector;
},
): EmbeddedViewRef<C>;
override createEmbeddedView<C>(
templateRef: TemplateRef<C>,
context?: C,
index?: number,
): EmbeddedViewRef<C>;
override createEmbeddedView<C>(
templateRef: TemplateRef<C>,
context?: C,
indexOrOptions?:
| number
| {
index?: number;
injector?: Injector;
},
): EmbeddedViewRef<C> {
let index: number | undefined;
let injector: Injector | undefined;
if (typeof indexOrOptions === 'number') {
index = indexOrOptions;
} else if (indexOrOptions != null) {
index = indexOrOptions.index;
injector = indexOrOptions.injector;
}
const dehydratedView = findMatchingDehydratedView(this._lContainer, templateRef.ssrId);
const viewRef = templateRef.createEmbeddedViewImpl(
context || <any>{},
injector,
dehydratedView,
);
this.insertImpl(viewRef, index, shouldAddViewToDom(this._hostTNode, dehydratedView));
return viewRef;
}
override createComponent<C>(
componentType: Type<C>,
options?: {
index?: number;
injector?: Injector;
projectableNodes?: Node[][];
ngModuleRef?: NgModuleRef<unknown>;
},
): ComponentRef<C>;
/**
* @deprecated Angular no longer requires component factories to dynamically create components.
* Use different signature of the `createComponent` method, which allows passing
* Component class directly.
*/
override createComponent<C>(
componentFactory: ComponentFactory<C>,
index?: number | undefined,
injector?: Injector | undefined,
projectableNodes?: any[][] | undefined,
environmentInjector?: EnvironmentInjector | NgModuleRef<any> | undefined,
): ComponentRef<C>; | {
"end_byte": 15508,
"start_byte": 12080,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/view_container_ref.ts"
} |
angular/packages/core/src/linker/view_container_ref.ts_15511_24516 | override createComponent<C>(
componentFactoryOrType: ComponentFactory<C> | Type<C>,
indexOrOptions?:
| number
| undefined
| {
index?: number;
injector?: Injector;
ngModuleRef?: NgModuleRef<unknown>;
environmentInjector?: EnvironmentInjector | NgModuleRef<unknown>;
projectableNodes?: Node[][];
},
injector?: Injector | undefined,
projectableNodes?: any[][] | undefined,
environmentInjector?: EnvironmentInjector | NgModuleRef<any> | undefined,
): ComponentRef<C> {
const isComponentFactory = componentFactoryOrType && !isType(componentFactoryOrType);
let index: number | undefined;
// This function supports 2 signatures and we need to handle options correctly for both:
// 1. When first argument is a Component type. This signature also requires extra
// options to be provided as object (more ergonomic option).
// 2. First argument is a Component factory. In this case extra options are represented as
// positional arguments. This signature is less ergonomic and will be deprecated.
if (isComponentFactory) {
if (ngDevMode) {
assertEqual(
typeof indexOrOptions !== 'object',
true,
'It looks like Component factory was provided as the first argument ' +
'and an options object as the second argument. This combination of arguments ' +
'is incompatible. You can either change the first argument to provide Component ' +
'type or change the second argument to be a number (representing an index at ' +
"which to insert the new component's host view into this container)",
);
}
index = indexOrOptions as number | undefined;
} else {
if (ngDevMode) {
assertDefined(
getComponentDef(componentFactoryOrType),
`Provided Component class doesn't contain Component definition. ` +
`Please check whether provided class has @Component decorator.`,
);
assertEqual(
typeof indexOrOptions !== 'number',
true,
'It looks like Component type was provided as the first argument ' +
"and a number (representing an index at which to insert the new component's " +
'host view into this container as the second argument. This combination of arguments ' +
'is incompatible. Please use an object as the second argument instead.',
);
}
const options = (indexOrOptions || {}) as {
index?: number;
injector?: Injector;
ngModuleRef?: NgModuleRef<unknown>;
environmentInjector?: EnvironmentInjector | NgModuleRef<unknown>;
projectableNodes?: Node[][];
};
if (ngDevMode && options.environmentInjector && options.ngModuleRef) {
throwError(
`Cannot pass both environmentInjector and ngModuleRef options to createComponent().`,
);
}
index = options.index;
injector = options.injector;
projectableNodes = options.projectableNodes;
environmentInjector = options.environmentInjector || options.ngModuleRef;
}
const componentFactory: ComponentFactory<C> = isComponentFactory
? (componentFactoryOrType as ComponentFactory<C>)
: new R3ComponentFactory(getComponentDef(componentFactoryOrType)!);
const contextInjector = injector || this.parentInjector;
// If an `NgModuleRef` is not provided explicitly, try retrieving it from the DI tree.
if (!environmentInjector && (componentFactory as any).ngModule == null) {
// For the `ComponentFactory` case, entering this logic is very unlikely, since we expect that
// an instance of a `ComponentFactory`, resolved via `ComponentFactoryResolver` would have an
// `ngModule` field. This is possible in some test scenarios and potentially in some JIT-based
// use-cases. For the `ComponentFactory` case we preserve backwards-compatibility and try
// using a provided injector first, then fall back to the parent injector of this
// `ViewContainerRef` instance.
//
// For the factory-less case, it's critical to establish a connection with the module
// injector tree (by retrieving an instance of an `NgModuleRef` and accessing its injector),
// so that a component can use DI tokens provided in MgModules. For this reason, we can not
// rely on the provided injector, since it might be detached from the DI tree (for example, if
// it was created via `Injector.create` without specifying a parent injector, or if an
// injector is retrieved from an `NgModuleRef` created via `createNgModule` using an
// NgModule outside of a module tree). Instead, we always use `ViewContainerRef`'s parent
// injector, which is normally connected to the DI tree, which includes module injector
// subtree.
const _injector = isComponentFactory ? contextInjector : this.parentInjector;
// DO NOT REFACTOR. The code here used to have a `injector.get(NgModuleRef, null) ||
// undefined` expression which seems to cause internal google apps to fail. This is documented
// in the following internal bug issue: go/b/142967802
const result = _injector.get(EnvironmentInjector, null);
if (result) {
environmentInjector = result;
}
}
const componentDef = getComponentDef(componentFactory.componentType ?? {});
const dehydratedView = findMatchingDehydratedView(this._lContainer, componentDef?.id ?? null);
const rNode = dehydratedView?.firstChild ?? null;
const componentRef = componentFactory.create(
contextInjector,
projectableNodes,
rNode,
environmentInjector,
);
this.insertImpl(
componentRef.hostView,
index,
shouldAddViewToDom(this._hostTNode, dehydratedView),
);
return componentRef;
}
override insert(viewRef: ViewRef, index?: number): ViewRef {
return this.insertImpl(viewRef, index, true);
}
private insertImpl(viewRef: ViewRef, index?: number, addToDOM?: boolean): ViewRef {
const lView = (viewRef as R3ViewRef<any>)._lView!;
if (ngDevMode && viewRef.destroyed) {
throw new Error('Cannot insert a destroyed View in a ViewContainer!');
}
if (viewAttachedToContainer(lView)) {
// If view is already attached, detach it first so we clean up references appropriately.
const prevIdx = this.indexOf(viewRef);
// A view might be attached either to this or a different container. The `prevIdx` for
// those cases will be:
// equal to -1 for views attached to this ViewContainerRef
// >= 0 for views attached to a different ViewContainerRef
if (prevIdx !== -1) {
this.detach(prevIdx);
} else {
const prevLContainer = lView[PARENT] as LContainer;
ngDevMode &&
assertEqual(
isLContainer(prevLContainer),
true,
'An attached view should have its PARENT point to a container.',
);
// We need to re-create a R3ViewContainerRef instance since those are not stored on
// LView (nor anywhere else).
const prevVCRef = new R3ViewContainerRef(
prevLContainer,
prevLContainer[T_HOST] as TDirectiveHostNode,
prevLContainer[PARENT],
);
prevVCRef.detach(prevVCRef.indexOf(viewRef));
}
}
// Logical operation of adding `LView` to `LContainer`
const adjustedIdx = this._adjustIndex(index);
const lContainer = this._lContainer;
addLViewToLContainer(lContainer, lView, adjustedIdx, addToDOM);
(viewRef as R3ViewRef<any>).attachToViewContainerRef();
addToArray(getOrCreateViewRefs(lContainer), adjustedIdx, viewRef);
return viewRef;
}
override move(viewRef: ViewRef, newIndex: number): ViewRef {
if (ngDevMode && viewRef.destroyed) {
throw new Error('Cannot move a destroyed View in a ViewContainer!');
}
return this.insert(viewRef, newIndex);
}
override indexOf(viewRef: ViewRef): number {
const viewRefsArr = getViewRefs(this._lContainer);
return viewRefsArr !== null ? viewRefsArr.indexOf(viewRef) : -1;
}
override remove(index?: number): void {
const adjustedIdx = this._adjustIndex(index, -1);
const detachedView = detachView(this._lContainer, adjustedIdx);
if (detachedView) {
// Before destroying the view, remove it from the container's array of `ViewRef`s.
// This ensures the view container length is updated before calling
// `destroyLView`, which could recursively call view container methods that
// rely on an accurate container length.
// (e.g. a method on this view container being called by a child directive's OnDestroy
// lifecycle hook)
removeFromArray(getOrCreateViewRefs(this._lContainer), adjustedIdx);
destroyLView(detachedView[TVIEW], detachedView);
}
} | {
"end_byte": 24516,
"start_byte": 15511,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/view_container_ref.ts"
} |
angular/packages/core/src/linker/view_container_ref.ts_24520_32227 | override detach(index?: number): ViewRef | null {
const adjustedIdx = this._adjustIndex(index, -1);
const view = detachView(this._lContainer, adjustedIdx);
const wasDetached =
view && removeFromArray(getOrCreateViewRefs(this._lContainer), adjustedIdx) != null;
return wasDetached ? new R3ViewRef(view!) : null;
}
private _adjustIndex(index?: number, shift: number = 0) {
if (index == null) {
return this.length + shift;
}
if (ngDevMode) {
assertGreaterThan(index, -1, `ViewRef index must be positive, got ${index}`);
// +1 because it's legal to insert at the end.
assertLessThan(index, this.length + 1 + shift, 'index');
}
return index;
}
};
function getViewRefs(lContainer: LContainer): ViewRef[] | null {
return lContainer[VIEW_REFS] as ViewRef[];
}
function getOrCreateViewRefs(lContainer: LContainer): ViewRef[] {
return (lContainer[VIEW_REFS] || (lContainer[VIEW_REFS] = [])) as ViewRef[];
}
/**
* Creates a ViewContainerRef and stores it on the injector.
*
* @param hostTNode The node that is requesting a ViewContainerRef
* @param hostLView The view to which the node belongs
* @returns The ViewContainerRef instance to use
*/
export function createContainerRef(
hostTNode: TElementNode | TContainerNode | TElementContainerNode,
hostLView: LView,
): ViewContainerRef {
ngDevMode && assertTNodeType(hostTNode, TNodeType.AnyContainer | TNodeType.AnyRNode);
let lContainer: LContainer;
const slotValue = hostLView[hostTNode.index];
if (isLContainer(slotValue)) {
// If the host is a container, we don't need to create a new LContainer
lContainer = slotValue;
} else {
// An LContainer anchor can not be `null`, but we set it here temporarily
// and update to the actual value later in this function (see
// `_locateOrCreateAnchorNode`).
lContainer = createLContainer(slotValue, hostLView, null!, hostTNode);
hostLView[hostTNode.index] = lContainer;
addToEndOfViewTree(hostLView, lContainer);
}
_locateOrCreateAnchorNode(lContainer, hostLView, hostTNode, slotValue);
return new R3ViewContainerRef(lContainer, hostTNode, hostLView);
}
/**
* Creates and inserts a comment node that acts as an anchor for a view container.
*
* If the host is a regular element, we have to insert a comment node manually which will
* be used as an anchor when inserting elements. In this specific case we use low-level DOM
* manipulation to insert it.
*/
function insertAnchorNode(hostLView: LView, hostTNode: TNode): RComment {
const renderer = hostLView[RENDERER];
ngDevMode && ngDevMode.rendererCreateComment++;
const commentNode = renderer.createComment(ngDevMode ? 'container' : '');
const hostNative = getNativeByTNode(hostTNode, hostLView)!;
const parentOfHostNative = nativeParentNode(renderer, hostNative);
nativeInsertBefore(
renderer,
parentOfHostNative!,
commentNode,
nativeNextSibling(renderer, hostNative),
false,
);
return commentNode;
}
let _locateOrCreateAnchorNode = createAnchorNode;
let _populateDehydratedViewsInLContainer: typeof populateDehydratedViewsInLContainerImpl = () =>
false; // noop by default
/**
* Looks up dehydrated views that belong to a given LContainer and populates
* this information into the `LContainer[DEHYDRATED_VIEWS]` slot. When running
* in client-only mode, this function is a noop.
*
* @param lContainer LContainer that should be populated.
* @param tNode Corresponding TNode.
* @param hostLView LView that hosts LContainer.
* @returns a boolean flag that indicates whether a populating operation
* was successful. The operation might be unsuccessful in case is has completed
* previously, we are rendering in client-only mode or this content is located
* in a skip hydration section.
*/
export function populateDehydratedViewsInLContainer(
lContainer: LContainer,
tNode: TNode,
hostLView: LView,
): boolean {
return _populateDehydratedViewsInLContainer(lContainer, tNode, hostLView);
}
/**
* Regular creation mode: an anchor is created and
* assigned to the `lContainer[NATIVE]` slot.
*/
function createAnchorNode(
lContainer: LContainer,
hostLView: LView,
hostTNode: TNode,
slotValue: any,
) {
// We already have a native element (anchor) set, return.
if (lContainer[NATIVE]) return;
let commentNode: RComment;
// If the host is an element container, the native host element is guaranteed to be a
// comment and we can reuse that comment as anchor element for the new LContainer.
// The comment node in question is already part of the DOM structure so we don't need to append
// it again.
if (hostTNode.type & TNodeType.ElementContainer) {
commentNode = unwrapRNode(slotValue) as RComment;
} else {
commentNode = insertAnchorNode(hostLView, hostTNode);
}
lContainer[NATIVE] = commentNode;
}
/**
* Hydration logic that looks up all dehydrated views in this container
* and puts them into `lContainer[DEHYDRATED_VIEWS]` slot.
*
* @returns a boolean flag that indicates whether a populating operation
* was successful. The operation might be unsuccessful in case is has completed
* previously, we are rendering in client-only mode or this content is located
* in a skip hydration section.
*/
function populateDehydratedViewsInLContainerImpl(
lContainer: LContainer,
tNode: TNode,
hostLView: LView,
): boolean {
// We already have a native element (anchor) set and the process
// of finding dehydrated views happened (so the `lContainer[DEHYDRATED_VIEWS]`
// is not null), exit early.
if (lContainer[NATIVE] && lContainer[DEHYDRATED_VIEWS]) {
return true;
}
const hydrationInfo = hostLView[HYDRATION];
const noOffsetIndex = tNode.index - HEADER_OFFSET;
const isNodeCreationMode =
!hydrationInfo ||
isInSkipHydrationBlock(tNode) ||
isDisconnectedNode(hydrationInfo, noOffsetIndex);
// Regular creation mode.
if (isNodeCreationMode) {
return false;
}
// Hydration mode, looking up an anchor node and dehydrated views in DOM.
const currentRNode: RNode | null = getSegmentHead(hydrationInfo, noOffsetIndex);
const serializedViews = hydrationInfo.data[CONTAINERS]?.[noOffsetIndex];
ngDevMode &&
assertDefined(
serializedViews,
'Unexpected state: no hydration info available for a given TNode, ' +
'which represents a view container.',
);
const [commentNode, dehydratedViews] = locateDehydratedViewsInContainer(
currentRNode!,
serializedViews!,
);
if (ngDevMode) {
validateMatchingNode(commentNode, Node.COMMENT_NODE, null, hostLView, tNode, true);
// Do not throw in case this node is already claimed (thus `false` as a second
// argument). If this container is created based on an `<ng-template>`, the comment
// node would be already claimed from the `template` instruction. If an element acts
// as an anchor (e.g. <div #vcRef>), a separate comment node would be created/located,
// so we need to claim it here.
markRNodeAsClaimedByHydration(commentNode, false);
}
lContainer[NATIVE] = commentNode as RComment;
lContainer[DEHYDRATED_VIEWS] = dehydratedViews;
return true;
}
function locateOrCreateAnchorNode(
lContainer: LContainer,
hostLView: LView,
hostTNode: TNode,
slotValue: any,
): void {
if (!_populateDehydratedViewsInLContainer(lContainer, hostTNode, hostLView)) {
// Populating dehydrated views operation returned `false`, which indicates
// that the logic was running in client-only mode, this an anchor comment
// node should be created for this container.
createAnchorNode(lContainer, hostLView, hostTNode, slotValue);
}
} | {
"end_byte": 32227,
"start_byte": 24520,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/view_container_ref.ts"
} |
angular/packages/core/src/linker/view_container_ref.ts_32229_32425 | export function enableLocateOrCreateContainerRefImpl() {
_locateOrCreateAnchorNode = locateOrCreateAnchorNode;
_populateDehydratedViewsInLContainer = populateDehydratedViewsInLContainerImpl;
} | {
"end_byte": 32425,
"start_byte": 32229,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/view_container_ref.ts"
} |
angular/packages/core/src/linker/component_factory_resolver.ts_0_1618 | /**
* @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 {Type} from '../interface/type';
import {stringify} from '../util/stringify';
import {ComponentFactory} from './component_factory';
class _NullComponentFactoryResolver implements ComponentFactoryResolver {
resolveComponentFactory<T>(component: {new (...args: any[]): T}): ComponentFactory<T> {
throw Error(`No component factory found for ${stringify(component)}.`);
}
}
/**
* A simple registry that maps `Components` to generated `ComponentFactory` classes
* that can be used to create instances of components.
* Use to obtain the factory for a given component type,
* then use the factory's `create()` method to create a component of that type.
*
* Note: since v13, dynamic component creation via
* [`ViewContainerRef.createComponent`](api/core/ViewContainerRef#createComponent)
* does **not** require resolving component factory: component class can be used directly.
*
* @publicApi
*
* @deprecated Angular no longer requires Component factories. Please use other APIs where
* Component class can be used directly.
*/
export abstract class ComponentFactoryResolver {
static NULL: ComponentFactoryResolver = /* @__PURE__ */ new _NullComponentFactoryResolver();
/**
* Retrieves the factory object that creates a component of the given type.
* @param component The component type.
*/
abstract resolveComponentFactory<T>(component: Type<T>): ComponentFactory<T>;
}
| {
"end_byte": 1618,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/component_factory_resolver.ts"
} |
angular/packages/core/src/linker/ng_module_registration.ts_0_2100 | /**
* @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 {Type} from '../interface/type';
import {NgModuleType} from '../metadata/ng_module_def';
import {stringify} from '../util/stringify';
/**
* Map of module-id to the corresponding NgModule.
*/
const modules = new Map<string, NgModuleType>();
/**
* Whether to check for duplicate NgModule registrations.
*
* This can be disabled for testing.
*/
let checkForDuplicateNgModules = true;
function assertSameOrNotExisting(id: string, type: Type<any> | null, incoming: Type<any>): void {
if (type && type !== incoming && checkForDuplicateNgModules) {
throw new Error(
`Duplicate module registered for ${id} - ${stringify(type)} vs ${stringify(type.name)}`,
);
}
}
/**
* Adds the given NgModule type to Angular's NgModule registry.
*
* This is generated as a side-effect of NgModule compilation. Note that the `id` is passed in
* explicitly and not read from the NgModule definition. This is for two reasons: it avoids a
* megamorphic read, and in JIT there's a chicken-and-egg problem where the NgModule may not be
* fully resolved when it's registered.
*
* @codeGenApi
*/
export function registerNgModuleType(ngModuleType: NgModuleType, id: string): void {
const existing = modules.get(id) || null;
assertSameOrNotExisting(id, existing, ngModuleType);
modules.set(id, ngModuleType);
}
export function clearModulesForTest(): void {
modules.clear();
}
export function getRegisteredNgModuleType(id: string): NgModuleType | undefined {
return modules.get(id);
}
/**
* Control whether the NgModule registration system enforces that each NgModule type registered has
* a unique id.
*
* This is useful for testing as the NgModule registry cannot be properly reset between tests with
* Angular's current API.
*/
export function setAllowDuplicateNgModuleIdsForTest(allowDuplicates: boolean): void {
checkForDuplicateNgModules = !allowDuplicates;
}
| {
"end_byte": 2100,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/ng_module_registration.ts"
} |
angular/packages/core/src/linker/ng_module_factory.ts_0_2479 | /**
* @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 '../di/injector';
import {EnvironmentInjector, R3Injector} from '../di/r3_injector';
import {Type} from '../interface/type';
import {ComponentFactoryResolver} from './component_factory_resolver';
/**
* Represents an instance of an `NgModule` created by an `NgModuleFactory`.
* Provides access to the `NgModule` instance and related objects.
*
* @publicApi
*/
export abstract class NgModuleRef<T> {
/**
* The injector that contains all of the providers of the `NgModule`.
*/
abstract get injector(): EnvironmentInjector;
/**
* The resolver that can retrieve component factories in a context of this module.
*
* Note: since v13, dynamic component creation via
* [`ViewContainerRef.createComponent`](api/core/ViewContainerRef#createComponent)
* does **not** require resolving component factory: component class can be used directly.
*
* @deprecated Angular no longer requires Component factories. Please use other APIs where
* Component class can be used directly.
*/
abstract get componentFactoryResolver(): ComponentFactoryResolver;
/**
* The `NgModule` instance.
*/
abstract get instance(): T;
/**
* Destroys the module instance and all of the data structures associated with it.
*/
abstract destroy(): void;
/**
* Registers a callback to be executed when the module is destroyed.
*/
abstract onDestroy(callback: () => void): void;
}
export interface InternalNgModuleRef<T> extends NgModuleRef<T> {
// Note: we are using the prefix _ as NgModuleData is an NgModuleRef and therefore directly
// exposed to the user.
_bootstrapComponents: Type<any>[];
resolveInjectorInitializers(): void;
}
/**
* @publicApi
*
* @deprecated
* This class was mostly used as a part of ViewEngine-based JIT API and is no longer needed in Ivy
* JIT mode. Angular provides APIs that accept NgModule classes directly (such as
* [PlatformRef.bootstrapModule](api/core/PlatformRef#bootstrapModule) and
* [createNgModule](api/core/createNgModule)), consider switching to those APIs instead of
* using factory-based ones.
*/
export abstract class NgModuleFactory<T> {
abstract get moduleType(): Type<T>;
abstract create(parentInjector: Injector | null): NgModuleRef<T>;
}
| {
"end_byte": 2479,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/ng_module_factory.ts"
} |
angular/packages/core/src/linker/ng_module_factory_loader.ts_0_1513 | /**
* @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 {Type} from '../interface/type';
import {NgModuleFactory as R3NgModuleFactory} from '../render3/ng_module_ref';
import {NgModuleFactory} from './ng_module_factory';
import {getRegisteredNgModuleType} from './ng_module_registration';
/**
* Returns the NgModuleFactory with the given id (specified using [@NgModule.id
* field](api/core/NgModule#id)), if it exists and has been loaded. Factories for NgModules that do
* not specify an `id` cannot be retrieved. Throws if an NgModule cannot be found.
* @publicApi
* @deprecated Use `getNgModuleById` instead.
*/
export function getModuleFactory(id: string): NgModuleFactory<any> {
const type = getRegisteredNgModuleType(id);
if (!type) throw noModuleError(id);
return new R3NgModuleFactory(type);
}
/**
* Returns the NgModule class with the given id (specified using [@NgModule.id
* field](api/core/NgModule#id)), if it exists and has been loaded. Classes for NgModules that do
* not specify an `id` cannot be retrieved. Throws if an NgModule cannot be found.
* @publicApi
*/
export function getNgModuleById<T>(id: string): Type<T> {
const type = getRegisteredNgModuleType(id);
if (!type) throw noModuleError(id);
return type;
}
function noModuleError(id: string): Error {
return new Error(`No module with ID ${id} loaded`);
}
| {
"end_byte": 1513,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/ng_module_factory_loader.ts"
} |
angular/packages/core/src/linker/element_ref.ts_0_2656 | /**
* @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 {TNode} from '../render3/interfaces/node';
import {RElement} from '../render3/interfaces/renderer_dom';
import {LView} from '../render3/interfaces/view';
import {getCurrentTNode, getLView} from '../render3/state';
import {getNativeByTNode} from '../render3/util/view_utils';
/**
* Creates an ElementRef from the most recent node.
*
* @returns The ElementRef instance to use
*/
export function injectElementRef(): ElementRef {
return createElementRef(getCurrentTNode()!, getLView());
}
/**
* Creates an ElementRef given a node.
*
* @param tNode The node for which you'd like an ElementRef
* @param lView The view to which the node belongs
* @returns The ElementRef instance to use
*/
export function createElementRef(tNode: TNode, lView: LView): ElementRef {
return new ElementRef(getNativeByTNode(tNode, lView) as RElement);
}
/**
* A wrapper around a native element inside of a View.
*
* An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM
* element.
*
* @security Permitting direct access to the DOM can make your application more vulnerable to
* XSS attacks. Carefully review any use of `ElementRef` in your code. For more detail, see the
* [Security Guide](https://g.co/ng/security).
*
* @publicApi
*/
// Note: We don't expose things like `Injector`, `ViewContainer`, ... here,
// i.e. users have to ask for what they need. With that, we can build better analysis tools
// and could do better codegen in the future.
export class ElementRef<T = any> {
/**
* <div class="callout is-critical">
* <header>Use with caution</header>
* <p>
* Use this API as the last resort when direct access to DOM is needed. Use templating and
* data-binding provided by Angular instead. Alternatively you can take a look at
* {@link Renderer2} which provides an API that can be safely used.
* </p>
* </div>
*/
public nativeElement: T;
constructor(nativeElement: T) {
this.nativeElement = nativeElement;
}
/**
* @internal
* @nocollapse
*/
static __NG_ELEMENT_ID__: () => ElementRef = injectElementRef;
}
/**
* Unwraps `ElementRef` and return the `nativeElement`.
*
* @param value value to unwrap
* @returns `nativeElement` if `ElementRef` otherwise returns value as is.
*/
export function unwrapElementRef<T, R>(value: T | ElementRef<R>): T | R {
return value instanceof ElementRef ? value.nativeElement : value;
}
| {
"end_byte": 2656,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/element_ref.ts"
} |
angular/packages/core/src/linker/query_list.ts_0_6070 | /**
* @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, Subject} from 'rxjs';
import {EventEmitter} from '../event_emitter';
import {Writable} from '../interface/type';
import {arrayEquals, flatten} from '../util/array_utils';
function symbolIterator<T>(this: QueryList<T>): Iterator<T> {
// @ts-expect-error accessing a private member
return this._results[Symbol.iterator]();
}
/**
* An unmodifiable list of items that Angular keeps up to date when the state
* of the application changes.
*
* The type of object that {@link ViewChildren}, {@link ContentChildren}, and {@link QueryList}
* provide.
*
* Implements an iterable interface, therefore it can be used in both ES6
* javascript `for (var i of items)` loops as well as in Angular templates with
* `*ngFor="let i of myList"`.
*
* Changes can be observed by subscribing to the changes `Observable`.
*
* NOTE: In the future this class will implement an `Observable` interface.
*
* @usageNotes
* ### Example
* ```typescript
* @Component({...})
* class Container {
* @ViewChildren(Item) items:QueryList<Item>;
* }
* ```
*
* @publicApi
*/
export class QueryList<T> implements Iterable<T> {
public readonly dirty = true;
private _onDirty?: () => void = undefined;
private _results: Array<T> = [];
private _changesDetected: boolean = false;
private _changes: Subject<QueryList<T>> | undefined = undefined;
readonly length: number = 0;
readonly first: T = undefined!;
readonly last: T = undefined!;
/**
* Returns `Observable` of `QueryList` notifying the subscriber of changes.
*/
get changes(): Observable<any> {
return (this._changes ??= new Subject());
}
/**
* @param emitDistinctChangesOnly Whether `QueryList.changes` should fire only when actual change
* has occurred. Or if it should fire when query is recomputed. (recomputing could resolve in
* the same result)
*/
constructor(private _emitDistinctChangesOnly: boolean = false) {}
/**
* Returns the QueryList entry at `index`.
*/
get(index: number): T | undefined {
return this._results[index];
}
/**
* See
* [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
*/
map<U>(fn: (item: T, index: number, array: T[]) => U): U[] {
return this._results.map(fn);
}
/**
* See
* [Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
*/
filter<S extends T>(predicate: (value: T, index: number, array: readonly T[]) => value is S): S[];
filter(predicate: (value: T, index: number, array: readonly T[]) => unknown): T[];
filter(fn: (item: T, index: number, array: T[]) => boolean): T[] {
return this._results.filter(fn);
}
/**
* See
* [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
*/
find(fn: (item: T, index: number, array: T[]) => boolean): T | undefined {
return this._results.find(fn);
}
/**
* See
* [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
*/
reduce<U>(fn: (prevValue: U, curValue: T, curIndex: number, array: T[]) => U, init: U): U {
return this._results.reduce(fn, init);
}
/**
* See
* [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
*/
forEach(fn: (item: T, index: number, array: T[]) => void): void {
this._results.forEach(fn);
}
/**
* See
* [Array.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
*/
some(fn: (value: T, index: number, array: T[]) => boolean): boolean {
return this._results.some(fn);
}
/**
* Returns a copy of the internal results list as an Array.
*/
toArray(): T[] {
return this._results.slice();
}
toString(): string {
return this._results.toString();
}
/**
* Updates the stored data of the query list, and resets the `dirty` flag to `false`, so that
* on change detection, it will not notify of changes to the queries, unless a new change
* occurs.
*
* @param resultsTree The query results to store
* @param identityAccessor Optional function for extracting stable object identity from a value
* in the array. This function is executed for each element of the query result list while
* comparing current query list with the new one (provided as a first argument of the `reset`
* function) to detect if the lists are different. If the function is not provided, elements
* are compared as is (without any pre-processing).
*/
reset(resultsTree: Array<T | any[]>, identityAccessor?: (value: T) => unknown): void {
(this as {dirty: boolean}).dirty = false;
const newResultFlat = flatten(resultsTree);
if ((this._changesDetected = !arrayEquals(this._results, newResultFlat, identityAccessor))) {
this._results = newResultFlat;
(this as Writable<this>).length = newResultFlat.length;
(this as Writable<this>).last = newResultFlat[this.length - 1];
(this as Writable<this>).first = newResultFlat[0];
}
}
/**
* Triggers a change event by emitting on the `changes` {@link EventEmitter}.
*/
notifyOnChanges(): void {
if (this._changes !== undefined && (this._changesDetected || !this._emitDistinctChangesOnly))
this._changes.next(this);
}
/** @internal */
onDirty(cb: () => void) {
this._onDirty = cb;
}
/** internal */
setDirty() {
(this as {dirty: boolean}).dirty = true;
this._onDirty?.();
}
/** internal */
destroy(): void {
if (this._changes !== undefined) {
this._changes.complete();
this._changes.unsubscribe();
}
}
[Symbol.iterator]: () => Iterator<T> = /** @__PURE__*/ (() => symbolIterator)();
}
| {
"end_byte": 6070,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/query_list.ts"
} |
angular/packages/core/src/linker/component_factory.ts_0_3686 | /**
* @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} from '../change_detection/change_detection';
import {Injector} from '../di/injector';
import {EnvironmentInjector} from '../di/r3_injector';
import {Type} from '../interface/type';
import {ElementRef} from './element_ref';
import {NgModuleRef} from './ng_module_factory';
import {ViewRef} from './view_ref';
/**
* Represents a component created by a `ComponentFactory`.
* Provides access to the component instance and related objects,
* and provides the means of destroying the instance.
*
* @publicApi
*/
export abstract class ComponentRef<C> {
/**
* Updates a specified input name to a new value. Using this method will properly mark for check
* component using the `OnPush` change detection strategy. It will also assure that the
* `OnChanges` lifecycle hook runs when a dynamically created component is change-detected.
*
* @param name The name of an input.
* @param value The new value of an input.
*/
abstract setInput(name: string, value: unknown): void;
/**
* The host or anchor element for this component instance.
*/
abstract get location(): ElementRef;
/**
* The dependency injector for this component instance.
*/
abstract get injector(): Injector;
/**
* This component instance.
*/
abstract get instance(): C;
/**
* The host view defined by the template
* for this component instance.
*/
abstract get hostView(): ViewRef;
/**
* The change detector for this component instance.
*/
abstract get changeDetectorRef(): ChangeDetectorRef;
/**
* The type of this component (as created by a `ComponentFactory` class).
*/
abstract get componentType(): Type<any>;
/**
* Destroys the component instance and all of the data structures associated with it.
*/
abstract destroy(): void;
/**
* A lifecycle hook that provides additional developer-defined cleanup
* functionality for the component.
* @param callback A handler function that cleans up developer-defined data
* associated with this component. Called when the `destroy()` method is invoked.
*/
abstract onDestroy(callback: Function): void;
}
/**
* Base class for a factory that can create a component dynamically.
* Instantiate a factory for a given type of component with `resolveComponentFactory()`.
* Use the resulting `ComponentFactory.create()` method to create a component of that type.
*
* @publicApi
*
* @deprecated Angular no longer requires Component factories. Please use other APIs where
* Component class can be used directly.
*/
export abstract class ComponentFactory<C> {
/**
* The component's HTML selector.
*/
abstract get selector(): string;
/**
* The type of component the factory will create.
*/
abstract get componentType(): Type<any>;
/**
* Selector for all <ng-content> elements in the component.
*/
abstract get ngContentSelectors(): string[];
/**
* The inputs of the component.
*/
abstract get inputs(): {
propName: string;
templateName: string;
transform?: (value: any) => any;
isSignal: boolean;
}[];
/**
* The outputs of the component.
*/
abstract get outputs(): {propName: string; templateName: string}[];
/**
* Creates a new component.
*/
abstract create(
injector: Injector,
projectableNodes?: any[][],
rootSelectorOrNode?: string | any,
environmentInjector?: EnvironmentInjector | NgModuleRef<any>,
): ComponentRef<C>;
}
| {
"end_byte": 3686,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/component_factory.ts"
} |
angular/packages/core/src/linker/template_ref.ts_0_5332 | /**
* @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 '../di/injector';
import {DehydratedContainerView} from '../hydration/interfaces';
import {TContainerNode, TNode, TNodeType} from '../render3/interfaces/node';
import {LView} from '../render3/interfaces/view';
import {getCurrentTNode, getLView} from '../render3/state';
import {createAndRenderEmbeddedLView} from '../render3/view_manipulation';
import {ViewRef as R3_ViewRef} from '../render3/view_ref';
import {assertDefined} from '../util/assert';
import {createElementRef, ElementRef} from './element_ref';
import {EmbeddedViewRef} from './view_ref';
/**
* Represents an embedded template that can be used to instantiate embedded views.
* To instantiate embedded views based on a template, use the `ViewContainerRef`
* method `createEmbeddedView()`.
*
* Access a `TemplateRef` instance by placing a directive on an `<ng-template>`
* element (or directive prefixed with `*`). The `TemplateRef` for the embedded view
* is injected into the constructor of the directive,
* using the `TemplateRef` token.
*
* You can also use a `Query` to find a `TemplateRef` associated with
* a component or a directive.
*
* @see {@link ViewContainerRef}
*
* @publicApi
*/
export abstract class TemplateRef<C> {
/**
* The anchor element in the parent view for this embedded view.
*
* The data-binding and [injection contexts](guide/di/dependency-injection-context) of embedded
* views created from this `TemplateRef` inherit from the contexts of this location.
*
* Typically new embedded views are attached to the view container of this location, but in
* advanced use-cases, the view can be attached to a different container while keeping the
* data-binding and injection context from the original location.
*
*/
// TODO(i): rename to anchor or location
abstract readonly elementRef: ElementRef;
/**
* Instantiates an unattached embedded view based on this template.
* @param context The data-binding context of the embedded view, as declared
* in the `<ng-template>` usage.
* @param injector Injector to be used within the embedded view.
* @returns The new embedded view object.
*/
abstract createEmbeddedView(context: C, injector?: Injector): EmbeddedViewRef<C>;
/**
* Implementation of the `createEmbeddedView` function.
*
* This implementation is internal and allows framework code
* to invoke it with extra parameters (e.g. for hydration) without
* affecting public API.
*
* @internal
*/
abstract createEmbeddedViewImpl(
context: C,
injector?: Injector,
dehydratedView?: DehydratedContainerView | null,
): EmbeddedViewRef<C>;
/**
* Returns an `ssrId` associated with a TView, which was used to
* create this instance of the `TemplateRef`.
*
* @internal
*/
abstract get ssrId(): string | null;
/**
* @internal
* @nocollapse
*/
static __NG_ELEMENT_ID__: () => TemplateRef<any> | null = injectTemplateRef;
}
const ViewEngineTemplateRef = TemplateRef;
// TODO(alxhub): combine interface and implementation. Currently this is challenging since something
// in g3 depends on them being separate.
const R3TemplateRef = class TemplateRef<T> extends ViewEngineTemplateRef<T> {
constructor(
private _declarationLView: LView,
private _declarationTContainer: TContainerNode,
public override elementRef: ElementRef,
) {
super();
}
/**
* Returns an `ssrId` associated with a TView, which was used to
* create this instance of the `TemplateRef`.
*
* @internal
*/
override get ssrId(): string | null {
return this._declarationTContainer.tView?.ssrId || null;
}
override createEmbeddedView(context: T, injector?: Injector): EmbeddedViewRef<T> {
return this.createEmbeddedViewImpl(context, injector);
}
/**
* @internal
*/
override createEmbeddedViewImpl(
context: T,
injector?: Injector,
dehydratedView?: DehydratedContainerView,
): EmbeddedViewRef<T> {
const embeddedLView = createAndRenderEmbeddedLView(
this._declarationLView,
this._declarationTContainer,
context,
{embeddedViewInjector: injector, dehydratedView},
);
return new R3_ViewRef<T>(embeddedLView);
}
};
/**
* Creates a TemplateRef given a node.
*
* @returns The TemplateRef instance to use
*/
export function injectTemplateRef<T>(): TemplateRef<T> | null {
return createTemplateRef<T>(getCurrentTNode()!, getLView());
}
/**
* Creates a TemplateRef and stores it on the injector.
*
* @param hostTNode The node on which a TemplateRef is requested
* @param hostLView The `LView` to which the node belongs
* @returns The TemplateRef instance or null if we can't create a TemplateRef on a given node type
*/
export function createTemplateRef<T>(hostTNode: TNode, hostLView: LView): TemplateRef<T> | null {
if (hostTNode.type & TNodeType.Container) {
ngDevMode && assertDefined(hostTNode.tView, 'TView must be allocated');
return new R3TemplateRef(
hostLView,
hostTNode as TContainerNode,
createElementRef(hostTNode, hostLView),
);
}
return null;
}
| {
"end_byte": 5332,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/template_ref.ts"
} |
angular/packages/core/src/linker/compiler.ts_0_4269 | /**
* @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 {Injectable} from '../di/injectable';
import {InjectionToken} from '../di/injection_token';
import {StaticProvider} from '../di/interface/provider';
import {Type} from '../interface/type';
import {ViewEncapsulation} from '../metadata/view';
import {ComponentFactory as ComponentFactoryR3} from '../render3/component_ref';
import {getComponentDef, getNgModuleDef} from '../render3/def_getters';
import {NgModuleFactory as NgModuleFactoryR3} from '../render3/ng_module_ref';
import {maybeUnwrapFn} from '../render3/util/misc_utils';
import {ComponentFactory} from './component_factory';
import {NgModuleFactory} from './ng_module_factory';
/**
* Combination of NgModuleFactory and ComponentFactories.
*
* @publicApi
*
* @deprecated
* Ivy JIT mode doesn't require accessing this symbol.
*/
export class ModuleWithComponentFactories<T> {
constructor(
public ngModuleFactory: NgModuleFactory<T>,
public componentFactories: ComponentFactory<any>[],
) {}
}
/**
* Low-level service for running the angular compiler during runtime
* to create {@link ComponentFactory}s, which
* can later be used to create and render a Component instance.
*
* Each `@NgModule` provides an own `Compiler` to its injector,
* that will use the directives/pipes of the ng module for compilation
* of components.
*
* @publicApi
*
* @deprecated
* Ivy JIT mode doesn't require accessing this symbol.
*/
@Injectable({providedIn: 'root'})
export class Compiler {
/**
* Compiles the given NgModule and all of its components. All templates of the components
* have to be inlined.
*/
compileModuleSync<T>(moduleType: Type<T>): NgModuleFactory<T> {
return new NgModuleFactoryR3(moduleType);
}
/**
* Compiles the given NgModule and all of its components
*/
compileModuleAsync<T>(moduleType: Type<T>): Promise<NgModuleFactory<T>> {
return Promise.resolve(this.compileModuleSync(moduleType));
}
/**
* Same as {@link Compiler#compileModuleSync compileModuleSync} but also creates ComponentFactories for all components.
*/
compileModuleAndAllComponentsSync<T>(moduleType: Type<T>): ModuleWithComponentFactories<T> {
const ngModuleFactory = this.compileModuleSync(moduleType);
const moduleDef = getNgModuleDef(moduleType)!;
const componentFactories = maybeUnwrapFn(moduleDef.declarations).reduce(
(factories: ComponentFactory<any>[], declaration: Type<any>) => {
const componentDef = getComponentDef(declaration);
componentDef && factories.push(new ComponentFactoryR3(componentDef));
return factories;
},
[] as ComponentFactory<any>[],
);
return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
}
/**
* Same as {@link Compiler#compileModuleAsync compileModuleAsync} but also creates ComponentFactories for all components.
*/
compileModuleAndAllComponentsAsync<T>(
moduleType: Type<T>,
): Promise<ModuleWithComponentFactories<T>> {
return Promise.resolve(this.compileModuleAndAllComponentsSync(moduleType));
}
/**
* Clears all caches.
*/
clearCache(): void {}
/**
* Clears the cache for the given component/ngModule.
*/
clearCacheFor(type: Type<any>) {}
/**
* Returns the id for a given NgModule, if one is defined and known to the compiler.
*/
getModuleId(moduleType: Type<any>): string | undefined {
return undefined;
}
}
/**
* Options for creating a compiler.
*
* @publicApi
*/
export type CompilerOptions = {
defaultEncapsulation?: ViewEncapsulation;
providers?: StaticProvider[];
preserveWhitespaces?: boolean;
};
/**
* Token to provide CompilerOptions in the platform injector.
*
* @publicApi
*/
export const COMPILER_OPTIONS = new InjectionToken<CompilerOptions[]>(
ngDevMode ? 'compilerOptions' : '',
);
/**
* A factory for creating a Compiler
*
* @publicApi
*
* @deprecated
* Ivy JIT mode doesn't require accessing this symbol.
*/
export abstract class CompilerFactory {
abstract createCompiler(options?: CompilerOptions[]): Compiler;
}
| {
"end_byte": 4269,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/compiler.ts"
} |
angular/packages/core/src/linker/ng_module_factory_loader_impl.ts_0_291 | /**
* @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 exists for easily patching NgModuleFactoryLoader in g3
export default {};
| {
"end_byte": 291,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker/ng_module_factory_loader_impl.ts"
} |
angular/packages/core/src/testability/testability.externs.js_0_518 | /** @externs */
/** @record @struct */
function PublicTestability() {}
/**
* @return {?}
*/
PublicTestability.prototype.isStable = function () {};
/**
* @param {?} callback
* @param {?} timeout
* @param {?} updateCallback
* @return {?}
*/
PublicTestability.prototype.whenStable = function (callback, timeout, updateCallback) {};
/**
* @param {?} using
* @param {?} provider
* @param {?} exactMatch
* @return {?}
*/
PublicTestability.prototype.findProviders = function (using, provider, exactMatch) {};
| {
"end_byte": 518,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/testability/testability.externs.js"
} |
angular/packages/core/src/testability/testability.ts_0_7826 | /**
* @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, InjectionToken} from '../di';
import {NgZone} from '../zone/ng_zone';
/**
* Testability API.
* `declare` keyword causes tsickle to generate externs, so these methods are
* not renamed by Closure Compiler.
* @publicApi
*/
export declare interface PublicTestability {
isStable(): boolean;
whenStable(callback: Function, timeout?: number, updateCallback?: Function): void;
findProviders(using: any, provider: string, exactMatch: boolean): any[];
}
// Angular internal, not intended for public API.
export interface PendingMacrotask {
source: string;
creationLocation: Error;
runCount?: number;
data?: TaskData;
}
export interface TaskData {
target?: XMLHttpRequest;
delay?: number;
isPeriodic?: boolean;
}
interface WaitCallback {
// Needs to be 'any' - setTimeout returns a number according to ES6, but
// on NodeJS it returns a Timer.
timeoutId: any;
doneCb: Function;
updateCb?: Function;
}
/**
* Internal injection token that can used to access an instance of a Testability class.
*
* This token acts as a bridge between the core bootstrap code and the `Testability` class. This is
* needed to ensure that there are no direct references to the `Testability` class, so it can be
* tree-shaken away (if not referenced). For the environments/setups when the `Testability` class
* should be available, this token is used to add a provider that references the `Testability`
* class. Otherwise, only this token is retained in a bundle, but the `Testability` class is not.
*/
export const TESTABILITY = new InjectionToken<Testability>('');
/**
* Internal injection token to retrieve Testability getter class instance.
*/
export const TESTABILITY_GETTER = new InjectionToken<GetTestability>('');
/**
* The Testability service provides testing hooks that can be accessed from
* the browser.
*
* Angular applications bootstrapped using an NgModule (via `@NgModule.bootstrap` field) will also
* instantiate Testability by default (in both development and production modes).
*
* For applications bootstrapped using the `bootstrapApplication` function, Testability is not
* included by default. You can include it into your applications by getting the list of necessary
* providers using the `provideProtractorTestingSupport()` function and adding them into the
* `options.providers` array. Example:
*
* ```typescript
* import {provideProtractorTestingSupport} from '@angular/platform-browser';
*
* await bootstrapApplication(RootComponent, providers: [provideProtractorTestingSupport()]);
* ```
*
* @publicApi
*/
@Injectable()
export class Testability implements PublicTestability {
private _isZoneStable: boolean = true;
private _callbacks: WaitCallback[] = [];
private taskTrackingZone: {macroTasks: Task[]} | null = null;
constructor(
private _ngZone: NgZone,
private registry: TestabilityRegistry,
@Inject(TESTABILITY_GETTER) testabilityGetter: GetTestability,
) {
// If there was no Testability logic registered in the global scope
// before, register the current testability getter as a global one.
if (!_testabilityGetter) {
setTestabilityGetter(testabilityGetter);
testabilityGetter.addToWindow(registry);
}
this._watchAngularEvents();
_ngZone.run(() => {
this.taskTrackingZone =
typeof Zone == 'undefined' ? null : Zone.current.get('TaskTrackingZone');
});
}
private _watchAngularEvents(): void {
this._ngZone.onUnstable.subscribe({
next: () => {
this._isZoneStable = false;
},
});
this._ngZone.runOutsideAngular(() => {
this._ngZone.onStable.subscribe({
next: () => {
NgZone.assertNotInAngularZone();
queueMicrotask(() => {
this._isZoneStable = true;
this._runCallbacksIfReady();
});
},
});
});
}
/**
* Whether an associated application is stable
*/
isStable(): boolean {
return this._isZoneStable && !this._ngZone.hasPendingMacrotasks;
}
private _runCallbacksIfReady(): void {
if (this.isStable()) {
// Schedules the call backs in a new frame so that it is always async.
queueMicrotask(() => {
while (this._callbacks.length !== 0) {
let cb = this._callbacks.pop()!;
clearTimeout(cb.timeoutId);
cb.doneCb();
}
});
} else {
// Still not stable, send updates.
let pending = this.getPendingTasks();
this._callbacks = this._callbacks.filter((cb) => {
if (cb.updateCb && cb.updateCb(pending)) {
clearTimeout(cb.timeoutId);
return false;
}
return true;
});
}
}
private getPendingTasks(): PendingMacrotask[] {
if (!this.taskTrackingZone) {
return [];
}
// Copy the tasks data so that we don't leak tasks.
return this.taskTrackingZone.macroTasks.map((t: Task) => {
return {
source: t.source,
// From TaskTrackingZone:
// https://github.com/angular/zone.js/blob/master/lib/zone-spec/task-tracking.ts#L40
creationLocation: (t as any).creationLocation as Error,
data: t.data,
};
});
}
private addCallback(cb: Function, timeout?: number, updateCb?: Function) {
let timeoutId: any = -1;
if (timeout && timeout > 0) {
timeoutId = setTimeout(() => {
this._callbacks = this._callbacks.filter((cb) => cb.timeoutId !== timeoutId);
cb();
}, timeout);
}
this._callbacks.push(<WaitCallback>{doneCb: cb, timeoutId: timeoutId, updateCb: updateCb});
}
/**
* Wait for the application to be stable with a timeout. If the timeout is reached before that
* happens, the callback receives a list of the macro tasks that were pending, otherwise null.
*
* @param doneCb The callback to invoke when Angular is stable or the timeout expires
* whichever comes first.
* @param timeout Optional. The maximum time to wait for Angular to become stable. If not
* specified, whenStable() will wait forever.
* @param updateCb Optional. If specified, this callback will be invoked whenever the set of
* pending macrotasks changes. If this callback returns true doneCb will not be invoked
* and no further updates will be issued.
*/
whenStable(doneCb: Function, timeout?: number, updateCb?: Function): void {
if (updateCb && !this.taskTrackingZone) {
throw new Error(
'Task tracking zone is required when passing an update callback to ' +
'whenStable(). Is "zone.js/plugins/task-tracking" loaded?',
);
}
this.addCallback(doneCb, timeout, updateCb);
this._runCallbacksIfReady();
}
/**
* Registers an application with a testability hook so that it can be tracked.
* @param token token of application, root element
*
* @internal
*/
registerApplication(token: any) {
this.registry.registerApplication(token, this);
}
/**
* Unregisters an application.
* @param token token of application, root element
*
* @internal
*/
unregisterApplication(token: any) {
this.registry.unregisterApplication(token);
}
/**
* Find providers by name
* @param using The root element to search from
* @param provider The name of binding variable
* @param exactMatch Whether using exactMatch
*/
findProviders(using: any, provider: string, exactMatch: boolean): any[] {
// TODO(juliemr): implement.
return [];
}
}
/**
* A global registry of {@link Testability} instances for specific elements.
* @publicApi
*/ | {
"end_byte": 7826,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/testability/testability.ts"
} |
angular/packages/core/src/testability/testability.ts_7827_10063 | @Injectable({providedIn: 'platform'})
export class TestabilityRegistry {
/** @internal */
_applications = new Map<any, Testability>();
/**
* Registers an application with a testability hook so that it can be tracked
* @param token token of application, root element
* @param testability Testability hook
*/
registerApplication(token: any, testability: Testability) {
this._applications.set(token, testability);
}
/**
* Unregisters an application.
* @param token token of application, root element
*/
unregisterApplication(token: any) {
this._applications.delete(token);
}
/**
* Unregisters all applications
*/
unregisterAllApplications() {
this._applications.clear();
}
/**
* Get a testability hook associated with the application
* @param elem root element
*/
getTestability(elem: any): Testability | null {
return this._applications.get(elem) || null;
}
/**
* Get all registered testabilities
*/
getAllTestabilities(): Testability[] {
return Array.from(this._applications.values());
}
/**
* Get all registered applications(root elements)
*/
getAllRootElements(): any[] {
return Array.from(this._applications.keys());
}
/**
* Find testability of a node in the Tree
* @param elem node
* @param findInAncestors whether finding testability in ancestors if testability was not found in
* current node
*/
findTestabilityInTree(elem: Node, findInAncestors: boolean = true): Testability | null {
return _testabilityGetter?.findTestabilityInTree(this, elem, findInAncestors) ?? null;
}
}
/**
* Adapter interface for retrieving the `Testability` service associated for a
* particular context.
*
* @publicApi
*/
export interface GetTestability {
addToWindow(registry: TestabilityRegistry): void;
findTestabilityInTree(
registry: TestabilityRegistry,
elem: any,
findInAncestors: boolean,
): Testability | null;
}
/**
* Set the {@link GetTestability} implementation used by the Angular testing framework.
* @publicApi
*/
export function setTestabilityGetter(getter: GetTestability): void {
_testabilityGetter = getter;
}
let _testabilityGetter: GetTestability | undefined; | {
"end_byte": 10063,
"start_byte": 7827,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/testability/testability.ts"
} |
angular/packages/core/src/platform/platform.ts_0_6303 | /**
* @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 {
publishDefaultGlobalUtils,
publishSignalConfiguration,
} from '../application/application_ref';
import {PLATFORM_INITIALIZER} from '../application/application_tokens';
import {
EnvironmentProviders,
InjectionToken,
Injector,
makeEnvironmentProviders,
runInInjectionContext,
StaticProvider,
} from '../di';
import {INJECTOR_SCOPE} from '../di/scope';
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {PlatformRef} from './platform_ref';
import {PLATFORM_DESTROY_LISTENERS} from './platform_destroy_listeners';
let _platformInjector: Injector | null = null;
/**
* Internal token to indicate whether having multiple bootstrapped platform should be allowed (only
* one bootstrapped platform is allowed by default). This token helps to support SSR scenarios.
*/
export const ALLOW_MULTIPLE_PLATFORMS = new InjectionToken<boolean>(
ngDevMode ? 'AllowMultipleToken' : '',
);
/**
* Creates a platform.
* Platforms must be created on launch using this function.
*
* @publicApi
*/
export function createPlatform(injector: Injector): PlatformRef {
if (_platformInjector && !_platformInjector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
throw new RuntimeError(
RuntimeErrorCode.MULTIPLE_PLATFORMS,
ngDevMode && 'There can be only one platform. Destroy the previous one to create a new one.',
);
}
publishDefaultGlobalUtils();
publishSignalConfiguration();
_platformInjector = injector;
const platform = injector.get(PlatformRef);
runPlatformInitializers(injector);
return platform;
}
/**
* Creates a factory for a platform. Can be used to provide or override `Providers` specific to
* your application's runtime needs, such as `PLATFORM_INITIALIZER` and `PLATFORM_ID`.
* @param parentPlatformFactory Another platform factory to modify. Allows you to compose factories
* to build up configurations that might be required by different libraries or parts of the
* application.
* @param name Identifies the new platform factory.
* @param providers A set of dependency providers for platforms created with the new factory.
*
* @publicApi
*/
export function createPlatformFactory(
parentPlatformFactory: ((extraProviders?: StaticProvider[]) => PlatformRef) | null,
name: string,
providers: StaticProvider[] = [],
): (extraProviders?: StaticProvider[]) => PlatformRef {
const desc = `Platform: ${name}`;
const marker = new InjectionToken(desc);
return (extraProviders: StaticProvider[] = []) => {
let platform = getPlatform();
if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
const platformProviders: StaticProvider[] = [
...providers,
...extraProviders,
{provide: marker, useValue: true},
];
if (parentPlatformFactory) {
parentPlatformFactory(platformProviders);
} else {
createPlatform(createPlatformInjector(platformProviders, desc));
}
}
return assertPlatform(marker);
};
}
/**
* Helper function to create an instance of a platform injector (that maintains the 'platform'
* scope).
*/
function createPlatformInjector(providers: StaticProvider[] = [], name?: string): Injector {
return Injector.create({
name,
providers: [
{provide: INJECTOR_SCOPE, useValue: 'platform'},
{provide: PLATFORM_DESTROY_LISTENERS, useValue: new Set([() => (_platformInjector = null)])},
...providers,
],
});
}
/**
* Checks that there is currently a platform that contains the given token as a provider.
*
* @publicApi
*/
export function assertPlatform(requiredToken: any): PlatformRef {
const platform = getPlatform();
if (!platform) {
throw new RuntimeError(RuntimeErrorCode.PLATFORM_NOT_FOUND, ngDevMode && 'No platform exists!');
}
if (
(typeof ngDevMode === 'undefined' || ngDevMode) &&
!platform.injector.get(requiredToken, null)
) {
throw new RuntimeError(
RuntimeErrorCode.MULTIPLE_PLATFORMS,
'A platform with a different configuration has been created. Please destroy it first.',
);
}
return platform;
}
/**
* Returns the current platform.
*
* @publicApi
*/
export function getPlatform(): PlatformRef | null {
return _platformInjector?.get(PlatformRef) ?? null;
}
/**
* Destroys the current Angular platform and all Angular applications on the page.
* Destroys all modules and listeners registered with the platform.
*
* @publicApi
*/
export function destroyPlatform(): void {
getPlatform()?.destroy();
}
/**
* The goal of this function is to bootstrap a platform injector,
* but avoid referencing `PlatformRef` class.
* This function is needed for bootstrapping a Standalone Component.
*/
export function createOrReusePlatformInjector(providers: StaticProvider[] = []): Injector {
// If a platform injector already exists, it means that the platform
// is already bootstrapped and no additional actions are required.
if (_platformInjector) return _platformInjector;
publishDefaultGlobalUtils();
// Otherwise, setup a new platform injector and run platform initializers.
const injector = createPlatformInjector(providers);
_platformInjector = injector;
publishSignalConfiguration();
runPlatformInitializers(injector);
return injector;
}
/**
* @description
* This function is used to provide initialization functions that will be executed upon
* initialization of the platform injector.
*
* Note that the provided initializer is run in the injection context.
*
* Previously, this was achieved using the `PLATFORM_INITIALIZER` token which is now deprecated.
*
* @see {@link PLATFORM_INITIALIZER}
*
* @publicApi
*/
export function providePlatformInitializer(initializerFn: () => void): EnvironmentProviders {
return makeEnvironmentProviders([
{
provide: PLATFORM_INITIALIZER,
useValue: initializerFn,
multi: true,
},
]);
}
function runPlatformInitializers(injector: Injector): void {
const inits = injector.get(PLATFORM_INITIALIZER, null);
runInInjectionContext(injector, () => {
inits?.forEach((init) => init());
});
}
| {
"end_byte": 6303,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/platform/platform.ts"
} |
angular/packages/core/src/platform/platform_core_providers.ts_0_556 | /**
* @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 {StaticProvider} from '../di';
import {createPlatformFactory} from './platform';
import {PlatformRef} from './platform_ref';
/**
* This platform has to be included in any other platform
*
* @publicApi
*/
export const platformCore: (extraProviders?: StaticProvider[] | undefined) => PlatformRef =
createPlatformFactory(null, 'core', []);
| {
"end_byte": 556,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/platform/platform_core_providers.ts"
} |
angular/packages/core/src/platform/platform_ref.ts_0_5244 | /**
* @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 {compileNgModuleFactory} from '../application/application_ngmodule_factory_compiler';
import {
_callAndReportToErrorHandler,
BootstrapOptions,
optionsReducer,
} from '../application/application_ref';
import {
getNgZoneOptions,
internalProvideZoneChangeDetection,
} from '../change_detection/scheduling/ng_zone_scheduling';
import {ChangeDetectionScheduler} from '../change_detection/scheduling/zoneless_scheduling';
import {ChangeDetectionSchedulerImpl} from '../change_detection/scheduling/zoneless_scheduling_impl';
import {Injectable, Injector} from '../di';
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {Type} from '../interface/type';
import {CompilerOptions} from '../linker';
import {NgModuleFactory, NgModuleRef} from '../linker/ng_module_factory';
import {createNgModuleRefWithProviders} from '../render3/ng_module_ref';
import {getNgZone, NgZone} from '../zone/ng_zone';
import {bootstrap} from './bootstrap';
import {PLATFORM_DESTROY_LISTENERS} from './platform_destroy_listeners';
/**
* The Angular platform is the entry point for Angular on a web page.
* Each page has exactly one platform. Services (such as reflection) which are common
* to every Angular application running on the page are bound in its scope.
* A page's platform is initialized implicitly when a platform is created using a platform
* factory such as `PlatformBrowser`, or explicitly by calling the `createPlatform()` function.
*
* @publicApi
*/
@Injectable({providedIn: 'platform'})
export class PlatformRef {
private _modules: NgModuleRef<any>[] = [];
private _destroyListeners: Array<() => void> = [];
private _destroyed: boolean = false;
/** @internal */
constructor(private _injector: Injector) {}
/**
* Creates an instance of an `@NgModule` for the given platform.
*
* @deprecated Passing NgModule factories as the `PlatformRef.bootstrapModuleFactory` function
* argument is deprecated. Use the `PlatformRef.bootstrapModule` API instead.
*/
bootstrapModuleFactory<M>(
moduleFactory: NgModuleFactory<M>,
options?: BootstrapOptions,
): Promise<NgModuleRef<M>> {
const scheduleInRootZone = (options as any)?.scheduleInRootZone;
const ngZoneFactory = () =>
getNgZone(options?.ngZone, {
...getNgZoneOptions({
eventCoalescing: options?.ngZoneEventCoalescing,
runCoalescing: options?.ngZoneRunCoalescing,
}),
scheduleInRootZone,
});
const ignoreChangesOutsideZone = options?.ignoreChangesOutsideZone;
const allAppProviders = [
internalProvideZoneChangeDetection({
ngZoneFactory,
ignoreChangesOutsideZone,
}),
{provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl},
];
const moduleRef = createNgModuleRefWithProviders(
moduleFactory.moduleType,
this.injector,
allAppProviders,
);
return bootstrap({
moduleRef,
allPlatformModules: this._modules,
platformInjector: this.injector,
});
}
/**
* Creates an instance of an `@NgModule` for a given platform.
*
* @usageNotes
* ### Simple Example
*
* ```typescript
* @NgModule({
* imports: [BrowserModule]
* })
* class MyModule {}
*
* let moduleRef = platformBrowser().bootstrapModule(MyModule);
* ```
*
*/
bootstrapModule<M>(
moduleType: Type<M>,
compilerOptions:
| (CompilerOptions & BootstrapOptions)
| Array<CompilerOptions & BootstrapOptions> = [],
): Promise<NgModuleRef<M>> {
const options = optionsReducer({}, compilerOptions);
return compileNgModuleFactory(this.injector, options, moduleType).then((moduleFactory) =>
this.bootstrapModuleFactory(moduleFactory, options),
);
}
/**
* Registers a listener to be called when the platform is destroyed.
*/
onDestroy(callback: () => void): void {
this._destroyListeners.push(callback);
}
/**
* Retrieves the platform {@link Injector}, which is the parent injector for
* every Angular application on the page and provides singleton providers.
*/
get injector(): Injector {
return this._injector;
}
/**
* Destroys the current Angular platform and all Angular applications on the page.
* Destroys all modules and listeners registered with the platform.
*/
destroy() {
if (this._destroyed) {
throw new RuntimeError(
RuntimeErrorCode.PLATFORM_ALREADY_DESTROYED,
ngDevMode && 'The platform has already been destroyed!',
);
}
this._modules.slice().forEach((module) => module.destroy());
this._destroyListeners.forEach((listener) => listener());
const destroyListeners = this._injector.get(PLATFORM_DESTROY_LISTENERS, null);
if (destroyListeners) {
destroyListeners.forEach((listener) => listener());
destroyListeners.clear();
}
this._destroyed = true;
}
/**
* Indicates whether this instance was destroyed.
*/
get destroyed() {
return this._destroyed;
}
}
| {
"end_byte": 5244,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/platform/platform_ref.ts"
} |
angular/packages/core/src/platform/bootstrap.ts_0_6578 | /**
* @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 {Subscription} from 'rxjs';
import {PROVIDED_NG_ZONE} from '../change_detection/scheduling/ng_zone_scheduling';
import {EnvironmentInjector, R3Injector} from '../di/r3_injector';
import {ErrorHandler} from '../error_handler';
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {DEFAULT_LOCALE_ID} from '../i18n/localization';
import {LOCALE_ID} from '../i18n/tokens';
import {ImagePerformanceWarning} from '../image_performance_warning';
import {Type} from '../interface/type';
import {PLATFORM_DESTROY_LISTENERS} from './platform_destroy_listeners';
import {setLocaleId} from '../render3/i18n/i18n_locale_id';
import {NgZone} from '../zone/ng_zone';
import {ApplicationInitStatus} from '../application/application_init';
import {_callAndReportToErrorHandler, ApplicationRef, remove} from '../application/application_ref';
import {PROVIDED_ZONELESS} from '../change_detection/scheduling/zoneless_scheduling';
import {Injector} from '../di';
import {InternalNgModuleRef, NgModuleRef} from '../linker/ng_module_factory';
import {stringify} from '../util/stringify';
export interface BootstrapConfig {
platformInjector: Injector;
}
export interface ModuleBootstrapConfig<M> extends BootstrapConfig {
moduleRef: InternalNgModuleRef<M>;
allPlatformModules: NgModuleRef<unknown>[];
}
export interface ApplicationBootstrapConfig extends BootstrapConfig {
r3Injector: R3Injector;
rootComponent: Type<unknown> | undefined;
}
function isApplicationBootstrapConfig(
config: ApplicationBootstrapConfig | ModuleBootstrapConfig<unknown>,
): config is ApplicationBootstrapConfig {
return !(config as ModuleBootstrapConfig<unknown>).moduleRef;
}
export function bootstrap<M>(
moduleBootstrapConfig: ModuleBootstrapConfig<M>,
): Promise<NgModuleRef<M>>;
export function bootstrap(
applicationBootstrapConfig: ApplicationBootstrapConfig,
): Promise<ApplicationRef>;
export function bootstrap<M>(
config: ModuleBootstrapConfig<M> | ApplicationBootstrapConfig,
): Promise<ApplicationRef> | Promise<NgModuleRef<M>> {
const envInjector = isApplicationBootstrapConfig(config)
? config.r3Injector
: config.moduleRef.injector;
const ngZone = envInjector.get(NgZone);
return ngZone.run(() => {
if (isApplicationBootstrapConfig(config)) {
config.r3Injector.resolveInjectorInitializers();
} else {
config.moduleRef.resolveInjectorInitializers();
}
const exceptionHandler = envInjector.get(ErrorHandler, null);
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (exceptionHandler === null) {
const errorMessage = isApplicationBootstrapConfig(config)
? 'No `ErrorHandler` found in the Dependency Injection tree.'
: 'No ErrorHandler. Is platform module (BrowserModule) included';
throw new RuntimeError(
RuntimeErrorCode.MISSING_REQUIRED_INJECTABLE_IN_BOOTSTRAP,
errorMessage,
);
}
if (envInjector.get(PROVIDED_ZONELESS) && envInjector.get(PROVIDED_NG_ZONE)) {
throw new RuntimeError(
RuntimeErrorCode.PROVIDED_BOTH_ZONE_AND_ZONELESS,
'Invalid change detection configuration: ' +
'provideZoneChangeDetection and provideExperimentalZonelessChangeDetection cannot be used together.',
);
}
}
let onErrorSubscription: Subscription;
ngZone.runOutsideAngular(() => {
onErrorSubscription = ngZone.onError.subscribe({
next: (error: any) => {
exceptionHandler!.handleError(error);
},
});
});
// If the whole platform is destroyed, invoke the `destroy` method
// for all bootstrapped applications as well.
if (isApplicationBootstrapConfig(config)) {
const destroyListener = () => envInjector.destroy();
const onPlatformDestroyListeners = config.platformInjector.get(PLATFORM_DESTROY_LISTENERS);
onPlatformDestroyListeners.add(destroyListener);
envInjector.onDestroy(() => {
onErrorSubscription.unsubscribe();
onPlatformDestroyListeners.delete(destroyListener);
});
} else {
const destroyListener = () => config.moduleRef.destroy();
const onPlatformDestroyListeners = config.platformInjector.get(PLATFORM_DESTROY_LISTENERS);
onPlatformDestroyListeners.add(destroyListener);
config.moduleRef.onDestroy(() => {
remove(config.allPlatformModules, config.moduleRef);
onErrorSubscription.unsubscribe();
onPlatformDestroyListeners.delete(destroyListener);
});
}
return _callAndReportToErrorHandler(exceptionHandler!, ngZone, () => {
const initStatus = envInjector.get(ApplicationInitStatus);
initStatus.runInitializers();
return initStatus.donePromise.then(() => {
// If the `LOCALE_ID` provider is defined at bootstrap then we set the value for ivy
const localeId = envInjector.get(LOCALE_ID, DEFAULT_LOCALE_ID);
setLocaleId(localeId || DEFAULT_LOCALE_ID);
if (typeof ngDevMode === 'undefined' || ngDevMode) {
const imagePerformanceService = envInjector.get(ImagePerformanceWarning);
imagePerformanceService.start();
}
if (isApplicationBootstrapConfig(config)) {
const appRef = envInjector.get(ApplicationRef);
if (config.rootComponent !== undefined) {
appRef.bootstrap(config.rootComponent);
}
return appRef;
} else {
moduleDoBootstrap(config.moduleRef, config.allPlatformModules);
return config.moduleRef;
}
});
});
});
}
function moduleDoBootstrap(
moduleRef: InternalNgModuleRef<any>,
allPlatformModules: NgModuleRef<unknown>[],
): void {
const appRef = moduleRef.injector.get(ApplicationRef);
if (moduleRef._bootstrapComponents.length > 0) {
moduleRef._bootstrapComponents.forEach((f) => appRef.bootstrap(f));
} else if (moduleRef.instance.ngDoBootstrap) {
moduleRef.instance.ngDoBootstrap(appRef);
} else {
throw new RuntimeError(
RuntimeErrorCode.BOOTSTRAP_COMPONENTS_NOT_FOUND,
ngDevMode &&
`The module ${stringify(moduleRef.instance.constructor)} was bootstrapped, ` +
`but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. ` +
`Please define one of these.`,
);
}
allPlatformModules.push(moduleRef);
}
| {
"end_byte": 6578,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/platform/bootstrap.ts"
} |
angular/packages/core/src/platform/platform_destroy_listeners.ts_0_695 | /**
* @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 {InjectionToken} from '../di';
/**
* Internal token that allows to register extra callbacks that should be invoked during the
* `PlatformRef.destroy` operation. This token is needed to avoid a direct reference to the
* `PlatformRef` class (i.e. register the callback via `PlatformRef.onDestroy`), thus making the
* entire class tree-shakeable.
*/
export const PLATFORM_DESTROY_LISTENERS = new InjectionToken<Set<VoidFunction>>(
ngDevMode ? 'PlatformDestroyListeners' : '',
);
| {
"end_byte": 695,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/platform/platform_destroy_listeners.ts"
} |
angular/packages/core/src/zone/async-stack-tagging.ts_0_1514 | /**
* @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
*/
interface ConsoleWithAsyncTagging {
createTask(name: string): ConsoleTask;
}
interface ConsoleTask {
run<T>(f: () => T): T;
}
interface ZoneConsoleTask extends Task {
consoleTask?: ConsoleTask;
}
export class AsyncStackTaggingZoneSpec implements ZoneSpec {
createTask: ConsoleWithAsyncTagging['createTask'];
constructor(
namePrefix: string,
consoleAsyncStackTaggingImpl: ConsoleWithAsyncTagging = console as any,
) {
this.name = 'asyncStackTagging for ' + namePrefix;
this.createTask = consoleAsyncStackTaggingImpl?.createTask ?? (() => null);
}
// ZoneSpec implementation below.
name: string;
onScheduleTask(
delegate: ZoneDelegate,
_current: Zone,
target: Zone,
task: ZoneConsoleTask,
): Task {
task.consoleTask = this.createTask(`Zone - ${task.source || task.type}`);
return delegate.scheduleTask(target, task);
}
onInvokeTask(
delegate: ZoneDelegate,
_currentZone: Zone,
targetZone: Zone,
task: ZoneConsoleTask,
applyThis: any,
applyArgs?: any[],
) {
let ret;
if (task.consoleTask) {
ret = task.consoleTask.run(() => delegate.invokeTask(targetZone, task, applyThis, applyArgs));
} else {
ret = delegate.invokeTask(targetZone, task, applyThis, applyArgs);
}
return ret;
}
}
| {
"end_byte": 1514,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/zone/async-stack-tagging.ts"
} |
angular/packages/core/src/zone/ng_zone.ts_0_3237 | /**
* @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 {SCHEDULE_IN_ROOT_ZONE_DEFAULT} from '../change_detection/scheduling/flags';
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {EventEmitter} from '../event_emitter';
import {scheduleCallbackWithRafRace} from '../util/callback_scheduler';
import {noop} from '../util/noop';
import {AsyncStackTaggingZoneSpec} from './async-stack-tagging';
// The below is needed as otherwise a number of targets fail in G3 due to:
// ERROR - [JSC_UNDEFINED_VARIABLE] variable Zone is undeclared
declare const Zone: any;
const isAngularZoneProperty = 'isAngularZone';
export const angularZoneInstanceIdProperty = isAngularZoneProperty + '_ID';
let ngZoneInstanceId = 0;
/**
* An injectable service for executing work inside or outside of the Angular zone.
*
* The most common use of this service is to optimize performance when starting a work consisting of
* one or more asynchronous tasks that don't require UI updates or error handling to be handled by
* Angular. Such tasks can be kicked off via {@link #runOutsideAngular} and if needed, these tasks
* can reenter the Angular zone via {@link #run}.
*
* <!-- TODO: add/fix links to:
* - docs explaining zones and the use of zones in Angular and change-detection
* - link to runOutsideAngular/run (throughout this file!)
* -->
*
* @usageNotes
* ### Example
*
* ```
* import {Component, NgZone} from '@angular/core';
* import {NgIf} from '@angular/common';
*
* @Component({
* selector: 'ng-zone-demo',
* template: `
* <h2>Demo: NgZone</h2>
*
* <p>Progress: {{progress}}%</p>
* <p *ngIf="progress >= 100">Done processing {{label}} of Angular zone!</p>
*
* <button (click)="processWithinAngularZone()">Process within Angular zone</button>
* <button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button>
* `,
* })
* export class NgZoneDemo {
* progress: number = 0;
* label: string;
*
* constructor(private _ngZone: NgZone) {}
*
* // Loop inside the Angular zone
* // so the UI DOES refresh after each setTimeout cycle
* processWithinAngularZone() {
* this.label = 'inside';
* this.progress = 0;
* this._increaseProgress(() => console.log('Inside Done!'));
* }
*
* // Loop outside of the Angular zone
* // so the UI DOES NOT refresh after each setTimeout cycle
* processOutsideOfAngularZone() {
* this.label = 'outside';
* this.progress = 0;
* this._ngZone.runOutsideAngular(() => {
* this._increaseProgress(() => {
* // reenter the Angular zone and display done
* this._ngZone.run(() => { console.log('Outside Done!'); });
* });
* });
* }
*
* _increaseProgress(doneCallback: () => void) {
* this.progress += 1;
* console.log(`Current progress: ${this.progress}%`);
*
* if (this.progress < 100) {
* window.setTimeout(() => this._increaseProgress(doneCallback), 10);
* } else {
* doneCallback();
* }
* }
* }
* ```
*
* @publicApi
*/ | {
"end_byte": 3237,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/zone/ng_zone.ts"
} |
angular/packages/core/src/zone/ng_zone.ts_3238_10149 | export class NgZone {
readonly hasPendingMacrotasks: boolean = false;
readonly hasPendingMicrotasks: boolean = false;
/**
* Whether there are no outstanding microtasks or macrotasks.
*/
readonly isStable: boolean = true;
/**
* Notifies when code enters Angular Zone. This gets fired first on VM Turn.
*/
readonly onUnstable: EventEmitter<any> = new EventEmitter(false);
/**
* Notifies when there is no more microtasks enqueued in the current VM Turn.
* This is a hint for Angular to do change detection, which may enqueue more microtasks.
* For this reason this event can fire multiple times per VM Turn.
*/
readonly onMicrotaskEmpty: EventEmitter<any> = new EventEmitter(false);
/**
* Notifies when the last `onMicrotaskEmpty` has run and there are no more microtasks, which
* implies we are about to relinquish VM turn.
* This event gets called just once.
*/
readonly onStable: EventEmitter<any> = new EventEmitter(false);
/**
* Notifies that an error has been delivered.
*/
readonly onError: EventEmitter<any> = new EventEmitter(false);
constructor(options: {
enableLongStackTrace?: boolean;
shouldCoalesceEventChangeDetection?: boolean;
shouldCoalesceRunChangeDetection?: boolean;
}) {
const {
enableLongStackTrace = false,
shouldCoalesceEventChangeDetection = false,
shouldCoalesceRunChangeDetection = false,
scheduleInRootZone = SCHEDULE_IN_ROOT_ZONE_DEFAULT,
} = options as InternalNgZoneOptions;
if (typeof Zone == 'undefined') {
throw new RuntimeError(
RuntimeErrorCode.MISSING_ZONEJS,
ngDevMode && `In this configuration Angular requires Zone.js`,
);
}
Zone.assertZonePatched();
const self = this as any as NgZonePrivate;
self._nesting = 0;
self._outer = self._inner = Zone.current;
// AsyncStackTaggingZoneSpec provides `linked stack traces` to show
// where the async operation is scheduled. For more details, refer
// to this article, https://developer.chrome.com/blog/devtools-better-angular-debugging/
// And we only import this AsyncStackTaggingZoneSpec in development mode,
// in the production mode, the AsyncStackTaggingZoneSpec will be tree shaken away.
if (ngDevMode) {
self._inner = self._inner.fork(new AsyncStackTaggingZoneSpec('Angular'));
}
if ((Zone as any)['TaskTrackingZoneSpec']) {
self._inner = self._inner.fork(new ((Zone as any)['TaskTrackingZoneSpec'] as any)());
}
if (enableLongStackTrace && (Zone as any)['longStackTraceZoneSpec']) {
self._inner = self._inner.fork((Zone as any)['longStackTraceZoneSpec']);
}
// if shouldCoalesceRunChangeDetection is true, all tasks including event tasks will be
// coalesced, so shouldCoalesceEventChangeDetection option is not necessary and can be skipped.
self.shouldCoalesceEventChangeDetection =
!shouldCoalesceRunChangeDetection && shouldCoalesceEventChangeDetection;
self.shouldCoalesceRunChangeDetection = shouldCoalesceRunChangeDetection;
self.callbackScheduled = false;
self.scheduleInRootZone = scheduleInRootZone;
forkInnerZoneWithAngularBehavior(self);
}
/**
This method checks whether the method call happens within an Angular Zone instance.
*/
static isInAngularZone(): boolean {
// Zone needs to be checked, because this method might be called even when NoopNgZone is used.
return typeof Zone !== 'undefined' && Zone.current.get(isAngularZoneProperty) === true;
}
/**
Assures that the method is called within the Angular Zone, otherwise throws an error.
*/
static assertInAngularZone(): void {
if (!NgZone.isInAngularZone()) {
throw new RuntimeError(
RuntimeErrorCode.UNEXPECTED_ZONE_STATE,
ngDevMode && 'Expected to be in Angular Zone, but it is not!',
);
}
}
/**
Assures that the method is called outside of the Angular Zone, otherwise throws an error.
*/
static assertNotInAngularZone(): void {
if (NgZone.isInAngularZone()) {
throw new RuntimeError(
RuntimeErrorCode.UNEXPECTED_ZONE_STATE,
ngDevMode && 'Expected to not be in Angular Zone, but it is!',
);
}
}
/**
* Executes the `fn` function synchronously within the Angular zone and returns value returned by
* the function.
*
* Running functions via `run` allows you to reenter Angular zone from a task that was executed
* outside of the Angular zone (typically started via {@link #runOutsideAngular}).
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* within the Angular zone.
*
* If a synchronous error happens it will be rethrown and not reported via `onError`.
*/
run<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any[]): T {
return (this as any as NgZonePrivate)._inner.run(fn, applyThis, applyArgs);
}
/**
* Executes the `fn` function synchronously within the Angular zone as a task and returns value
* returned by the function.
*
* Running functions via `run` allows you to reenter Angular zone from a task that was executed
* outside of the Angular zone (typically started via {@link #runOutsideAngular}).
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* within the Angular zone.
*
* If a synchronous error happens it will be rethrown and not reported via `onError`.
*/
runTask<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any[], name?: string): T {
const zone = (this as any as NgZonePrivate)._inner;
const task = zone.scheduleEventTask('NgZoneEvent: ' + name, fn, EMPTY_PAYLOAD, noop, noop);
try {
return zone.runTask(task, applyThis, applyArgs);
} finally {
zone.cancelTask(task);
}
}
/**
* Same as `run`, except that synchronous errors are caught and forwarded via `onError` and not
* rethrown.
*/
runGuarded<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any[]): T {
return (this as any as NgZonePrivate)._inner.runGuarded(fn, applyThis, applyArgs);
}
/**
* Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
* the function.
*
* Running functions via {@link #runOutsideAngular} allows you to escape Angular's zone and do
* work that
* doesn't trigger Angular change-detection or is subject to Angular's error handling.
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* outside of the Angular zone.
*
* Use {@link #run} to reenter the Angular zone and do work that updates the application model.
*/
runOutsideAngular<T>(fn: (...args: any[]) => T): T {
return (this as any as NgZonePrivate)._outer.run(fn);
}
}
const EMPTY_PAYLOAD = {}; | {
"end_byte": 10149,
"start_byte": 3238,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/zone/ng_zone.ts"
} |
angular/packages/core/src/zone/ng_zone.ts_10151_18384 | export interface NgZonePrivate extends NgZone {
_outer: Zone;
_inner: Zone;
_nesting: number;
_hasPendingMicrotasks: boolean;
hasPendingMacrotasks: boolean;
hasPendingMicrotasks: boolean;
callbackScheduled: boolean;
/**
* A flag to indicate if NgZone is currently inside
* checkStable and to prevent re-entry. The flag is
* needed because it is possible to invoke the change
* detection from within change detection leading to
* incorrect behavior.
*
* For detail, please refer here,
* https://github.com/angular/angular/pull/40540
*/
isCheckStableRunning: boolean;
isStable: boolean;
/**
* Optionally specify coalescing event change detections or not.
* Consider the following case.
*
* <div (click)="doSomething()">
* <button (click)="doSomethingElse()"></button>
* </div>
*
* When button is clicked, because of the event bubbling, both
* event handlers will be called and 2 change detections will be
* triggered. We can coalesce such kind of events to trigger
* change detection only once.
*
* By default, this option will be false. So the events will not be
* coalesced and the change detection will be triggered multiple times.
* And if this option be set to true, the change detection will be
* triggered async by scheduling it in an animation frame. So in the case above,
* the change detection will only be trigged once.
*/
shouldCoalesceEventChangeDetection: boolean;
/**
* Optionally specify if `NgZone#run()` method invocations should be coalesced
* into a single change detection.
*
* Consider the following case.
*
* for (let i = 0; i < 10; i ++) {
* ngZone.run(() => {
* // do something
* });
* }
*
* This case triggers the change detection multiple times.
* With ngZoneRunCoalescing options, all change detections in an event loops trigger only once.
* In addition, the change detection executes in requestAnimation.
*
*/
shouldCoalesceRunChangeDetection: boolean;
/**
* Whether to schedule the coalesced change detection in the root zone
*/
scheduleInRootZone: boolean;
}
function checkStable(zone: NgZonePrivate) {
// TODO: @JiaLiPassion, should check zone.isCheckStableRunning to prevent
// re-entry. The case is:
//
// @Component({...})
// export class AppComponent {
// constructor(private ngZone: NgZone) {
// this.ngZone.onStable.subscribe(() => {
// this.ngZone.run(() => console.log('stable'););
// });
// }
//
// The onStable subscriber run another function inside ngZone
// which causes `checkStable()` re-entry.
// But this fix causes some issues in g3, so this fix will be
// launched in another PR.
if (zone._nesting == 0 && !zone.hasPendingMicrotasks && !zone.isStable) {
try {
zone._nesting++;
zone.onMicrotaskEmpty.emit(null);
} finally {
zone._nesting--;
if (!zone.hasPendingMicrotasks) {
try {
zone.runOutsideAngular(() => zone.onStable.emit(null));
} finally {
zone.isStable = true;
}
}
}
}
}
function delayChangeDetectionForEvents(zone: NgZonePrivate) {
/**
* We also need to check _nesting here
* Consider the following case with shouldCoalesceRunChangeDetection = true
*
* ngZone.run(() => {});
* ngZone.run(() => {});
*
* We want the two `ngZone.run()` only trigger one change detection
* when shouldCoalesceRunChangeDetection is true.
* And because in this case, change detection run in async way(requestAnimationFrame),
* so we also need to check the _nesting here to prevent multiple
* change detections.
*/
if (zone.isCheckStableRunning || zone.callbackScheduled) {
return;
}
zone.callbackScheduled = true;
function scheduleCheckStable() {
scheduleCallbackWithRafRace(() => {
zone.callbackScheduled = false;
updateMicroTaskStatus(zone);
zone.isCheckStableRunning = true;
checkStable(zone);
zone.isCheckStableRunning = false;
});
}
if (zone.scheduleInRootZone) {
Zone.root.run(() => {
scheduleCheckStable();
});
} else {
zone._outer.run(() => {
scheduleCheckStable();
});
}
updateMicroTaskStatus(zone);
}
function forkInnerZoneWithAngularBehavior(zone: NgZonePrivate) {
const delayChangeDetectionForEventsDelegate = () => {
delayChangeDetectionForEvents(zone);
};
const instanceId = ngZoneInstanceId++;
zone._inner = zone._inner.fork({
name: 'angular',
properties: <any>{
[isAngularZoneProperty]: true,
[angularZoneInstanceIdProperty]: instanceId,
[angularZoneInstanceIdProperty + instanceId]: true,
},
onInvokeTask: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
task: Task,
applyThis: any,
applyArgs: any,
): any => {
// Prevent triggering change detection when the flag is detected.
if (shouldBeIgnoredByZone(applyArgs)) {
return delegate.invokeTask(target, task, applyThis, applyArgs);
}
try {
onEnter(zone);
return delegate.invokeTask(target, task, applyThis, applyArgs);
} finally {
if (
(zone.shouldCoalesceEventChangeDetection && task.type === 'eventTask') ||
zone.shouldCoalesceRunChangeDetection
) {
delayChangeDetectionForEventsDelegate();
}
onLeave(zone);
}
},
onInvoke: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
callback: Function,
applyThis: any,
applyArgs?: any[],
source?: string,
): any => {
try {
onEnter(zone);
return delegate.invoke(target, callback, applyThis, applyArgs, source);
} finally {
if (
zone.shouldCoalesceRunChangeDetection &&
// Do not delay change detection when the task is the scheduler's tick.
// We need to synchronously trigger the stability logic so that the
// zone-based scheduler can prevent a duplicate ApplicationRef.tick
// by first checking if the scheduler tick is running. This does seem a bit roundabout,
// but we _do_ still want to trigger all the correct events when we exit the zone.run
// (`onMicrotaskEmpty` and `onStable` _should_ emit; developers can have code which
// relies on these events happening after change detection runs).
// Note: `zone.callbackScheduled` is already in delayChangeDetectionForEventsDelegate
// but is added here as well to prevent reads of applyArgs when not necessary
!zone.callbackScheduled &&
!isSchedulerTick(applyArgs)
) {
delayChangeDetectionForEventsDelegate();
}
onLeave(zone);
}
},
onHasTask: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
hasTaskState: HasTaskState,
) => {
delegate.hasTask(target, hasTaskState);
if (current === target) {
// We are only interested in hasTask events which originate from our zone
// (A child hasTask event is not interesting to us)
if (hasTaskState.change == 'microTask') {
zone._hasPendingMicrotasks = hasTaskState.microTask;
updateMicroTaskStatus(zone);
checkStable(zone);
} else if (hasTaskState.change == 'macroTask') {
zone.hasPendingMacrotasks = hasTaskState.macroTask;
}
}
},
onHandleError: (delegate: ZoneDelegate, current: Zone, target: Zone, error: any): boolean => {
delegate.handleError(target, error);
zone.runOutsideAngular(() => zone.onError.emit(error));
return false;
},
});
}
function updateMicroTaskStatus(zone: NgZonePrivate) {
if (
zone._hasPendingMicrotasks ||
((zone.shouldCoalesceEventChangeDetection || zone.shouldCoalesceRunChangeDetection) &&
zone.callbackScheduled === true)
) {
zone.hasPendingMicrotasks = true;
} else {
zone.hasPendingMicrotasks = false;
}
}
function onEnter(zone: NgZonePrivate) {
zone._nesting++;
if (zone.isStable) {
zone.isStable = false;
zone.onUnstable.emit(null);
}
} | {
"end_byte": 18384,
"start_byte": 10151,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/zone/ng_zone.ts"
} |
angular/packages/core/src/zone/ng_zone.ts_18386_20564 | function onLeave(zone: NgZonePrivate) {
zone._nesting--;
checkStable(zone);
}
/**
* Provides a noop implementation of `NgZone` which does nothing. This zone requires explicit calls
* to framework to perform rendering.
*/
export class NoopNgZone implements NgZone {
readonly hasPendingMicrotasks = false;
readonly hasPendingMacrotasks = false;
readonly isStable = true;
readonly onUnstable = new EventEmitter<any>();
readonly onMicrotaskEmpty = new EventEmitter<any>();
readonly onStable = new EventEmitter<any>();
readonly onError = new EventEmitter<any>();
run<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any): T {
return fn.apply(applyThis, applyArgs);
}
runGuarded<T>(fn: (...args: any[]) => any, applyThis?: any, applyArgs?: any): T {
return fn.apply(applyThis, applyArgs);
}
runOutsideAngular<T>(fn: (...args: any[]) => T): T {
return fn();
}
runTask<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any, name?: string): T {
return fn.apply(applyThis, applyArgs);
}
}
function shouldBeIgnoredByZone(applyArgs: unknown): boolean {
return hasApplyArgsData(applyArgs, '__ignore_ng_zone__');
}
function isSchedulerTick(applyArgs: unknown): boolean {
return hasApplyArgsData(applyArgs, '__scheduler_tick__');
}
function hasApplyArgsData(applyArgs: unknown, key: string) {
if (!Array.isArray(applyArgs)) {
return false;
}
// We should only ever get 1 arg passed through to invokeTask.
// Short circuit here incase that behavior changes.
if (applyArgs.length !== 1) {
return false;
}
return applyArgs[0]?.data?.[key] === true;
}
// Set of options recognized by the NgZone.
export interface InternalNgZoneOptions {
enableLongStackTrace?: boolean;
shouldCoalesceEventChangeDetection?: boolean;
shouldCoalesceRunChangeDetection?: boolean;
scheduleInRootZone?: boolean;
}
export function getNgZone(
ngZoneToUse: NgZone | 'zone.js' | 'noop' = 'zone.js',
options: InternalNgZoneOptions,
): NgZone {
if (ngZoneToUse === 'noop') {
return new NoopNgZone();
}
if (ngZoneToUse === 'zone.js') {
return new NgZone(options);
}
return ngZoneToUse;
} | {
"end_byte": 20564,
"start_byte": 18386,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/zone/ng_zone.ts"
} |
angular/packages/core/src/internal/README.md_0_110 | Contains utilities exposed specifically for g3-internal functionality.
These APIs are not considered public.
| {
"end_byte": 110,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/internal/README.md"
} |
angular/packages/core/src/internal/get_closest_component_name.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 {ComponentDef} from '../render3';
import {readPatchedLView} from '../render3/context_discovery';
import {isComponentHost, isLContainer, isLView} from '../render3/interfaces/type_checks';
import {HEADER_OFFSET, HOST, TVIEW} from '../render3/interfaces/view';
import {getTNode} from '../render3/util/view_utils';
/**
* Gets the class name of the closest component to a node.
* Warning! this function will return minified names if the name of the component is minified. The
* consumer of the function is responsible for resolving the minified name to its original name.
* @param node Node from which to start the search.
*/
export function getClosestComponentName(node: Node): string | null {
let currentNode = node as Node | null;
while (currentNode) {
const lView = readPatchedLView(currentNode);
if (lView !== null) {
for (let i = HEADER_OFFSET; i < lView.length; i++) {
const current = lView[i];
if ((!isLView(current) && !isLContainer(current)) || current[HOST] !== currentNode) {
continue;
}
const tView = lView[TVIEW];
const tNode = getTNode(tView, i);
if (isComponentHost(tNode)) {
const def = tView.data[tNode.directiveStart + tNode.componentOffset] as ComponentDef<{}>;
const name = def.debugInfo?.className || def.type.name;
// Note: the name may be an empty string if the class name is
// dropped due to minification. In such cases keep going up the tree.
if (name) {
return name;
} else {
break;
}
}
}
}
currentNode = currentNode.parentNode;
}
return null;
}
| {
"end_byte": 1889,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/internal/get_closest_component_name.ts"
} |
angular/packages/core/src/render/api.ts_0_1958 | /**
* @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 {isLView} from '../render3/interfaces/type_checks';
import {RENDERER} from '../render3/interfaces/view';
import {getCurrentTNode, getLView} from '../render3/state';
import {getComponentLViewByIndex} from '../render3/util/view_utils';
import {RendererStyleFlags2, RendererType2} from './api_flags';
/**
* Creates and initializes a custom renderer that implements the `Renderer2` base class.
*
* @publicApi
*/
export abstract class RendererFactory2 {
/**
* Creates and initializes a custom renderer for a host DOM element.
* @param hostElement The element to render.
* @param type The base class to implement.
* @returns The new custom renderer instance.
*/
abstract createRenderer(hostElement: any, type: RendererType2 | null): Renderer2;
/**
* A callback invoked when rendering has begun.
*/
abstract begin?(): void;
/**
* A callback invoked when rendering has completed.
*/
abstract end?(): void;
/**
* Use with animations test-only mode. Notifies the test when rendering has completed.
* @returns The asynchronous result of the developer-defined function.
*/
abstract whenRenderingDone?(): Promise<any>;
}
/**
* Extend this base class to implement custom rendering. By default, Angular
* renders a template into DOM. You can use custom rendering to intercept
* rendering calls, or to render to something other than DOM.
*
* Create your custom renderer using `RendererFactory2`.
*
* Use a custom renderer to bypass Angular's templating and
* make custom UI changes that can't be expressed declaratively.
* For example if you need to set a property or an attribute whose name is
* not statically known, use the `setProperty()` or
* `setAttribute()` method.
*
* @publicApi
*/ | {
"end_byte": 1958,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render/api.ts"
} |
angular/packages/core/src/render/api.ts_1959_9561 | export abstract class Renderer2 {
/**
* Use to store arbitrary developer-defined data on a renderer instance,
* as an object containing key-value pairs.
* This is useful for renderers that delegate to other renderers.
*/
abstract get data(): {[key: string]: any};
/**
* Implement this callback to destroy the renderer or the host element.
*/
abstract destroy(): void;
/**
* Implement this callback to create an instance of the host element.
* @param name An identifying name for the new element, unique within the namespace.
* @param namespace The namespace for the new element.
* @returns The new element.
*/
abstract createElement(name: string, namespace?: string | null): any;
/**
* Implement this callback to add a comment to the DOM of the host element.
* @param value The comment text.
* @returns The modified element.
*/
abstract createComment(value: string): any;
/**
* Implement this callback to add text to the DOM of the host element.
* @param value The text string.
* @returns The modified element.
*/
abstract createText(value: string): any;
/**
* If null or undefined, the view engine won't call it.
* This is used as a performance optimization for production mode.
*/
destroyNode: ((node: any) => void) | null = null;
/**
* Appends a child to a given parent node in the host element DOM.
* @param parent The parent node.
* @param newChild The new child node.
*/
abstract appendChild(parent: any, newChild: any): void;
/**
* Implement this callback to insert a child node at a given position in a parent node
* in the host element DOM.
* @param parent The parent node.
* @param newChild The new child nodes.
* @param refChild The existing child node before which `newChild` is inserted.
* @param isMove Optional argument which signifies if the current `insertBefore` is a result of a
* move. Animation uses this information to trigger move animations. In the past the Animation
* would always assume that any `insertBefore` is a move. This is not strictly true because
* with runtime i18n it is possible to invoke `insertBefore` as a result of i18n and it should
* not trigger an animation move.
*/
abstract insertBefore(parent: any, newChild: any, refChild: any, isMove?: boolean): void;
/**
* Implement this callback to remove a child node from the host element's DOM.
* @param parent The parent node.
* @param oldChild The child node to remove.
* @param isHostElement Optionally signal to the renderer whether this element is a host element
* or not
*/
abstract removeChild(parent: any, oldChild: any, isHostElement?: boolean): void;
/**
* Implement this callback to prepare an element to be bootstrapped
* as a root element, and return the element instance.
* @param selectorOrNode The DOM element.
* @param preserveContent Whether the contents of the root element
* should be preserved, or cleared upon bootstrap (default behavior).
* Use with `ViewEncapsulation.ShadowDom` to allow simple native
* content projection via `<slot>` elements.
* @returns The root element.
*/
abstract selectRootElement(selectorOrNode: string | any, preserveContent?: boolean): any;
/**
* Implement this callback to get the parent of a given node
* in the host element's DOM.
* @param node The child node to query.
* @returns The parent node, or null if there is no parent.
* This is because the check is synchronous,
* and the caller can't rely on checking for null.
*/
abstract parentNode(node: any): any;
/**
* Implement this callback to get the next sibling node of a given node
* in the host element's DOM.
* @returns The sibling node, or null if there is no sibling.
* This is because the check is synchronous,
* and the caller can't rely on checking for null.
*/
abstract nextSibling(node: any): any;
/**
* Implement this callback to set an attribute value for an element in the DOM.
* @param el The element.
* @param name The attribute name.
* @param value The new value.
* @param namespace The namespace.
*/
abstract setAttribute(el: any, name: string, value: string, namespace?: string | null): void;
/**
* Implement this callback to remove an attribute from an element in the DOM.
* @param el The element.
* @param name The attribute name.
* @param namespace The namespace.
*/
abstract removeAttribute(el: any, name: string, namespace?: string | null): void;
/**
* Implement this callback to add a class to an element in the DOM.
* @param el The element.
* @param name The class name.
*/
abstract addClass(el: any, name: string): void;
/**
* Implement this callback to remove a class from an element in the DOM.
* @param el The element.
* @param name The class name.
*/
abstract removeClass(el: any, name: string): void;
/**
* Implement this callback to set a CSS style for an element in the DOM.
* @param el The element.
* @param style The name of the style.
* @param value The new value.
* @param flags Flags for style variations. No flags are set by default.
*/
abstract setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void;
/**
* Implement this callback to remove the value from a CSS style for an element in the DOM.
* @param el The element.
* @param style The name of the style.
* @param flags Flags for style variations to remove, if set. ???
*/
abstract removeStyle(el: any, style: string, flags?: RendererStyleFlags2): void;
/**
* Implement this callback to set the value of a property of an element in the DOM.
* @param el The element.
* @param name The property name.
* @param value The new value.
*/
abstract setProperty(el: any, name: string, value: any): void;
/**
* Implement this callback to set the value of a node in the host element.
* @param node The node.
* @param value The new value.
*/
abstract setValue(node: any, value: string): void;
/**
* Implement this callback to start an event listener.
* @param target The context in which to listen for events. Can be
* the entire window or document, the body of the document, or a specific
* DOM element.
* @param eventName The event to listen for.
* @param callback A handler function to invoke when the event occurs.
* @returns An "unlisten" function for disposing of this handler.
*/
abstract listen(
target: 'window' | 'document' | 'body' | any,
eventName: string,
callback: (event: any) => boolean | void,
): () => void;
/**
* @internal
* @nocollapse
*/
static __NG_ELEMENT_ID__: () => Renderer2 = () => injectRenderer2();
}
/** Injects a Renderer2 for the current component. */
export function injectRenderer2(): Renderer2 {
// We need the Renderer to be based on the component that it's being injected into, however since
// DI happens before we've entered its view, `getLView` will return the parent view instead.
const lView = getLView();
const tNode = getCurrentTNode()!;
const nodeAtIndex = getComponentLViewByIndex(tNode.index, lView);
return (isLView(nodeAtIndex) ? nodeAtIndex : lView)[RENDERER] as Renderer2;
}
/**
* This enum is meant to be used by `ɵtype` properties of the different renderers implemented
* by the framework
*
* We choose to not add `ɵtype` to `Renderer2` to no expose it to the public API.
*/
export const enum AnimationRendererType {
Regular = 0,
Delegated = 1,
}
| {
"end_byte": 9561,
"start_byte": 1959,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render/api.ts"
} |
angular/packages/core/src/render/api_flags.ts_0_2158 | /**
* @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 {ViewEncapsulation} from '../metadata/view';
/**
* Used by `RendererFactory2` to associate custom rendering data and styles
* with a rendering implementation.
* @publicApi
*/
export interface RendererType2 {
/**
* A unique identifying string for the new renderer, used when creating
* unique styles for encapsulation.
*/
id: string;
/**
* The view encapsulation type, which determines how styles are applied to
* DOM elements. One of
* - `Emulated` (default): Emulate native scoping of styles.
* - `Native`: Use the native encapsulation mechanism of the renderer.
* - `ShadowDom`: Use modern [Shadow
* DOM](https://w3c.github.io/webcomponents/spec/shadow/) and
* create a ShadowRoot for component's host element.
* - `None`: Do not provide any template or style encapsulation.
*/
encapsulation: ViewEncapsulation;
/**
* Defines CSS styles to be stored on a renderer instance.
*/
styles: string[];
/**
* Defines arbitrary developer-defined data to be stored on a renderer instance.
* This is useful for renderers that delegate to other renderers.
*/
data: {[kind: string]: any};
/**
* A function added by the {@link ɵɵExternalStylesFeature} and used by the framework to create
* the list of external runtime style URLs.
*/
getExternalStyles?: ((encapsulationId?: string) => string[]) | null;
}
/**
* Flags for renderer-specific style modifiers.
* @publicApi
*/
export enum RendererStyleFlags2 {
// TODO(misko): This needs to be refactored into a separate file so that it can be imported from
// `node_manipulation.ts` Currently doing the import cause resolution order to change and fails
// the tests. The work around is to have hard coded value in `node_manipulation.ts` for now.
/**
* Marks a style as important.
*/
Important = 1 << 0,
/**
* Marks a style as using dash case naming (this-is-dash-case).
*/
DashCase = 1 << 1,
}
| {
"end_byte": 2158,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render/api_flags.ts"
} |
angular/packages/core/src/authoring/queries.ts_0_8114 | /**
* @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 {assertInInjectionContext} from '../di';
import {ProviderToken} from '../di/provider_token';
import {
createMultiResultQuerySignalFn,
createSingleResultOptionalQuerySignalFn,
createSingleResultRequiredQuerySignalFn,
} from '../render3/query_reactive';
import {Signal} from '../render3/reactivity/api';
function viewChildFn<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts?: {read?: ProviderToken<ReadT>; debugName?: string},
): Signal<ReadT | undefined> {
ngDevMode && assertInInjectionContext(viewChild);
return createSingleResultOptionalQuerySignalFn<ReadT>(opts);
}
function viewChildRequiredFn<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts?: {read?: ProviderToken<ReadT>; debugName?: string},
): Signal<ReadT> {
ngDevMode && assertInInjectionContext(viewChild);
return createSingleResultRequiredQuerySignalFn<ReadT>(opts);
}
/**
* Type of the `viewChild` function. The viewChild function creates a singular view query.
*
* It is a special function that also provides access to required query results via the `.required`
* property.
*
* @publicAPI
* @docsPrivate Ignored because `viewChild` is the canonical API entry.
*/
export interface ViewChildFunction {
/**
* Initializes a view child query. Consider using `viewChild.required` for queries that should
* always match.
*
* @publicAPI
*/
<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts: {
read: ProviderToken<ReadT>;
debugName?: string;
},
): Signal<ReadT | undefined>;
<LocatorT>(
locator: ProviderToken<LocatorT> | string,
opts?: {
debugName?: string;
},
): Signal<LocatorT | undefined>;
/**
* Initializes a view child query that is expected to always match an element.
*
* @publicAPI
*/
required: {
<LocatorT>(
locator: ProviderToken<LocatorT> | string,
opts?: {
debugName?: string;
},
): Signal<LocatorT>;
<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts: {
read: ProviderToken<ReadT>;
debugName?: string;
},
): Signal<ReadT>;
};
}
/**
* Initializes a view child query.
*
* Consider using `viewChild.required` for queries that should always match.
*
* @usageNotes
* Create a child query in your component by declaring a
* class field and initializing it with the `viewChild()` function.
*
* ```ts
* @Component({template: '<div #el></div><my-component #cmp />'})
* export class TestComponent {
* divEl = viewChild<ElementRef>('el'); // Signal<ElementRef|undefined>
* divElRequired = viewChild.required<ElementRef>('el'); // Signal<ElementRef>
* cmp = viewChild(MyComponent); // Signal<MyComponent|undefined>
* cmpRequired = viewChild.required(MyComponent); // Signal<MyComponent>
* }
* ```
*
* @publicAPI
* @initializerApiFunction
*/
export const viewChild: ViewChildFunction = (() => {
// Note: This may be considered a side-effect, but nothing will depend on
// this assignment, unless this `viewChild` constant export is accessed. It's a
// self-contained side effect that is local to the user facing `viewChild` export.
(viewChildFn as any).required = viewChildRequiredFn;
return viewChildFn as typeof viewChildFn & {required: typeof viewChildRequiredFn};
})();
export function viewChildren<LocatorT>(
locator: ProviderToken<LocatorT> | string,
opts?: {debugName?: string},
): Signal<ReadonlyArray<LocatorT>>;
export function viewChildren<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts: {
read: ProviderToken<ReadT>;
debugName?: string;
},
): Signal<ReadonlyArray<ReadT>>;
/**
* Initializes a view children query.
*
* Query results are represented as a signal of a read-only collection containing all matched
* elements.
*
* @usageNotes
* Create a children query in your component by declaring a
* class field and initializing it with the `viewChildren()` function.
*
* ```ts
* @Component({...})
* export class TestComponent {
* divEls = viewChildren<ElementRef>('el'); // Signal<ReadonlyArray<ElementRef>>
* }
* ```
*
* @initializerApiFunction
* @publicAPI
*/
export function viewChildren<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts?: {
read?: ProviderToken<ReadT>;
debugName?: string;
},
): Signal<ReadonlyArray<ReadT>> {
ngDevMode && assertInInjectionContext(viewChildren);
return createMultiResultQuerySignalFn<ReadT>(opts);
}
export function contentChildFn<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts?: {
descendants?: boolean;
read?: ProviderToken<ReadT>;
debugName?: string;
},
): Signal<ReadT | undefined> {
ngDevMode && assertInInjectionContext(contentChild);
return createSingleResultOptionalQuerySignalFn<ReadT>(opts);
}
function contentChildRequiredFn<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts?: {
descendants?: boolean;
read?: ProviderToken<ReadT>;
debugName?: string;
},
): Signal<ReadT> {
ngDevMode && assertInInjectionContext(contentChildren);
return createSingleResultRequiredQuerySignalFn<ReadT>(opts);
}
/**
* Type of the `contentChild` function.
*
* The contentChild function creates a singular content query. It is a special function that also
* provides access to required query results via the `.required` property.
*
* @publicAPI
* @docsPrivate Ignored because `contentChild` is the canonical API entry.
*/
export interface ContentChildFunction {
/**
* Initializes a content child query.
*
* Consider using `contentChild.required` for queries that should always match.
* @publicAPI
*/
<LocatorT>(
locator: ProviderToken<LocatorT> | string,
opts?: {
descendants?: boolean;
read?: undefined;
debugName?: string;
},
): Signal<LocatorT | undefined>;
<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts: {
descendants?: boolean;
read: ProviderToken<ReadT>;
debugName?: string;
},
): Signal<ReadT | undefined>;
/**
* Initializes a content child query that is always expected to match.
*/
required: {
<LocatorT>(
locator: ProviderToken<LocatorT> | string,
opts?: {
descendants?: boolean;
read?: undefined;
debugName?: string;
},
): Signal<LocatorT>;
<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts: {
descendants?: boolean;
read: ProviderToken<ReadT>;
debugName?: string;
},
): Signal<ReadT>;
};
}
/**
* Initializes a content child query. Consider using `contentChild.required` for queries that should
* always match.
*
* @usageNotes
* Create a child query in your component by declaring a
* class field and initializing it with the `contentChild()` function.
*
* ```ts
* @Component({...})
* export class TestComponent {
* headerEl = contentChild<ElementRef>('h'); // Signal<ElementRef|undefined>
* headerElElRequired = contentChild.required<ElementRef>('h'); // Signal<ElementRef>
* header = contentChild(MyHeader); // Signal<MyHeader|undefined>
* headerRequired = contentChild.required(MyHeader); // Signal<MyHeader>
* }
* ```
*
* @initializerApiFunction
* @publicAPI
*/
export const contentChild: ContentChildFunction = (() => {
// Note: This may be considered a side-effect, but nothing will depend on
// this assignment, unless this `viewChild` constant export is accessed. It's a
// self-contained side effect that is local to the user facing `viewChild` export.
(contentChildFn as any).required = contentChildRequiredFn;
return contentChildFn as typeof contentChildFn & {required: typeof contentChildRequiredFn};
})(); | {
"end_byte": 8114,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring/queries.ts"
} |
angular/packages/core/src/authoring/queries.ts_8116_9361 | export function contentChildren<LocatorT>(
locator: ProviderToken<LocatorT> | string,
opts?: {
descendants?: boolean;
read?: undefined;
debugName?: string;
},
): Signal<ReadonlyArray<LocatorT>>;
export function contentChildren<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts: {
descendants?: boolean;
read: ProviderToken<ReadT>;
debugName?: string;
},
): Signal<ReadonlyArray<ReadT>>;
/**
* Initializes a content children query.
*
* Query results are represented as a signal of a read-only collection containing all matched
* elements.
*
* @usageNotes
* Create a children query in your component by declaring a
* class field and initializing it with the `contentChildren()` function.
*
* ```ts
* @Component({...})
* export class TestComponent {
* headerEl = contentChildren<ElementRef>('h'); // Signal<ReadonlyArray<ElementRef>>
* }
* ```
*
* @initializerApiFunction
* @publicAPI
*/
export function contentChildren<LocatorT, ReadT>(
locator: ProviderToken<LocatorT> | string,
opts?: {
descendants?: boolean;
read?: ProviderToken<ReadT>;
debugName?: string;
},
): Signal<ReadonlyArray<ReadT>> {
return createMultiResultQuerySignalFn<ReadT>(opts);
} | {
"end_byte": 9361,
"start_byte": 8116,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring/queries.ts"
} |
angular/packages/core/src/authoring/input/input.ts_0_5168 | /**
* @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 {assertInInjectionContext} from '../../di';
import {
createInputSignal,
InputOptions,
InputOptionsWithoutTransform,
InputOptionsWithTransform,
InputSignal,
InputSignalWithTransform,
} from './input_signal';
import {REQUIRED_UNSET_VALUE} from './input_signal_node';
export function inputFunction<ReadT, WriteT>(
initialValue?: ReadT,
opts?: InputOptions<ReadT, WriteT>,
): InputSignalWithTransform<ReadT | undefined, WriteT> {
ngDevMode && assertInInjectionContext(input);
return createInputSignal(initialValue, opts);
}
export function inputRequiredFunction<ReadT, WriteT = ReadT>(
opts?: InputOptions<ReadT, WriteT>,
): InputSignalWithTransform<ReadT, WriteT> {
ngDevMode && assertInInjectionContext(input);
return createInputSignal(REQUIRED_UNSET_VALUE as never, opts);
}
/**
* The `input` function allows declaration of inputs in directives and
* components.
*
* The function exposes an API for also declaring required inputs via the
* `input.required` function.
*
* @publicAPI
* @docsPrivate Ignored because `input` is the canonical API entry.
*/
export interface InputFunction {
/**
* Initializes an input of type `T` with an initial value of `undefined`.
* Angular will implicitly use `undefined` as initial value.
*/
<T>(): InputSignal<T | undefined>;
/** Declares an input of type `T` with an explicit initial value. */
<T>(initialValue: T, opts?: InputOptionsWithoutTransform<T>): InputSignal<T>;
/** Declares an input of type `T|undefined` without an initial value, but with input options */
<T>(initialValue: undefined, opts: InputOptionsWithoutTransform<T>): InputSignal<T | undefined>;
/**
* Declares an input of type `T` with an initial value and a transform
* function.
*
* The input accepts values of type `TransformT` and the given
* transform function will transform the value to type `T`.
*/
<T, TransformT>(
initialValue: T,
opts: InputOptionsWithTransform<T, TransformT>,
): InputSignalWithTransform<T, TransformT>;
/**
* Declares an input of type `T|undefined` without an initial value and with a transform
* function.
*
* The input accepts values of type `TransformT` and the given
* transform function will transform the value to type `T|undefined`.
*/ <T, TransformT>(
initialValue: undefined,
opts: InputOptionsWithTransform<T | undefined, TransformT>,
): InputSignalWithTransform<T | undefined, TransformT>;
/**
* Initializes a required input.
*
* Consumers of your directive/component need to bind to this
* input. If unset, a compile time error will be reported.
*
* @publicAPI
*/
required: {
/** Declares a required input of type `T`. */
<T>(opts?: InputOptionsWithoutTransform<T>): InputSignal<T>;
/**
* Declares a required input of type `T` with a transform function.
*
* The input accepts values of type `TransformT` and the given
* transform function will transform the value to type `T`.
*/
<T, TransformT>(
opts: InputOptionsWithTransform<T, TransformT>,
): InputSignalWithTransform<T, TransformT>;
};
}
/**
* The `input` function allows declaration of Angular inputs in directives
* and components.
*
* There are two variants of inputs that can be declared:
*
* 1. **Optional inputs** with an initial value.
* 2. **Required inputs** that consumers need to set.
*
* By default, the `input` function will declare optional inputs that
* always have an initial value. Required inputs can be declared
* using the `input.required()` function.
*
* Inputs are signals. The values of an input are exposed as a `Signal`.
* The signal always holds the latest value of the input that is bound
* from the parent.
*
* @usageNotes
* To use signal-based inputs, import `input` from `@angular/core`.
*
* ```
* import {input} from '@angular/core`;
* ```
*
* Inside your component, introduce a new class member and initialize
* it with a call to `input` or `input.required`.
*
* ```ts
* @Component({
* ...
* })
* export class UserProfileComponent {
* firstName = input<string>(); // Signal<string|undefined>
* lastName = input.required<string>(); // Signal<string>
* age = input(0) // Signal<number>
* }
* ```
*
* Inside your component template, you can display values of the inputs
* by calling the signal.
*
* ```html
* <span>{{firstName()}}</span>
* ```
*
* @publicAPI
* @initializerApiFunction
*/
export const input: InputFunction = (() => {
// Note: This may be considered a side-effect, but nothing will depend on
// this assignment, unless this `input` constant export is accessed. It's a
// self-contained side effect that is local to the user facing`input` export.
(inputFunction as any).required = inputRequiredFunction;
return inputFunction as typeof inputFunction & {required: typeof inputRequiredFunction};
})();
| {
"end_byte": 5168,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring/input/input.ts"
} |
angular/packages/core/src/authoring/input/input_signal_node.ts_0_1894 | /**
* @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 {SIGNAL_NODE, SignalNode, signalSetFn} from '@angular/core/primitives/signals';
export const REQUIRED_UNSET_VALUE = /* @__PURE__ */ Symbol('InputSignalNode#UNSET');
/**
* Reactive node type for an input signal. An input signal extends a signal.
* There are special properties to enable transforms and required inputs.
*/
export interface InputSignalNode<T, TransformT> extends SignalNode<T> {
/**
* User-configured transform that will run whenever a new value is applied
* to the input signal node.
*/
transformFn: ((value: TransformT) => T) | undefined;
/**
* Applies a new value to the input signal. Expects transforms to be run
* manually before.
*
* This function is called by the framework runtime code whenever a binding
* changes. The value can in practice be anything at runtime, but for typing
* purposes we assume it's a valid `T` value. Type-checking will enforce that.
*/
applyValueToInputSignal<T, TransformT>(node: InputSignalNode<T, TransformT>, value: T): void;
/**
* A debug name for the input signal. Used in Angular DevTools to identify the signal.
*/
debugName?: string;
}
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
export const INPUT_SIGNAL_NODE: InputSignalNode<unknown, unknown> = /* @__PURE__ */ (() => {
return {
...SIGNAL_NODE,
transformFn: undefined,
applyValueToInputSignal<T, TransformT>(node: InputSignalNode<T, TransformT>, value: T) {
signalSetFn(node, value);
},
};
})();
| {
"end_byte": 1894,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring/input/input_signal_node.ts"
} |
angular/packages/core/src/authoring/input/input_signal.ts_0_4797 | /**
* @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 {producerAccessed, SIGNAL} from '@angular/core/primitives/signals';
import {RuntimeError, RuntimeErrorCode} from '../../errors';
import {Signal} from '../../render3/reactivity/api';
import {INPUT_SIGNAL_NODE, InputSignalNode, REQUIRED_UNSET_VALUE} from './input_signal_node';
/**
* @publicAPI
*
* Options for signal inputs.
*/
export interface InputOptions<T, TransformT> {
/** Optional public name for the input. By default, the class field name is used. */
alias?: string;
/**
* Optional transform that runs whenever a new value is bound. Can be used to
* transform the input value before the input is updated.
*
* The transform function can widen the type of the input. For example, consider
* an input for `disabled`. In practice, as the component author, you want to only
* deal with a boolean, but users may want to bind a string if they just use the
* attribute form to bind to the input via `<my-dir input>`. A transform can then
* handle such string values and convert them to `boolean`. See: {@link booleanAttribute}.
*/
transform?: (v: TransformT) => T;
/**
* A debug name for the input signal. Used in Angular DevTools to identify the signal.
*/
debugName?: string;
}
/**
* Signal input options without the transform option.
*
* @publicAPI
*/
export type InputOptionsWithoutTransform<T> =
// Note: We still keep a notion of `transform` for auto-completion.
Omit<InputOptions<T, T>, 'transform'> & {transform?: undefined};
/**
* Signal input options with the transform option required.
*
* @publicAPI
*/
export type InputOptionsWithTransform<T, TransformT> = Required<
Pick<InputOptions<T, TransformT>, 'transform'>
> &
InputOptions<T, TransformT>;
export const ɵINPUT_SIGNAL_BRAND_READ_TYPE = /* @__PURE__ */ Symbol();
export const ɵINPUT_SIGNAL_BRAND_WRITE_TYPE = /* @__PURE__ */ Symbol();
/**
* `InputSignalWithTransform` represents a special `Signal` for a
* directive/component input with a `transform` function.
*
* Signal inputs with transforms capture an extra generic for their transform write
* type. Transforms can expand the accepted bound values for an input while ensuring
* value retrievals of the signal input are still matching the generic input type.
*
* ```ts
* class MyDir {
* disabled = input(false, {
* transform: (v: string|boolean) => convertToBoolean(v),
* }); // InputSignalWithTransform<boolean, string|boolean>
*
* click() {
* this.disabled() // always returns a `boolean`.
* }
* }
* ```
*
* @see {@link InputSignal} for additional information.
*
* @publicAPI
*/
export interface InputSignalWithTransform<T, TransformT> extends Signal<T> {
[SIGNAL]: InputSignalNode<T, TransformT>;
[ɵINPUT_SIGNAL_BRAND_READ_TYPE]: T;
[ɵINPUT_SIGNAL_BRAND_WRITE_TYPE]: TransformT;
}
/**
* `InputSignal` represents a special `Signal` for a directive/component input.
*
* An input signal is similar to a non-writable signal except that it also
* carries additional type-information for transforms, and that Angular internally
* updates the signal whenever a new value is bound.
*
* @see {@link InputOptionsWithTransform} for inputs with transforms.
*
* @publicAPI
*/
export interface InputSignal<T> extends InputSignalWithTransform<T, T> {}
/**
* Creates an input signal.
*
* @param initialValue The initial value.
* Can be set to {@link REQUIRED_UNSET_VALUE} for required inputs.
* @param options Additional options for the input. e.g. a transform, or an alias.
*/
export function createInputSignal<T, TransformT>(
initialValue: T,
options?: InputOptions<T, TransformT>,
): InputSignalWithTransform<T, TransformT> {
const node: InputSignalNode<T, TransformT> = Object.create(INPUT_SIGNAL_NODE);
node.value = initialValue;
// Perf note: Always set `transformFn` here to ensure that `node` always
// has the same v8 class shape, allowing monomorphic reads on input signals.
node.transformFn = options?.transform;
function inputValueFn() {
// Record that someone looked at this signal.
producerAccessed(node);
if (node.value === REQUIRED_UNSET_VALUE) {
throw new RuntimeError(
RuntimeErrorCode.REQUIRED_INPUT_NO_VALUE,
ngDevMode && 'Input is required but no value is available yet.',
);
}
return node.value;
}
(inputValueFn as any)[SIGNAL] = node;
if (ngDevMode) {
inputValueFn.toString = () => `[Input Signal: ${inputValueFn()}]`;
node.debugName = options?.debugName;
}
return inputValueFn as InputSignalWithTransform<T, TransformT>;
}
| {
"end_byte": 4797,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring/input/input_signal.ts"
} |
angular/packages/core/src/authoring/input/input_type_checking.ts_0_714 | /**
* @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 {InputSignalWithTransform} from './input_signal';
/** Retrieves the write type of an `InputSignal` and `InputSignalWithTransform`. */
export type ɵUnwrapInputSignalWriteType<Field> =
Field extends InputSignalWithTransform<any, infer WriteT> ? WriteT : never;
/**
* Unwraps all `InputSignal`/`InputSignalWithTransform` class fields of
* the given directive.
*/
export type ɵUnwrapDirectiveSignalInputs<Dir, Fields extends keyof Dir> = {
[P in Fields]: ɵUnwrapInputSignalWriteType<Dir[P]>;
};
| {
"end_byte": 714,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring/input/input_type_checking.ts"
} |
angular/packages/core/src/authoring/output/output.ts_0_1709 | /**
* @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 {assertInInjectionContext} from '../../di';
import {OutputEmitterRef} from './output_emitter_ref';
/**
* Options for declaring an output.
*
* @publicAPI
*/
export interface OutputOptions {
alias?: string;
}
/**
* The `output` function allows declaration of Angular outputs in
* directives and components.
*
* You can use outputs to emit values to parent directives and component.
* Parents can subscribe to changes via:
*
* - template event bindings. For example, `(myOutput)="doSomething($event)"`
* - programmatic subscription by using `OutputRef#subscribe`.
*
* @usageNotes
*
* To use `output()`, import the function from `@angular/core`.
*
* ```ts
* import {output} from '@angular/core';
* ```
*
* Inside your component, introduce a new class member and initialize
* it with a call to `output`.
*
* ```ts
* @Directive({
* ...
* })
* export class MyDir {
* nameChange = output<string>(); // OutputEmitterRef<string>
* onClick = output(); // OutputEmitterRef<void>
* }
* ```
*
* You can emit values to consumers of your directive, by using
* the `emit` method from `OutputEmitterRef`.
*
* ```ts
* updateName(newName: string): void {
* this.nameChange.emit(newName);
* }
* ```
* @initializerApiFunction {"showTypesInSignaturePreview": true}
* @publicAPI
*/
export function output<T = void>(opts?: OutputOptions): OutputEmitterRef<T> {
ngDevMode && assertInInjectionContext(output);
return new OutputEmitterRef<T>();
}
| {
"end_byte": 1709,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring/output/output.ts"
} |
angular/packages/core/src/authoring/output/output_ref.ts_0_1394 | /**
* @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 {DestroyRef} from '../../linker/destroy_ref';
/**
* Function that can be used to manually clean up a
* programmatic {@link OutputRef#subscribe} subscription.
*
* Note: Angular will automatically clean up subscriptions
* when the directive/component of the output is destroyed.
*
* @publicAPI
*/
export interface OutputRefSubscription {
unsubscribe(): void;
}
/**
* A reference to an Angular output.
*
* @publicAPI
*/
export interface OutputRef<T> {
/**
* Registers a callback that is invoked whenever the output
* emits a new value of type `T`.
*
* Angular will automatically clean up the subscription when
* the directive/component of the output is destroyed.
*/
subscribe(callback: (value: T) => void): OutputRefSubscription;
/**
* Reference to the `DestroyRef` of the directive/component declaring
* the output. The `DestroyRef` is captured so that helpers like
* the `outputToObservable` can complete the observable upon destroy.
*
* Note: May be `undefined` in cases of `EventEmitter` where
* we do not want to add a dependency on an injection context.
*
* @internal
*/
destroyRef: DestroyRef | undefined;
}
| {
"end_byte": 1394,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring/output/output_ref.ts"
} |
angular/packages/core/src/authoring/output/output_emitter_ref.ts_0_2884 | /**
* @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 {setActiveConsumer} from '@angular/core/primitives/signals';
import {inject} from '../../di/injector_compatibility';
import {ErrorHandler} from '../../error_handler';
import {RuntimeError, RuntimeErrorCode} from '../../errors';
import {DestroyRef} from '../../linker/destroy_ref';
import {OutputRef, OutputRefSubscription} from './output_ref';
/**
* An `OutputEmitterRef` is created by the `output()` function and can be
* used to emit values to consumers of your directive or component.
*
* Consumers of your directive/component can bind to the output and
* subscribe to changes via the bound event syntax. For example:
*
* ```html
* <my-comp (valueChange)="processNewValue($event)" />
* ```
*
* @publicAPI
*/
export class OutputEmitterRef<T> implements OutputRef<T> {
private destroyed = false;
private listeners: Array<(value: T) => void> | null = null;
private errorHandler = inject(ErrorHandler, {optional: true});
/** @internal */
destroyRef: DestroyRef = inject(DestroyRef);
constructor() {
// Clean-up all listeners and mark as destroyed upon destroy.
this.destroyRef.onDestroy(() => {
this.destroyed = true;
this.listeners = null;
});
}
subscribe(callback: (value: T) => void): OutputRefSubscription {
if (this.destroyed) {
throw new RuntimeError(
RuntimeErrorCode.OUTPUT_REF_DESTROYED,
ngDevMode &&
'Unexpected subscription to destroyed `OutputRef`. ' +
'The owning directive/component is destroyed.',
);
}
(this.listeners ??= []).push(callback);
return {
unsubscribe: () => {
const idx = this.listeners?.indexOf(callback);
if (idx !== undefined && idx !== -1) {
this.listeners?.splice(idx, 1);
}
},
};
}
/** Emits a new value to the output. */
emit(value: T): void {
if (this.destroyed) {
throw new RuntimeError(
RuntimeErrorCode.OUTPUT_REF_DESTROYED,
ngDevMode &&
'Unexpected emit for destroyed `OutputRef`. ' +
'The owning directive/component is destroyed.',
);
}
if (this.listeners === null) {
return;
}
const previousConsumer = setActiveConsumer(null);
try {
for (const listenerFn of this.listeners) {
try {
listenerFn(value);
} catch (err: unknown) {
this.errorHandler?.handleError(err);
}
}
} finally {
setActiveConsumer(previousConsumer);
}
}
}
/** Gets the owning `DestroyRef` for the given output. */
export function getOutputDestroyRef(ref: OutputRef<unknown>): DestroyRef | undefined {
return ref.destroyRef;
}
| {
"end_byte": 2884,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring/output/output_emitter_ref.ts"
} |
angular/packages/core/src/authoring/model/model.ts_0_3556 | /**
* @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 {assertInInjectionContext} from '../../di';
import {REQUIRED_UNSET_VALUE} from '../input/input_signal_node';
import {createModelSignal, ModelOptions, ModelSignal} from './model_signal';
export function modelFunction<T>(
initialValue?: T,
opts?: ModelOptions,
): ModelSignal<T | undefined> {
ngDevMode && assertInInjectionContext(model);
return createModelSignal(initialValue, opts);
}
export function modelRequiredFunction<T>(opts?: ModelOptions): ModelSignal<T> {
ngDevMode && assertInInjectionContext(model);
return createModelSignal(REQUIRED_UNSET_VALUE as T, opts);
}
/**
* `model` declares a writeable signal that is exposed as an input/output pair on the containing
* directive. The input name is taken either from the class member or from the `alias` option.
* The output name is generated by taking the input name and appending `Change`.
*
* The function exposes an API for also declaring required models via the
* `model.required` function.
*
* @publicAPI
* @docsPrivate Ignored because `model` is the canonical API entry.
*/
export interface ModelFunction {
/**
* Initializes a model of type `T` with an initial value of `undefined`.
* Angular will implicitly use `undefined` as initial value.
*/
<T>(): ModelSignal<T | undefined>;
/** Initializes a model of type `T` with the given initial value. */
<T>(initialValue: T, opts?: ModelOptions): ModelSignal<T>;
required: {
/**
* Initializes a required model.
*
* Users of your directive/component need to bind to the input side of the model.
* If unset, a compile time error will be reported.
*/
<T>(opts?: ModelOptions): ModelSignal<T>;
};
}
/**
* `model` declares a writeable signal that is exposed as an input/output
* pair on the containing directive.
*
* The input name is taken either from the class member or from the `alias` option.
* The output name is generated by taking the input name and appending `Change`.
*
* @usageNotes
*
* To use `model()`, import the function from `@angular/core`.
*
* ```
* import {model} from '@angular/core`;
* ```
*
* Inside your component, introduce a new class member and initialize
* it with a call to `model` or `model.required`.
*
* ```ts
* @Directive({
* ...
* })
* export class MyDir {
* firstName = model<string>(); // ModelSignal<string|undefined>
* lastName = model.required<string>(); // ModelSignal<string>
* age = model(0); // ModelSignal<number>
* }
* ```
*
* Inside your component template, you can display the value of a `model`
* by calling the signal.
*
* ```html
* <span>{{firstName()}}</span>
* ```
*
* Updating the `model` is equivalent to updating a writable signal.
*
* ```ts
* updateName(newFirstName: string): void {
* this.firstName.set(newFirstName);
* }
* ```
*
* @publicAPI
* @initializerApiFunction
*/
export const model: ModelFunction = (() => {
// Note: This may be considered a side-effect, but nothing will depend on
// this assignment, unless this `model` constant export is accessed. It's a
// self-contained side effect that is local to the user facing `model` export.
(modelFunction as any).required = modelRequiredFunction;
return modelFunction as typeof modelFunction & {required: typeof modelRequiredFunction};
})();
| {
"end_byte": 3556,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring/model/model.ts"
} |
angular/packages/core/src/authoring/model/model_signal.ts_0_3411 | /**
* @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 {producerAccessed, SIGNAL, signalSetFn} from '@angular/core/primitives/signals';
import {RuntimeError, RuntimeErrorCode} from '../../errors';
import {Signal} from '../../render3/reactivity/api';
import {
signalAsReadonlyFn,
WritableSignal,
ɵWRITABLE_SIGNAL,
} from '../../render3/reactivity/signal';
import {
InputSignal,
ɵINPUT_SIGNAL_BRAND_READ_TYPE,
ɵINPUT_SIGNAL_BRAND_WRITE_TYPE,
} from '../input/input_signal';
import {INPUT_SIGNAL_NODE, InputSignalNode, REQUIRED_UNSET_VALUE} from '../input/input_signal_node';
import {OutputEmitterRef} from '../output/output_emitter_ref';
import {OutputRef} from '../output/output_ref';
/**
* @publicAPI
*
* Options for model signals.
*/
export interface ModelOptions {
/**
* Optional public name of the input side of the model. The output side will have the same
* name as the input, but suffixed with `Change`. By default, the class field name is used.
*/
alias?: string;
/**
* A debug name for the model signal. Used in Angular DevTools to identify the signal.
*/
debugName?: string;
}
/**
* `ModelSignal` represents a special `Signal` for a directive/component model field.
*
* A model signal is a writeable signal that can be exposed as an output.
* Whenever its value is updated, it emits to the output.
*
* @publicAPI
*/
export interface ModelSignal<T> extends WritableSignal<T>, InputSignal<T>, OutputRef<T> {
[SIGNAL]: InputSignalNode<T, T>;
}
/**
* Creates a model signal.
*
* @param initialValue The initial value.
* Can be set to {@link REQUIRED_UNSET_VALUE} for required model signals.
* @param options Additional options for the model.
*/
export function createModelSignal<T>(initialValue: T, opts?: ModelOptions): ModelSignal<T> {
const node: InputSignalNode<T, T> = Object.create(INPUT_SIGNAL_NODE);
const emitterRef = new OutputEmitterRef<T>();
node.value = initialValue;
function getter(): T {
producerAccessed(node);
assertModelSet(node.value);
return node.value;
}
getter[SIGNAL] = node;
getter.asReadonly = signalAsReadonlyFn.bind(getter as any) as () => Signal<T>;
// TODO: Should we throw an error when updating a destroyed model?
getter.set = (newValue: T) => {
if (!node.equal(node.value, newValue)) {
signalSetFn(node, newValue);
emitterRef.emit(newValue);
}
};
getter.update = (updateFn: (value: T) => T) => {
assertModelSet(node.value);
getter.set(updateFn(node.value));
};
getter.subscribe = emitterRef.subscribe.bind(emitterRef);
getter.destroyRef = emitterRef.destroyRef;
if (ngDevMode) {
getter.toString = () => `[Model Signal: ${getter()}]`;
node.debugName = opts?.debugName;
}
return getter as typeof getter &
Pick<
ModelSignal<T>,
| typeof ɵINPUT_SIGNAL_BRAND_READ_TYPE
| typeof ɵINPUT_SIGNAL_BRAND_WRITE_TYPE
| typeof ɵWRITABLE_SIGNAL
>;
}
/** Asserts that a model's value is set. */
function assertModelSet(value: unknown): void {
if (value === REQUIRED_UNSET_VALUE) {
throw new RuntimeError(
RuntimeErrorCode.REQUIRED_MODEL_NO_VALUE,
ngDevMode && 'Model is required but no value is available yet.',
);
}
}
| {
"end_byte": 3411,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring/model/model_signal.ts"
} |
angular/packages/core/src/view/provider_flags.ts_0_867 | /**
* @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 default value is when checking the hierarchy for a token.
//
// It means both:
// - the token is not provided by the current injector,
// - only the element injectors should be checked (ie do not check module injectors
//
// mod1
// /
// el1 mod2
// \ /
// el2
//
// When requesting el2.injector.get(token), we should check in the following order and return the
// first found value:
// - el2.injector.get(token, default)
// - el1.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) -> do not check the module
// - mod2.injector.get(token, default)
export const NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR = {};
| {
"end_byte": 867,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/view/provider_flags.ts"
} |
angular/packages/core/src/render3/state.ts_0_7893 | /**
* @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 {InjectFlags} from '../di/interface/injector';
import {
assertDefined,
assertEqual,
assertGreaterThanOrEqual,
assertLessThan,
assertNotEqual,
throwError,
} from '../util/assert';
import {assertLViewOrUndefined, assertTNodeForLView, assertTNodeForTView} from './assert';
import {DirectiveDef} from './interfaces/definition';
import {TNode, TNodeType} from './interfaces/node';
import {
CONTEXT,
DECLARATION_VIEW,
HEADER_OFFSET,
LView,
OpaqueViewState,
T_HOST,
TData,
TVIEW,
TView,
TViewType,
} from './interfaces/view';
import {MATH_ML_NAMESPACE, SVG_NAMESPACE} from './namespaces';
import {getTNode, walkUpViews} from './util/view_utils';
/**
*
*/
interface LFrame {
/**
* Parent LFrame.
*
* This is needed when `leaveView` is called to restore the previous state.
*/
parent: LFrame;
/**
* Child LFrame.
*
* This is used to cache existing LFrames to relieve the memory pressure.
*/
child: LFrame | null;
/**
* State of the current view being processed.
*
* An array of nodes (text, element, container, etc), pipes, their bindings, and
* any local variables that need to be stored between invocations.
*/
lView: LView;
/**
* Current `TView` associated with the `LFrame.lView`.
*
* One can get `TView` from `lFrame[TVIEW]` however because it is so common it makes sense to
* store it in `LFrame` for perf reasons.
*/
tView: TView;
/**
* Used to set the parent property when nodes are created and track query results.
*
* This is used in conjunction with `isParent`.
*/
currentTNode: TNode | null;
/**
* If `isParent` is:
* - `true`: then `currentTNode` points to a parent node.
* - `false`: then `currentTNode` points to previous node (sibling).
*/
isParent: boolean;
/**
* Index of currently selected element in LView.
*
* Used by binding instructions. Updated as part of advance instruction.
*/
selectedIndex: number;
/**
* Current pointer to the binding index.
*/
bindingIndex: number;
/**
* The last viewData retrieved by nextContext().
* Allows building nextContext() and reference() calls.
*
* e.g. const inner = x().$implicit; const outer = x().$implicit;
*/
contextLView: LView | null;
/**
* Store the element depth count. This is used to identify the root elements of the template
* so that we can then attach patch data `LView` to only those elements. We know that those
* are the only places where the patch data could change, this way we will save on number
* of places where tha patching occurs.
*/
elementDepthCount: number;
/**
* Current namespace to be used when creating elements
*/
currentNamespace: string | null;
/**
* The root index from which pure function instructions should calculate their binding
* indices. In component views, this is TView.bindingStartIndex. In a host binding
* context, this is the TView.expandoStartIndex + any dirs/hostVars before the given dir.
*/
bindingRootIndex: number;
/**
* Current index of a View or Content Query which needs to be processed next.
* We iterate over the list of Queries and increment current query index at every step.
*/
currentQueryIndex: number;
/**
* When host binding is executing this points to the directive index.
* `TView.data[currentDirectiveIndex]` is `DirectiveDef`
* `LView[currentDirectiveIndex]` is directive instance.
*/
currentDirectiveIndex: number;
/**
* Are we currently in i18n block as denoted by `ɵɵelementStart` and `ɵɵelementEnd`.
*
* This information is needed because while we are in i18n block all elements must be pre-declared
* in the translation. (i.e. `Hello �#2�World�/#2�!` pre-declares element at `�#2�` location.)
* This allocates `TNodeType.Placeholder` element at location `2`. If translator removes `�#2�`
* from translation than the runtime must also ensure tha element at `2` does not get inserted
* into the DOM. The translation does not carry information about deleted elements. Therefor the
* only way to know that an element is deleted is that it was not pre-declared in the translation.
*
* This flag works by ensuring that elements which are created without pre-declaration
* (`TNodeType.Placeholder`) are not inserted into the DOM render tree. (It does mean that the
* element still gets instantiated along with all of its behavior [directives])
*/
inI18n: boolean;
}
/**
* All implicit instruction state is stored here.
*
* It is useful to have a single object where all of the state is stored as a mental model
* (rather it being spread across many different variables.)
*
* PERF NOTE: Turns out that writing to a true global variable is slower than
* having an intermediate object with properties.
*/
interface InstructionState {
/**
* Current `LFrame`
*
* `null` if we have not called `enterView`
*/
lFrame: LFrame;
/**
* Stores whether directives should be matched to elements.
*
* When template contains `ngNonBindable` then we need to prevent the runtime from matching
* directives on children of that element.
*
* Example:
* ```
* <my-comp my-directive>
* Should match component / directive.
* </my-comp>
* <div ngNonBindable>
* <my-comp my-directive>
* Should not match component / directive because we are in ngNonBindable.
* </my-comp>
* </div>
* ```
*/
bindingsEnabled: boolean;
/**
* Stores the root TNode that has the 'ngSkipHydration' attribute on it for later reference.
*
* Example:
* ```
* <my-comp ngSkipHydration>
* Should reference this root node
* </my-comp>
* ```
*/
skipHydrationRootTNode: TNode | null;
}
const instructionState: InstructionState = {
lFrame: createLFrame(null),
bindingsEnabled: true,
skipHydrationRootTNode: null,
};
export enum CheckNoChangesMode {
Off,
Exhaustive,
OnlyDirtyViews,
}
/**
* In this mode, any changes in bindings will throw an ExpressionChangedAfterChecked error.
*
* Necessary to support ChangeDetectorRef.checkNoChanges().
*
* The `checkNoChanges` function is invoked only in ngDevMode=true and verifies that no unintended
* changes exist in the change detector or its children.
*/
let _checkNoChangesMode: CheckNoChangesMode = 0; /* CheckNoChangesMode.Off */
/**
* Flag used to indicate that we are in the middle running change detection on a view
*
* @see detectChangesInViewWhileDirty
*/
let _isRefreshingViews = false;
/**
* Returns true if the instruction state stack is empty.
*
* Intended to be called from tests only (tree shaken otherwise).
*/
export function specOnlyIsInstructionStateEmpty(): boolean {
return instructionState.lFrame.parent === null;
}
export function getElementDepthCount() {
return instructionState.lFrame.elementDepthCount;
}
export function increaseElementDepthCount() {
instructionState.lFrame.elementDepthCount++;
}
export function decreaseElementDepthCount() {
instructionState.lFrame.elementDepthCount--;
}
export function getBindingsEnabled(): boolean {
return instructionState.bindingsEnabled;
}
/**
* Returns true if currently inside a skip hydration block.
* @returns boolean
*/
export function isInSkipHydrationBlock(): boolean {
return instructionState.skipHydrationRootTNode !== null;
}
/**
* Returns true if this is the root TNode of the skip hydration block.
* @param tNode the current TNode
* @returns boolean
*/
export function isSkipHydrationRootTNode(tNode: TNode): boolean {
return instructionState.skipHydrationRootTNode === tNode;
}
/**
* Enables dir | {
"end_byte": 7893,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/state.ts"
} |
angular/packages/core/src/render3/state.ts_7895_15949 | tive matching on elements.
*
* * Example:
* ```
* <my-comp my-directive>
* Should match component / directive.
* </my-comp>
* <div ngNonBindable>
* <!-- ɵɵdisableBindings() -->
* <my-comp my-directive>
* Should not match component / directive because we are in ngNonBindable.
* </my-comp>
* <!-- ɵɵenableBindings() -->
* </div>
* ```
*
* @codeGenApi
*/
export function ɵɵenableBindings(): void {
instructionState.bindingsEnabled = true;
}
/**
* Sets a flag to specify that the TNode is in a skip hydration block.
* @param tNode the current TNode
*/
export function enterSkipHydrationBlock(tNode: TNode): void {
instructionState.skipHydrationRootTNode = tNode;
}
/**
* Disables directive matching on element.
*
* * Example:
* ```
* <my-comp my-directive>
* Should match component / directive.
* </my-comp>
* <div ngNonBindable>
* <!-- ɵɵdisableBindings() -->
* <my-comp my-directive>
* Should not match component / directive because we are in ngNonBindable.
* </my-comp>
* <!-- ɵɵenableBindings() -->
* </div>
* ```
*
* @codeGenApi
*/
export function ɵɵdisableBindings(): void {
instructionState.bindingsEnabled = false;
}
/**
* Clears the root skip hydration node when leaving a skip hydration block.
*/
export function leaveSkipHydrationBlock(): void {
instructionState.skipHydrationRootTNode = null;
}
/**
* Return the current `LView`.
*/
export function getLView<T>(): LView<T> {
return instructionState.lFrame.lView as LView<T>;
}
/**
* Return the current `TView`.
*/
export function getTView(): TView {
return instructionState.lFrame.tView;
}
/**
* Restores `contextViewData` to the given OpaqueViewState instance.
*
* Used in conjunction with the getCurrentView() instruction to save a snapshot
* of the current view and restore it when listeners are invoked. This allows
* walking the declaration view tree in listeners to get vars from parent views.
*
* @param viewToRestore The OpaqueViewState instance to restore.
* @returns Context of the restored OpaqueViewState instance.
*
* @codeGenApi
*/
export function ɵɵrestoreView<T = any>(viewToRestore: OpaqueViewState): T {
instructionState.lFrame.contextLView = viewToRestore as any as LView;
return (viewToRestore as any as LView)[CONTEXT] as unknown as T;
}
/**
* Clears the view set in `ɵɵrestoreView` from memory. Returns the passed in
* value so that it can be used as a return value of an instruction.
*
* @codeGenApi
*/
export function ɵɵresetView<T>(value?: T): T | undefined {
instructionState.lFrame.contextLView = null;
return value;
}
export function getCurrentTNode(): TNode | null {
let currentTNode = getCurrentTNodePlaceholderOk();
while (currentTNode !== null && currentTNode.type === TNodeType.Placeholder) {
currentTNode = currentTNode.parent;
}
return currentTNode;
}
export function getCurrentTNodePlaceholderOk(): TNode | null {
return instructionState.lFrame.currentTNode;
}
export function getCurrentParentTNode(): TNode | null {
const lFrame = instructionState.lFrame;
const currentTNode = lFrame.currentTNode;
return lFrame.isParent ? currentTNode : currentTNode!.parent;
}
export function setCurrentTNode(tNode: TNode | null, isParent: boolean) {
ngDevMode && tNode && assertTNodeForTView(tNode, instructionState.lFrame.tView);
const lFrame = instructionState.lFrame;
lFrame.currentTNode = tNode;
lFrame.isParent = isParent;
}
export function isCurrentTNodeParent(): boolean {
return instructionState.lFrame.isParent;
}
export function setCurrentTNodeAsNotParent(): void {
instructionState.lFrame.isParent = false;
}
export function getContextLView(): LView {
const contextLView = instructionState.lFrame.contextLView;
ngDevMode && assertDefined(contextLView, 'contextLView must be defined.');
return contextLView!;
}
export function isInCheckNoChangesMode(): boolean {
!ngDevMode && throwError('Must never be called in production mode');
return _checkNoChangesMode !== CheckNoChangesMode.Off;
}
export function isExhaustiveCheckNoChanges(): boolean {
!ngDevMode && throwError('Must never be called in production mode');
return _checkNoChangesMode === CheckNoChangesMode.Exhaustive;
}
export function setIsInCheckNoChangesMode(mode: CheckNoChangesMode): void {
!ngDevMode && throwError('Must never be called in production mode');
_checkNoChangesMode = mode;
}
export function isRefreshingViews(): boolean {
return _isRefreshingViews;
}
export function setIsRefreshingViews(mode: boolean): boolean {
const prev = _isRefreshingViews;
_isRefreshingViews = mode;
return prev;
}
// top level variables should not be exported for performance reasons (PERF_NOTES.md)
export function getBindingRoot() {
const lFrame = instructionState.lFrame;
let index = lFrame.bindingRootIndex;
if (index === -1) {
index = lFrame.bindingRootIndex = lFrame.tView.bindingStartIndex;
}
return index;
}
export function getBindingIndex(): number {
return instructionState.lFrame.bindingIndex;
}
export function setBindingIndex(value: number): number {
return (instructionState.lFrame.bindingIndex = value);
}
export function nextBindingIndex(): number {
return instructionState.lFrame.bindingIndex++;
}
export function incrementBindingIndex(count: number): number {
const lFrame = instructionState.lFrame;
const index = lFrame.bindingIndex;
lFrame.bindingIndex = lFrame.bindingIndex + count;
return index;
}
export function isInI18nBlock() {
return instructionState.lFrame.inI18n;
}
export function setInI18nBlock(isInI18nBlock: boolean): void {
instructionState.lFrame.inI18n = isInI18nBlock;
}
/**
* Set a new binding root index so that host template functions can execute.
*
* Bindings inside the host template are 0 index. But because we don't know ahead of time
* how many host bindings we have we can't pre-compute them. For this reason they are all
* 0 index and we just shift the root so that they match next available location in the LView.
*
* @param bindingRootIndex Root index for `hostBindings`
* @param currentDirectiveIndex `TData[currentDirectiveIndex]` will point to the current directive
* whose `hostBindings` are being processed.
*/
export function setBindingRootForHostBindings(
bindingRootIndex: number,
currentDirectiveIndex: number,
) {
const lFrame = instructionState.lFrame;
lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;
setCurrentDirectiveIndex(currentDirectiveIndex);
}
/**
* When host binding is executing this points to the directive index.
* `TView.data[getCurrentDirectiveIndex()]` is `DirectiveDef`
* `LView[getCurrentDirectiveIndex()]` is directive instance.
*/
export function getCurrentDirectiveIndex(): number {
return instructionState.lFrame.currentDirectiveIndex;
}
/**
* Sets an index of a directive whose `hostBindings` are being processed.
*
* @param currentDirectiveIndex `TData` index where current directive instance can be found.
*/
export function setCurrentDirectiveIndex(currentDirectiveIndex: number): void {
instructionState.lFrame.currentDirectiveIndex = currentDirectiveIndex;
}
/**
* Retrieve the current `DirectiveDef` which is active when `hostBindings` instruction is being
* executed.
*
* @param tData Current `TData` where the `DirectiveDef` will be looked up at.
*/
export function getCurrentDirectiveDef(tData: TData): DirectiveDef<any> | null {
const currentDirectiveIndex = instructionState.lFrame.currentDirectiveIndex;
return currentDirectiveIndex === -1 ? null : (tData[currentDirectiveIndex] as DirectiveDef<any>);
}
export function getCurrentQueryIndex(): number {
return instructionState.lFrame.currentQueryIndex;
}
export function setCurrentQueryIndex(value: number): void {
instructionState.lFrame.currentQueryIndex = value;
}
/**
* Returns a `TNode` of the location where the current `LView` is declared at.
*
* @param lView an `LView` that we want to find parent `TNode` for.
*/
function getDeclarationTNode(lView: L | {
"end_byte": 15949,
"start_byte": 7895,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/state.ts"
} |
angular/packages/core/src/render3/state.ts_15950_23330 | iew): TNode | null {
const tView = lView[TVIEW];
// Return the declaration parent for embedded views
if (tView.type === TViewType.Embedded) {
ngDevMode && assertDefined(tView.declTNode, 'Embedded TNodes should have declaration parents.');
return tView.declTNode;
}
// Components don't have `TView.declTNode` because each instance of component could be
// inserted in different location, hence `TView.declTNode` is meaningless.
// Falling back to `T_HOST` in case we cross component boundary.
if (tView.type === TViewType.Component) {
return lView[T_HOST];
}
// Remaining TNode type is `TViewType.Root` which doesn't have a parent TNode.
return null;
}
/**
* This is a light weight version of the `enterView` which is needed by the DI system.
*
* @param lView `LView` location of the DI context.
* @param tNode `TNode` for DI context
* @param flags DI context flags. if `SkipSelf` flag is set than we walk up the declaration
* tree from `tNode` until we find parent declared `TElementNode`.
* @returns `true` if we have successfully entered DI associated with `tNode` (or with declared
* `TNode` if `flags` has `SkipSelf`). Failing to enter DI implies that no associated
* `NodeInjector` can be found and we should instead use `ModuleInjector`.
* - If `true` than this call must be fallowed by `leaveDI`
* - If `false` than this call failed and we should NOT call `leaveDI`
*/
export function enterDI(lView: LView, tNode: TNode, flags: InjectFlags) {
ngDevMode && assertLViewOrUndefined(lView);
if (flags & InjectFlags.SkipSelf) {
ngDevMode && assertTNodeForTView(tNode, lView[TVIEW]);
let parentTNode = tNode as TNode | null;
let parentLView = lView;
while (true) {
ngDevMode && assertDefined(parentTNode, 'Parent TNode should be defined');
parentTNode = parentTNode!.parent as TNode | null;
if (parentTNode === null && !(flags & InjectFlags.Host)) {
parentTNode = getDeclarationTNode(parentLView);
if (parentTNode === null) break;
// In this case, a parent exists and is definitely an element. So it will definitely
// have an existing lView as the declaration view, which is why we can assume it's defined.
ngDevMode && assertDefined(parentLView, 'Parent LView should be defined');
parentLView = parentLView[DECLARATION_VIEW]!;
// In Ivy there are Comment nodes that correspond to ngIf and NgFor embedded directives
// We want to skip those and look only at Elements and ElementContainers to ensure
// we're looking at true parent nodes, and not content or other types.
if (parentTNode.type & (TNodeType.Element | TNodeType.ElementContainer)) {
break;
}
} else {
break;
}
}
if (parentTNode === null) {
// If we failed to find a parent TNode this means that we should use module injector.
return false;
} else {
tNode = parentTNode;
lView = parentLView;
}
}
ngDevMode && assertTNodeForLView(tNode, lView);
const lFrame = (instructionState.lFrame = allocLFrame());
lFrame.currentTNode = tNode;
lFrame.lView = lView;
return true;
}
/**
* Swap the current lView with a new lView.
*
* For performance reasons we store the lView in the top level of the module.
* This way we minimize the number of properties to read. Whenever a new view
* is entered we have to store the lView for later, and when the view is
* exited the state has to be restored
*
* @param newView New lView to become active
* @returns the previously active lView;
*/
export function enterView(newView: LView): void {
ngDevMode && assertNotEqual(newView[0], newView[1] as any, '????');
ngDevMode && assertLViewOrUndefined(newView);
const newLFrame = allocLFrame();
if (ngDevMode) {
assertEqual(newLFrame.isParent, true, 'Expected clean LFrame');
assertEqual(newLFrame.lView, null, 'Expected clean LFrame');
assertEqual(newLFrame.tView, null, 'Expected clean LFrame');
assertEqual(newLFrame.selectedIndex, -1, 'Expected clean LFrame');
assertEqual(newLFrame.elementDepthCount, 0, 'Expected clean LFrame');
assertEqual(newLFrame.currentDirectiveIndex, -1, 'Expected clean LFrame');
assertEqual(newLFrame.currentNamespace, null, 'Expected clean LFrame');
assertEqual(newLFrame.bindingRootIndex, -1, 'Expected clean LFrame');
assertEqual(newLFrame.currentQueryIndex, 0, 'Expected clean LFrame');
}
const tView = newView[TVIEW];
instructionState.lFrame = newLFrame;
ngDevMode && tView.firstChild && assertTNodeForTView(tView.firstChild, tView);
newLFrame.currentTNode = tView.firstChild!;
newLFrame.lView = newView;
newLFrame.tView = tView;
newLFrame.contextLView = newView;
newLFrame.bindingIndex = tView.bindingStartIndex;
newLFrame.inI18n = false;
}
/**
* Allocates next free LFrame. This function tries to reuse the `LFrame`s to lower memory pressure.
*/
function allocLFrame() {
const currentLFrame = instructionState.lFrame;
const childLFrame = currentLFrame === null ? null : currentLFrame.child;
const newLFrame = childLFrame === null ? createLFrame(currentLFrame) : childLFrame;
return newLFrame;
}
function createLFrame(parent: LFrame | null): LFrame {
const lFrame: LFrame = {
currentTNode: null,
isParent: true,
lView: null!,
tView: null!,
selectedIndex: -1,
contextLView: null,
elementDepthCount: 0,
currentNamespace: null,
currentDirectiveIndex: -1,
bindingRootIndex: -1,
bindingIndex: -1,
currentQueryIndex: 0,
parent: parent!,
child: null,
inI18n: false,
};
parent !== null && (parent.child = lFrame); // link the new LFrame for reuse.
return lFrame;
}
/**
* A lightweight version of leave which is used with DI.
*
* This function only resets `currentTNode` and `LView` as those are the only properties
* used with DI (`enterDI()`).
*
* NOTE: This function is reexported as `leaveDI`. However `leaveDI` has return type of `void` where
* as `leaveViewLight` has `LFrame`. This is so that `leaveViewLight` can be used in `leaveView`.
*/
function leaveViewLight(): LFrame {
const oldLFrame = instructionState.lFrame;
instructionState.lFrame = oldLFrame.parent;
oldLFrame.currentTNode = null!;
oldLFrame.lView = null!;
return oldLFrame;
}
/**
* This is a lightweight version of the `leaveView` which is needed by the DI system.
*
* NOTE: this function is an alias so that we can change the type of the function to have `void`
* return type.
*/
export const leaveDI: () => void = leaveViewLight;
/**
* Leave the current `LView`
*
* This pops the `LFrame` with the associated `LView` from the stack.
*
* IMPORTANT: We must zero out the `LFrame` values here otherwise they will be retained. This is
* because for performance reasons we don't release `LFrame` but rather keep it for next use.
*/
export function leaveView() {
const oldLFrame = leaveViewLight();
oldLFrame.isParent = true;
oldLFrame.tView = null!;
oldLFrame.selectedIndex = -1;
oldLFrame.contextLView = null;
oldLFrame.elementDepthCount = 0;
oldLFrame.currentDirectiveIndex = -1;
oldLFrame.currentNamespace = null;
oldLFrame.bindingRootIndex = -1;
oldLFrame.bindingIndex = -1;
oldLFrame.currentQueryIndex = 0;
}
export function nextContextImpl<T = | {
"end_byte": 23330,
"start_byte": 15950,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/state.ts"
} |
angular/packages/core/src/render3/state.ts_23332_26291 | y>(level: number): T {
const contextLView = (instructionState.lFrame.contextLView = walkUpViews(
level,
instructionState.lFrame.contextLView!,
));
return contextLView[CONTEXT] as unknown as T;
}
/**
* Gets the currently selected element index.
*
* Used with {@link property} instruction (and more in the future) to identify the index in the
* current `LView` to act on.
*/
export function getSelectedIndex() {
return instructionState.lFrame.selectedIndex;
}
/**
* Sets the most recent index passed to {@link select}
*
* Used with {@link property} instruction (and more in the future) to identify the index in the
* current `LView` to act on.
*
* (Note that if an "exit function" was set earlier (via `setElementExitFn()`) then that will be
* run if and when the provided `index` value is different from the current selected index value.)
*/
export function setSelectedIndex(index: number) {
ngDevMode &&
index !== -1 &&
assertGreaterThanOrEqual(index, HEADER_OFFSET, 'Index must be past HEADER_OFFSET (or -1).');
ngDevMode &&
assertLessThan(
index,
instructionState.lFrame.lView.length,
"Can't set index passed end of LView",
);
instructionState.lFrame.selectedIndex = index;
}
/**
* Gets the `tNode` that represents currently selected element.
*/
export function getSelectedTNode() {
const lFrame = instructionState.lFrame;
return getTNode(lFrame.tView, lFrame.selectedIndex);
}
/**
* Sets the namespace used to create elements to `'http://www.w3.org/2000/svg'` in global state.
*
* @codeGenApi
*/
export function ɵɵnamespaceSVG() {
instructionState.lFrame.currentNamespace = SVG_NAMESPACE;
}
/**
* Sets the namespace used to create elements to `'http://www.w3.org/1998/MathML/'` in global state.
*
* @codeGenApi
*/
export function ɵɵnamespaceMathML() {
instructionState.lFrame.currentNamespace = MATH_ML_NAMESPACE;
}
/**
* Sets the namespace used to create elements to `null`, which forces element creation to use
* `createElement` rather than `createElementNS`.
*
* @codeGenApi
*/
export function ɵɵnamespaceHTML() {
namespaceHTMLInternal();
}
/**
* Sets the namespace used to create elements to `null`, which forces element creation to use
* `createElement` rather than `createElementNS`.
*/
export function namespaceHTMLInternal() {
instructionState.lFrame.currentNamespace = null;
}
export function getNamespace(): string | null {
return instructionState.lFrame.currentNamespace;
}
let _wasLastNodeCreated = true;
/**
* Retrieves a global flag that indicates whether the most recent DOM node
* was created or hydrated.
*/
export function wasLastNodeCreated(): boolean {
return _wasLastNodeCreated;
}
/**
* Sets a global flag to indicate whether the most recent DOM node
* was created or hydrated.
*/
export function lastNodeWasCreated(flag: boolean): void {
_wasLastNodeCreated = flag;
}
| {
"end_byte": 26291,
"start_byte": 23332,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/state.ts"
} |
angular/packages/core/src/render3/namespaces.ts_0_281 | /**
* @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 SVG_NAMESPACE = 'svg';
export const MATH_ML_NAMESPACE = 'math';
| {
"end_byte": 281,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/namespaces.ts"
} |
angular/packages/core/src/render3/view_ref.ts_0_1733 | /**
* @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} from '../change_detection/change_detector_ref';
import {NotificationSource} from '../change_detection/scheduling/zoneless_scheduling';
import type {ApplicationRef} from '../core';
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {EmbeddedViewRef} from '../linker/view_ref';
import {removeFromArray} from '../util/array_utils';
import {assertEqual} from '../util/assert';
import {collectNativeNodes} from './collect_native_nodes';
import {checkNoChangesInternal, detectChangesInternal} from './instructions/change_detection';
import {markViewDirty} from './instructions/mark_view_dirty';
import {CONTAINER_HEADER_OFFSET, VIEW_REFS} from './interfaces/container';
import {isLContainer, isRootView} from './interfaces/type_checks';
import {
CONTEXT,
DECLARATION_LCONTAINER,
FLAGS,
LView,
LViewFlags,
PARENT,
REACTIVE_TEMPLATE_CONSUMER,
TVIEW,
} from './interfaces/view';
import {
destroyLView,
detachMovedView,
detachView,
detachViewFromDOM,
trackMovedView,
} from './node_manipulation';
import {CheckNoChangesMode} from './state';
import {
markViewForRefresh,
storeLViewOnDestroy,
updateAncestorTraversalFlagsOnAttach,
} from './util/view_utils';
// Needed due to tsickle downleveling where multiple `implements` with classes creates
// multiple @extends in Closure annotations, which is illegal. This workaround fixes
// the multiple @extends by making the annotation @implements instead
interface ChangeDetectorRefInterface extends ChangeDetectorRef {} | {
"end_byte": 1733,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/view_ref.ts"
} |
angular/packages/core/src/render3/view_ref.ts_1735_9328 | export class ViewRef<T> implements EmbeddedViewRef<T>, ChangeDetectorRefInterface {
private _appRef: ApplicationRef | null = null;
private _attachedToViewContainer = false;
get rootNodes(): any[] {
const lView = this._lView;
const tView = lView[TVIEW];
return collectNativeNodes(tView, lView, tView.firstChild, []);
}
constructor(
/**
* This represents `LView` associated with the component when ViewRef is a ChangeDetectorRef.
*
* When ViewRef is created for a dynamic component, this also represents the `LView` for the
* component.
*
* For a "regular" ViewRef created for an embedded view, this is the `LView` for the embedded
* view.
*
* @internal
*/
public _lView: LView,
/**
* This represents the `LView` associated with the point where `ChangeDetectorRef` was
* requested.
*
* This may be different from `_lView` if the `_cdRefInjectingView` is an embedded view.
*/
private _cdRefInjectingView?: LView,
readonly notifyErrorHandler = true,
) {}
get context(): T {
return this._lView[CONTEXT] as unknown as T;
}
/**
* Reports whether the given view is considered dirty according to the different marking mechanisms.
*/
get dirty(): boolean {
return (
!!(
this._lView[FLAGS] &
(LViewFlags.Dirty | LViewFlags.RefreshView | LViewFlags.HasChildViewsToRefresh)
) || !!this._lView[REACTIVE_TEMPLATE_CONSUMER]?.dirty
);
}
/**
* @deprecated Replacing the full context object is not supported. Modify the context
* directly, or consider using a `Proxy` if you need to replace the full object.
* // TODO(devversion): Remove this.
*/
set context(value: T) {
if (ngDevMode) {
// Note: We have a warning message here because the `@deprecated` JSDoc will not be picked
// up for assignments on the setter. We want to let users know about the deprecated usage.
console.warn(
'Angular: Replacing the `context` object of an `EmbeddedViewRef` is deprecated.',
);
}
this._lView[CONTEXT] = value as unknown as {};
}
get destroyed(): boolean {
return (this._lView[FLAGS] & LViewFlags.Destroyed) === LViewFlags.Destroyed;
}
destroy(): void {
if (this._appRef) {
this._appRef.detachView(this);
} else if (this._attachedToViewContainer) {
const parent = this._lView[PARENT];
if (isLContainer(parent)) {
const viewRefs = parent[VIEW_REFS] as ViewRef<unknown>[] | null;
const index = viewRefs ? viewRefs.indexOf(this) : -1;
if (index > -1) {
ngDevMode &&
assertEqual(
index,
parent.indexOf(this._lView) - CONTAINER_HEADER_OFFSET,
'An attached view should be in the same position within its container as its ViewRef in the VIEW_REFS array.',
);
detachView(parent, index);
removeFromArray(viewRefs!, index);
}
}
this._attachedToViewContainer = false;
}
destroyLView(this._lView[TVIEW], this._lView);
}
onDestroy(callback: Function) {
storeLViewOnDestroy(this._lView, callback as () => void);
}
/**
* Marks a view and all of its ancestors dirty.
*
* This can be used to ensure an {@link ChangeDetectionStrategy#OnPush} component is
* checked when it needs to be re-rendered but the two normal triggers haven't marked it
* dirty (i.e. inputs haven't changed and events haven't fired in the view).
*
* <!-- TODO: Add a link to a chapter on OnPush components -->
*
* @usageNotes
* ### Example
*
* ```typescript
* @Component({
* selector: 'app-root',
* template: `Number of ticks: {{numberOfTicks}}`
* changeDetection: ChangeDetectionStrategy.OnPush,
* })
* class AppComponent {
* numberOfTicks = 0;
*
* constructor(private ref: ChangeDetectorRef) {
* setInterval(() => {
* this.numberOfTicks++;
* // the following is required, otherwise the view will not be updated
* this.ref.markForCheck();
* }, 1000);
* }
* }
* ```
*/
markForCheck(): void {
markViewDirty(this._cdRefInjectingView || this._lView, NotificationSource.MarkForCheck);
}
markForRefresh(): void {
markViewForRefresh(this._cdRefInjectingView || this._lView);
}
/**
* Detaches the view from the change detection tree.
*
* Detached views will not be checked during change detection runs until they are
* re-attached, even if they are dirty. `detach` can be used in combination with
* {@link ChangeDetectorRef#detectChanges} to implement local change
* detection checks.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
* <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
*
* @usageNotes
* ### Example
*
* The following example defines a component with a large list of readonly data.
* Imagine the data changes constantly, many times per second. For performance reasons,
* we want to check and update the list every five seconds. We can do that by detaching
* the component's change detector and doing a local check every five seconds.
*
* ```typescript
* class DataProvider {
* // in a real application the returned data will be different every time
* get data() {
* return [1,2,3,4,5];
* }
* }
*
* @Component({
* selector: 'giant-list',
* template: `
* <li *ngFor="let d of dataProvider.data">Data {{d}}</li>
* `,
* })
* class GiantList {
* constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {
* ref.detach();
* setInterval(() => {
* this.ref.detectChanges();
* }, 5000);
* }
* }
*
* @Component({
* selector: 'app',
* providers: [DataProvider],
* template: `
* <giant-list><giant-list>
* `,
* })
* class App {
* }
* ```
*/
detach(): void {
this._lView[FLAGS] &= ~LViewFlags.Attached;
}
/**
* Re-attaches a view to the change detection tree.
*
* This can be used to re-attach views that were previously detached from the tree
* using {@link ChangeDetectorRef#detach}. Views are attached to the tree by default.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
*
* @usageNotes
* ### Example
*
* The following example creates a component displaying `live` data. The component will detach
* its change detector from the main change detector tree when the component's live property
* is set to false.
*
* ```typescript
* class DataProvider {
* data = 1;
*
* constructor() {
* setInterval(() => {
* this.data = this.data * 2;
* }, 500);
* }
* }
*
* @Component({
* selector: 'live-data',
* inputs: ['live'],
* template: 'Data: {{dataProvider.data}}'
* })
* class LiveData {
* constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {}
*
* set live(value) {
* if (value) {
* this.ref.reattach();
* } else {
* this.ref.detach();
* }
* }
* }
*
* @Component({
* selector: 'app-root',
* providers: [DataProvider],
* template: `
* Live Update: <input type="checkbox" [(ngModel)]="live">
* <live-data [live]="live"><live-data>
* `,
* })
* class AppComponent {
* live = true;
* }
* ```
*/ | {
"end_byte": 9328,
"start_byte": 1735,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/view_ref.ts"
} |
angular/packages/core/src/render3/view_ref.ts_9331_12471 | reattach(): void {
updateAncestorTraversalFlagsOnAttach(this._lView);
this._lView[FLAGS] |= LViewFlags.Attached;
}
/**
* Checks the view and its children.
*
* This can also be used in combination with {@link ChangeDetectorRef#detach} to implement
* local change detection checks.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
* <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
*
* @usageNotes
* ### Example
*
* The following example defines a component with a large list of readonly data.
* Imagine, the data changes constantly, many times per second. For performance reasons,
* we want to check and update the list every five seconds.
*
* We can do that by detaching the component's change detector and doing a local change detection
* check every five seconds.
*
* See {@link ChangeDetectorRef#detach} for more information.
*/
detectChanges(): void {
// Add `RefreshView` flag to ensure this view is refreshed if not already dirty.
// `RefreshView` flag is used intentionally over `Dirty` because it gets cleared before
// executing any of the actual refresh code while the `Dirty` flag doesn't get cleared
// until the end of the refresh. Using `RefreshView` prevents creating a potential difference
// in the state of the LViewFlags during template execution.
this._lView[FLAGS] |= LViewFlags.RefreshView;
detectChangesInternal(this._lView, this.notifyErrorHandler);
}
/**
* Checks the change detector and its children, and throws if any changes are detected.
*
* This is used in development mode to verify that running change detection doesn't
* introduce other changes.
*/
checkNoChanges(): void {
if (ngDevMode) {
checkNoChangesInternal(
this._lView,
CheckNoChangesMode.OnlyDirtyViews,
this.notifyErrorHandler,
);
}
}
attachToViewContainerRef() {
if (this._appRef) {
throw new RuntimeError(
RuntimeErrorCode.VIEW_ALREADY_ATTACHED,
ngDevMode && 'This view is already attached directly to the ApplicationRef!',
);
}
this._attachedToViewContainer = true;
}
detachFromAppRef() {
this._appRef = null;
const isRoot = isRootView(this._lView);
const declarationContainer = this._lView[DECLARATION_LCONTAINER];
if (declarationContainer !== null && !isRoot) {
detachMovedView(declarationContainer, this._lView);
}
detachViewFromDOM(this._lView[TVIEW], this._lView);
}
attachToAppRef(appRef: ApplicationRef) {
if (this._attachedToViewContainer) {
throw new RuntimeError(
RuntimeErrorCode.VIEW_ALREADY_ATTACHED,
ngDevMode && 'This view is already attached to a ViewContainer!',
);
}
this._appRef = appRef;
const isRoot = isRootView(this._lView);
const declarationContainer = this._lView[DECLARATION_LCONTAINER];
if (declarationContainer !== null && !isRoot) {
trackMovedView(declarationContainer, this._lView);
}
updateAncestorTraversalFlagsOnAttach(this._lView);
}
} | {
"end_byte": 12471,
"start_byte": 9331,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/view_ref.ts"
} |
angular/packages/core/src/render3/standalone-default-value.ts_0_423 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A constant defining the default value for the standalone attribute in Directive and Pipes decorators.
* Extracted to a separate file to facilitate G3 patches.
*/
export const NG_STANDALONE_DEFAULT_VALUE = true;
| {
"end_byte": 423,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/standalone-default-value.ts"
} |
angular/packages/core/src/render3/scope.ts_0_3118 | /**
* @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 {isForwardRef, resolveForwardRef} from '../di/forward_ref';
import {Type} from '../interface/type';
import {flatten} from '../util/array_utils';
import {noSideEffects} from '../util/closure';
import {EMPTY_ARRAY} from '../util/empty';
import {getNgModuleDef} from './def_getters';
import {extractDefListOrFactory} from './definition';
import {depsTracker} from './deps_tracker/deps_tracker';
import {
ComponentDef,
ComponentType,
NgModuleScopeInfoFromDecorator,
RawScopeInfoFromDecorator,
} from './interfaces/definition';
import {isModuleWithProviders} from './jit/util';
/**
* Generated next to NgModules to monkey-patch directive and pipe references onto a component's
* definition, when generating a direct reference in the component file would otherwise create an
* import cycle.
*
* See [this explanation](https://hackmd.io/Odw80D0pR6yfsOjg_7XCJg?view) for more details.
*
* @codeGenApi
*/
export function ɵɵsetComponentScope(
type: ComponentType<any>,
directives: Type<any>[] | (() => Type<any>[]),
pipes: Type<any>[] | (() => Type<any>[]),
): void {
const def = type.ɵcmp as ComponentDef<any>;
def.directiveDefs = extractDefListOrFactory(directives, /* pipeDef */ false);
def.pipeDefs = extractDefListOrFactory(pipes, /* pipeDef */ true);
}
/**
* Adds the module metadata that is necessary to compute the module's transitive scope to an
* existing module definition.
*
* Scope metadata of modules is not used in production builds, so calls to this function can be
* marked pure to tree-shake it from the bundle, allowing for all referenced declarations
* to become eligible for tree-shaking as well.
*
* @codeGenApi
*/
export function ɵɵsetNgModuleScope(type: any, scope: NgModuleScopeInfoFromDecorator): unknown {
return noSideEffects(() => {
const ngModuleDef = getNgModuleDef(type, true);
ngModuleDef.declarations = convertToTypeArray(scope.declarations || EMPTY_ARRAY);
ngModuleDef.imports = convertToTypeArray(scope.imports || EMPTY_ARRAY);
ngModuleDef.exports = convertToTypeArray(scope.exports || EMPTY_ARRAY);
if (scope.bootstrap) {
// This only happens in local compilation mode.
ngModuleDef.bootstrap = convertToTypeArray(scope.bootstrap);
}
depsTracker.registerNgModule(type, scope);
});
}
function convertToTypeArray(
values: Type<any>[] | (() => Type<any>[]) | RawScopeInfoFromDecorator[],
): Type<any>[] | (() => Type<any>[]) {
if (typeof values === 'function') {
return values;
}
const flattenValues = flatten(values);
if (flattenValues.some(isForwardRef)) {
return () => flattenValues.map(resolveForwardRef).map(maybeUnwrapModuleWithProviders);
} else {
return flattenValues.map(maybeUnwrapModuleWithProviders);
}
}
function maybeUnwrapModuleWithProviders(value: any): Type<any> {
return isModuleWithProviders(value) ? value.ngModule : (value as Type<any>);
}
| {
"end_byte": 3118,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/scope.ts"
} |
angular/packages/core/src/render3/profiler_types.ts_0_2162 | /*!
* @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: ideally we would roll these types into the `profiler.ts`. During the update to TS 5.5
// they had to be moved out into a separate file, because `@microsoft/api-extractor` was throwing
// an error saying `Unable to follow symbol for "Profiler"`.
/**
* Profiler events is an enum used by the profiler to distinguish between different calls of user
* code invoked throughout the application lifecycle.
*/
export const enum ProfilerEvent {
/**
* Corresponds to the point in time before the runtime has called the template function of a
* component with `RenderFlags.Create`.
*/
TemplateCreateStart,
/**
* Corresponds to the point in time after the runtime has called the template function of a
* component with `RenderFlags.Create`.
*/
TemplateCreateEnd,
/**
* Corresponds to the point in time before the runtime has called the template function of a
* component with `RenderFlags.Update`.
*/
TemplateUpdateStart,
/**
* Corresponds to the point in time after the runtime has called the template function of a
* component with `RenderFlags.Update`.
*/
TemplateUpdateEnd,
/**
* Corresponds to the point in time before the runtime has called a lifecycle hook of a component
* or directive.
*/
LifecycleHookStart,
/**
* Corresponds to the point in time after the runtime has called a lifecycle hook of a component
* or directive.
*/
LifecycleHookEnd,
/**
* Corresponds to the point in time before the runtime has evaluated an expression associated with
* an event or an output.
*/
OutputStart,
/**
* Corresponds to the point in time after the runtime has evaluated an expression associated with
* an event or an output.
*/
OutputEnd,
}
/**
* Profiler function which the runtime will invoke before and after user code.
*/
export interface Profiler {
(event: ProfilerEvent, instance: {} | null, hookOrListener?: (e?: any) => any): void;
}
| {
"end_byte": 2162,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/profiler_types.ts"
} |
angular/packages/core/src/render3/pipe.ts_0_8200 | /**
* @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 {PipeTransform} from '../change_detection/pipe_transform';
import {setInjectImplementation} from '../di/inject_switch';
import {formatRuntimeError, RuntimeError, RuntimeErrorCode} from '../errors';
import {Type} from '../interface/type';
import {InjectorProfilerContext, setInjectorProfilerContext} from './debug/injector_profiler';
import {getFactoryDef} from './definition_factory';
import {NodeInjector, setIncludeViewProviders} from './di';
import {store, ɵɵdirectiveInject} from './instructions/all';
import {isHostComponentStandalone} from './instructions/element_validation';
import {PipeDef, PipeDefList} from './interfaces/definition';
import {TTextNode} from './interfaces/node';
import {CONTEXT, DECLARATION_COMPONENT_VIEW, HEADER_OFFSET, LView, TVIEW} from './interfaces/view';
import {
pureFunction1Internal,
pureFunction2Internal,
pureFunction3Internal,
pureFunction4Internal,
pureFunctionVInternal,
} from './pure_function';
import {getBindingRoot, getCurrentTNode, getLView, getTView} from './state';
import {load} from './util/view_utils';
/**
* Create a pipe.
*
* @param index Pipe index where the pipe will be stored.
* @param pipeName The name of the pipe
* @returns T the instance of the pipe.
*
* @codeGenApi
*/
export function ɵɵpipe(index: number, pipeName: string): any {
const tView = getTView();
let pipeDef: PipeDef<any>;
const adjustedIndex = index + HEADER_OFFSET;
if (tView.firstCreatePass) {
// The `getPipeDef` throws if a pipe with a given name is not found
// (so we use non-null assertion below).
pipeDef = getPipeDef(pipeName, tView.pipeRegistry)!;
tView.data[adjustedIndex] = pipeDef;
if (pipeDef.onDestroy) {
(tView.destroyHooks ??= []).push(adjustedIndex, pipeDef.onDestroy);
}
} else {
pipeDef = tView.data[adjustedIndex] as PipeDef<any>;
}
const pipeFactory = pipeDef.factory || (pipeDef.factory = getFactoryDef(pipeDef.type, true));
let previousInjectorProfilerContext: InjectorProfilerContext;
if (ngDevMode) {
previousInjectorProfilerContext = setInjectorProfilerContext({
injector: new NodeInjector(getCurrentTNode() as TTextNode, getLView()),
token: pipeDef.type,
});
}
const previousInjectImplementation = setInjectImplementation(ɵɵdirectiveInject);
try {
// DI for pipes is supposed to behave like directives when placed on a component
// host node, which means that we have to disable access to `viewProviders`.
const previousIncludeViewProviders = setIncludeViewProviders(false);
const pipeInstance = pipeFactory();
setIncludeViewProviders(previousIncludeViewProviders);
store(tView, getLView(), adjustedIndex, pipeInstance);
return pipeInstance;
} finally {
// we have to restore the injector implementation in finally, just in case the creation of the
// pipe throws an error.
setInjectImplementation(previousInjectImplementation);
ngDevMode && setInjectorProfilerContext(previousInjectorProfilerContext!);
}
}
/**
* Searches the pipe registry for a pipe with the given name. If one is found,
* returns the pipe. Otherwise, an error is thrown because the pipe cannot be resolved.
*
* @param name Name of pipe to resolve
* @param registry Full list of available pipes
* @returns Matching PipeDef
*/
function getPipeDef(name: string, registry: PipeDefList | null): PipeDef<any> | undefined {
if (registry) {
if (ngDevMode) {
const pipes = registry.filter((pipe) => pipe.name === name);
// TODO: Throw an error in the next major
if (pipes.length > 1) {
console.warn(
formatRuntimeError(
RuntimeErrorCode.MULTIPLE_MATCHING_PIPES,
getMultipleMatchingPipesMessage(name),
),
);
}
}
for (let i = registry.length - 1; i >= 0; i--) {
const pipeDef = registry[i];
if (name === pipeDef.name) {
return pipeDef;
}
}
}
if (ngDevMode) {
throw new RuntimeError(RuntimeErrorCode.PIPE_NOT_FOUND, getPipeNotFoundErrorMessage(name));
}
return;
}
/**
* Generates a helpful error message for the user when multiple pipes match the name.
*
* @param name Name of the pipe
* @returns The error message
*/
function getMultipleMatchingPipesMessage(name: string) {
const lView = getLView();
const declarationLView = lView[DECLARATION_COMPONENT_VIEW] as LView<Type<unknown>>;
const context = declarationLView[CONTEXT];
const hostIsStandalone = isHostComponentStandalone(lView);
const componentInfoMessage = context ? ` in the '${context.constructor.name}' component` : '';
const verifyMessage = `check ${
hostIsStandalone ? "'@Component.imports' of this component" : 'the imports of this module'
}`;
const errorMessage = `Multiple pipes match the name \`${name}\`${componentInfoMessage}. ${verifyMessage}`;
return errorMessage;
}
/**
* Generates a helpful error message for the user when a pipe is not found.
*
* @param name Name of the missing pipe
* @returns The error message
*/
function getPipeNotFoundErrorMessage(name: string) {
const lView = getLView();
const declarationLView = lView[DECLARATION_COMPONENT_VIEW] as LView<Type<unknown>>;
const context = declarationLView[CONTEXT];
const hostIsStandalone = isHostComponentStandalone(lView);
const componentInfoMessage = context ? ` in the '${context.constructor.name}' component` : '';
const verifyMessage = `Verify that it is ${
hostIsStandalone
? "included in the '@Component.imports' of this component"
: 'declared or imported in this module'
}`;
const errorMessage = `The pipe '${name}' could not be found${componentInfoMessage}. ${verifyMessage}`;
return errorMessage;
}
/**
* Invokes a pipe with 1 arguments.
*
* This instruction acts as a guard to {@link PipeTransform#transform} invoking
* the pipe only when an input to the pipe changes.
*
* @param index Pipe index where the pipe was stored on creation.
* @param offset the binding offset
* @param v1 1st argument to {@link PipeTransform#transform}.
*
* @codeGenApi
*/
export function ɵɵpipeBind1(index: number, offset: number, v1: any): any {
const adjustedIndex = index + HEADER_OFFSET;
const lView = getLView();
const pipeInstance = load<PipeTransform>(lView, adjustedIndex);
return isPure(lView, adjustedIndex)
? pureFunction1Internal(
lView,
getBindingRoot(),
offset,
pipeInstance.transform,
v1,
pipeInstance,
)
: pipeInstance.transform(v1);
}
/**
* Invokes a pipe with 2 arguments.
*
* This instruction acts as a guard to {@link PipeTransform#transform} invoking
* the pipe only when an input to the pipe changes.
*
* @param index Pipe index where the pipe was stored on creation.
* @param slotOffset the offset in the reserved slot space
* @param v1 1st argument to {@link PipeTransform#transform}.
* @param v2 2nd argument to {@link PipeTransform#transform}.
*
* @codeGenApi
*/
export function ɵɵpipeBind2(index: number, slotOffset: number, v1: any, v2: any): any {
const adjustedIndex = index + HEADER_OFFSET;
const lView = getLView();
const pipeInstance = load<PipeTransform>(lView, adjustedIndex);
return isPure(lView, adjustedIndex)
? pureFunction2Internal(
lView,
getBindingRoot(),
slotOffset,
pipeInstance.transform,
v1,
v2,
pipeInstance,
)
: pipeInstance.transform(v1, v2);
}
/**
* Invokes a pipe with 3 arguments.
*
* This instruction acts as a guard to {@link PipeTransform#transform} invoking
* the pipe only when an input to the pipe changes.
*
* @param index Pipe index where the pipe was stored on creation.
* @param slotOffset the offset in the reserved slot space
* @param v1 1st argument to {@link PipeTransform#transform}.
* @param v2 2nd argument to {@link PipeTransform#transform}.
* @param v3 4rd argument to {@link PipeTransform#transform}.
*
* @codeGenApi
*/
export fu | {
"end_byte": 8200,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/pipe.ts"
} |
angular/packages/core/src/render3/pipe.ts_8201_10883 | ction ɵɵpipeBind3(index: number, slotOffset: number, v1: any, v2: any, v3: any): any {
const adjustedIndex = index + HEADER_OFFSET;
const lView = getLView();
const pipeInstance = load<PipeTransform>(lView, adjustedIndex);
return isPure(lView, adjustedIndex)
? pureFunction3Internal(
lView,
getBindingRoot(),
slotOffset,
pipeInstance.transform,
v1,
v2,
v3,
pipeInstance,
)
: pipeInstance.transform(v1, v2, v3);
}
/**
* Invokes a pipe with 4 arguments.
*
* This instruction acts as a guard to {@link PipeTransform#transform} invoking
* the pipe only when an input to the pipe changes.
*
* @param index Pipe index where the pipe was stored on creation.
* @param slotOffset the offset in the reserved slot space
* @param v1 1st argument to {@link PipeTransform#transform}.
* @param v2 2nd argument to {@link PipeTransform#transform}.
* @param v3 3rd argument to {@link PipeTransform#transform}.
* @param v4 4th argument to {@link PipeTransform#transform}.
*
* @codeGenApi
*/
export function ɵɵpipeBind4(
index: number,
slotOffset: number,
v1: any,
v2: any,
v3: any,
v4: any,
): any {
const adjustedIndex = index + HEADER_OFFSET;
const lView = getLView();
const pipeInstance = load<PipeTransform>(lView, adjustedIndex);
return isPure(lView, adjustedIndex)
? pureFunction4Internal(
lView,
getBindingRoot(),
slotOffset,
pipeInstance.transform,
v1,
v2,
v3,
v4,
pipeInstance,
)
: pipeInstance.transform(v1, v2, v3, v4);
}
/**
* Invokes a pipe with variable number of arguments.
*
* This instruction acts as a guard to {@link PipeTransform#transform} invoking
* the pipe only when an input to the pipe changes.
*
* @param index Pipe index where the pipe was stored on creation.
* @param slotOffset the offset in the reserved slot space
* @param values Array of arguments to pass to {@link PipeTransform#transform} method.
*
* @codeGenApi
*/
export function ɵɵpipeBindV(index: number, slotOffset: number, values: [any, ...any[]]): any {
const adjustedIndex = index + HEADER_OFFSET;
const lView = getLView();
const pipeInstance = load<PipeTransform>(lView, adjustedIndex);
return isPure(lView, adjustedIndex)
? pureFunctionVInternal(
lView,
getBindingRoot(),
slotOffset,
pipeInstance.transform,
values,
pipeInstance,
)
: pipeInstance.transform.apply(pipeInstance, values);
}
function isPure(lView: LView, index: number): boolean {
return (<PipeDef<any>>lView[TVIEW].data[index]).pure;
}
| {
"end_byte": 10883,
"start_byte": 8201,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/pipe.ts"
} |
angular/packages/core/src/render3/CODE_GEN_API.md_0_935 | # Code Gen API
### Prefix ɵɵ
Ivy exports a number of functions prefixed with `ɵɵ`, for example `ɵɵelementStart`, or `ɵɵinject`, et al. These functions are part of API required for code generation by the Angular compiler. These functions are called by generated code, and they must be publicly exposed in order to be consumed by this generated code. **They are not meant for developer consumption**. The reason they are prefixed with `ɵɵ` is not only to identify them as different from other functions, but also to make them not show up at the top of IDE code completion in environments such as Visual Studio code.
### Guidance
- Do not use `ɵɵ` functions directly. They are meant to be used in generated code.
- Do not create new `ɵɵ` functions, it's not a convention that Angular consumes, and it is liable to confuse other developers into thinking consuming Angular's `ɵɵ` functions is a good pattern to follow.
| {
"end_byte": 935,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/CODE_GEN_API.md"
} |
angular/packages/core/src/render3/profiler.ts_0_1394 | /**
* @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 {type Profiler} from './profiler_types';
let profilerCallback: Profiler | null = null;
/**
* Sets the callback function which will be invoked before and after performing certain actions at
* runtime (for example, before and after running change detection).
*
* Warning: this function is *INTERNAL* and should not be relied upon in application's code.
* The contract of the function might be changed in any release and/or the function can be removed
* completely.
*
* @param profiler function provided by the caller or null value to disable profiling.
*/
export const setProfiler = (profiler: Profiler | null) => {
profilerCallback = profiler;
};
/**
* Profiler function which wraps user code executed by the runtime.
*
* @param event ProfilerEvent corresponding to the execution context
* @param instance component instance
* @param hookOrListener lifecycle hook function or output listener. The value depends on the
* execution context
* @returns
*/
export const profiler: Profiler = function (event, instance, hookOrListener) {
if (profilerCallback != null /* both `null` and `undefined` */) {
profilerCallback(event, instance, hookOrListener);
}
};
| {
"end_byte": 1394,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/profiler.ts"
} |
angular/packages/core/src/render3/view_manipulation.ts_0_5135 | /**
* @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 {setActiveConsumer} from '@angular/core/primitives/signals';
import {Injector} from '../di/injector';
import {DehydratedContainerView} from '../hydration/interfaces';
import {hasInSkipHydrationBlockFlag} from '../hydration/skip_hydration';
import {assertDefined} from '../util/assert';
import {assertLContainer, assertLView, assertTNodeForLView} from './assert';
import {renderView} from './instructions/render';
import {createLView} from './instructions/shared';
import {CONTAINER_HEADER_OFFSET, LContainer, NATIVE} from './interfaces/container';
import {TNode} from './interfaces/node';
import {RComment, RElement} from './interfaces/renderer_dom';
import {
DECLARATION_LCONTAINER,
FLAGS,
HYDRATION,
LView,
LViewFlags,
QUERIES,
RENDERER,
T_HOST,
TVIEW,
} from './interfaces/view';
import {
addViewToDOM,
destroyLView,
detachView,
getBeforeNodeForView,
insertView,
nativeParentNode,
} from './node_manipulation';
export function createAndRenderEmbeddedLView<T>(
declarationLView: LView<unknown>,
templateTNode: TNode,
context: T,
options?: {
injector?: Injector;
embeddedViewInjector?: Injector;
dehydratedView?: DehydratedContainerView | null;
},
): LView<T> {
const prevConsumer = setActiveConsumer(null);
try {
const embeddedTView = templateTNode.tView!;
ngDevMode && assertDefined(embeddedTView, 'TView must be defined for a template node.');
ngDevMode && assertTNodeForLView(templateTNode, declarationLView);
// Embedded views follow the change detection strategy of the view they're declared in.
const isSignalView = declarationLView[FLAGS] & LViewFlags.SignalView;
const viewFlags = isSignalView ? LViewFlags.SignalView : LViewFlags.CheckAlways;
const embeddedLView = createLView<T>(
declarationLView,
embeddedTView,
context,
viewFlags,
null,
templateTNode,
null,
null,
options?.injector ?? null,
options?.embeddedViewInjector ?? null,
options?.dehydratedView ?? null,
);
const declarationLContainer = declarationLView[templateTNode.index];
ngDevMode && assertLContainer(declarationLContainer);
embeddedLView[DECLARATION_LCONTAINER] = declarationLContainer;
const declarationViewLQueries = declarationLView[QUERIES];
if (declarationViewLQueries !== null) {
embeddedLView[QUERIES] = declarationViewLQueries.createEmbeddedView(embeddedTView);
}
// execute creation mode of a view
renderView(embeddedTView, embeddedLView, context);
return embeddedLView;
} finally {
setActiveConsumer(prevConsumer);
}
}
export function getLViewFromLContainer<T>(
lContainer: LContainer,
index: number,
): LView<T> | undefined {
const adjustedIndex = CONTAINER_HEADER_OFFSET + index;
// avoid reading past the array boundaries
if (adjustedIndex < lContainer.length) {
const lView = lContainer[adjustedIndex];
ngDevMode && assertLView(lView);
return lView as LView<T>;
}
return undefined;
}
/**
* Returns whether an elements that belong to a view should be
* inserted into the DOM. For client-only cases, DOM elements are
* always inserted. For hydration cases, we check whether serialized
* info is available for a view and the view is not in a "skip hydration"
* block (in which case view contents was re-created, thus needing insertion).
*/
export function shouldAddViewToDom(
tNode: TNode,
dehydratedView?: DehydratedContainerView | null,
): boolean {
return (
!dehydratedView || dehydratedView.firstChild === null || hasInSkipHydrationBlockFlag(tNode)
);
}
export function addLViewToLContainer(
lContainer: LContainer,
lView: LView<unknown>,
index: number,
addToDOM = true,
): void {
const tView = lView[TVIEW];
// Insert into the view tree so the new view can be change-detected
insertView(tView, lView, lContainer, index);
// Insert elements that belong to this view into the DOM tree
if (addToDOM) {
const beforeNode = getBeforeNodeForView(index, lContainer);
const renderer = lView[RENDERER];
const parentRNode = nativeParentNode(renderer, lContainer[NATIVE] as RElement | RComment);
if (parentRNode !== null) {
addViewToDOM(tView, lContainer[T_HOST], renderer, lView, parentRNode, beforeNode);
}
}
// When in hydration mode, reset the pointer to the first child in
// the dehydrated view. This indicates that the view was hydrated and
// further attaching/detaching should work with this view as normal.
const hydrationInfo = lView[HYDRATION];
if (hydrationInfo !== null && hydrationInfo.firstChild !== null) {
hydrationInfo.firstChild = null;
}
}
export function removeLViewFromLContainer(
lContainer: LContainer,
index: number,
): LView<unknown> | undefined {
const lView = detachView(lContainer, index);
if (lView !== undefined) {
destroyLView(lView[TVIEW], lView);
}
return lView;
}
| {
"end_byte": 5135,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/view_manipulation.ts"
} |
angular/packages/core/src/render3/component.ts_0_7013 | /**
* @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 '../di/injector';
import {EnvironmentInjector, getNullInjector} from '../di/r3_injector';
import {Type} from '../interface/type';
import {ComponentRef} from '../linker/component_factory';
import {ComponentFactory} from './component_ref';
import {getComponentDef} from './def_getters';
import {assertComponentDef} from './errors';
/**
* Creates a `ComponentRef` instance based on provided component type and a set of options.
*
* @usageNotes
*
* The example below demonstrates how the `createComponent` function can be used
* to create an instance of a ComponentRef dynamically and attach it to an ApplicationRef,
* so that it gets included into change detection cycles.
*
* Note: the example uses standalone components, but the function can also be used for
* non-standalone components (declared in an NgModule) as well.
*
* ```typescript
* @Component({
* standalone: true,
* template: `Hello {{ name }}!`
* })
* class HelloComponent {
* name = 'Angular';
* }
*
* @Component({
* standalone: true,
* template: `<div id="hello-component-host"></div>`
* })
* class RootComponent {}
*
* // Bootstrap an application.
* const applicationRef = await bootstrapApplication(RootComponent);
*
* // Locate a DOM node that would be used as a host.
* const hostElement = document.getElementById('hello-component-host');
*
* // Get an `EnvironmentInjector` instance from the `ApplicationRef`.
* const environmentInjector = applicationRef.injector;
*
* // We can now create a `ComponentRef` instance.
* const componentRef = createComponent(HelloComponent, {hostElement, environmentInjector});
*
* // Last step is to register the newly created ref using the `ApplicationRef` instance
* // to include the component view into change detection cycles.
* applicationRef.attachView(componentRef.hostView);
* componentRef.changeDetectorRef.detectChanges();
* ```
*
* @param component Component class reference.
* @param options Set of options to use:
* * `environmentInjector`: An `EnvironmentInjector` instance to be used for the component.
* * `hostElement` (optional): A DOM node that should act as a host node for the component. If not
* provided, Angular creates one based on the tag name used in the component selector (and falls
* back to using `div` if selector doesn't have tag name info).
* * `elementInjector` (optional): An `ElementInjector` instance, see additional info about it
* [here](guide/di/hierarchical-dependency-injection#elementinjector).
* * `projectableNodes` (optional): A list of DOM nodes that should be projected through
* [`<ng-content>`](api/core/ng-content) of the new component instance.
* @returns ComponentRef instance that represents a given Component.
*
* @publicApi
*/
export function createComponent<C>(
component: Type<C>,
options: {
environmentInjector: EnvironmentInjector;
hostElement?: Element;
elementInjector?: Injector;
projectableNodes?: Node[][];
},
): ComponentRef<C> {
ngDevMode && assertComponentDef(component);
const componentDef = getComponentDef(component)!;
const elementInjector = options.elementInjector || getNullInjector();
const factory = new ComponentFactory<C>(componentDef);
return factory.create(
elementInjector,
options.projectableNodes,
options.hostElement,
options.environmentInjector,
);
}
/**
* An interface that describes the subset of component metadata
* that can be retrieved using the `reflectComponentType` function.
*
* @publicApi
*/
export interface ComponentMirror<C> {
/**
* The component's HTML selector.
*/
get selector(): string;
/**
* The type of component the factory will create.
*/
get type(): Type<C>;
/**
* The inputs of the component.
*/
get inputs(): ReadonlyArray<{
readonly propName: string;
readonly templateName: string;
readonly transform?: (value: any) => any;
readonly isSignal: boolean;
}>;
/**
* The outputs of the component.
*/
get outputs(): ReadonlyArray<{readonly propName: string; readonly templateName: string}>;
/**
* Selector for all <ng-content> elements in the component.
*/
get ngContentSelectors(): ReadonlyArray<string>;
/**
* Whether this component is marked as standalone.
* Note: an extra flag, not present in `ComponentFactory`.
*/
get isStandalone(): boolean;
/**
* // TODO(signals): Remove internal and add public documentation
* @internal
*/
get isSignal(): boolean;
}
/**
* Creates an object that allows to retrieve component metadata.
*
* @usageNotes
*
* The example below demonstrates how to use the function and how the fields
* of the returned object map to the component metadata.
*
* ```typescript
* @Component({
* standalone: true,
* selector: 'foo-component',
* template: `
* <ng-content></ng-content>
* <ng-content select="content-selector-a"></ng-content>
* `,
* })
* class FooComponent {
* @Input('inputName') inputPropName: string;
* @Output('outputName') outputPropName = new EventEmitter<void>();
* }
*
* const mirror = reflectComponentType(FooComponent);
* expect(mirror.type).toBe(FooComponent);
* expect(mirror.selector).toBe('foo-component');
* expect(mirror.isStandalone).toBe(true);
* expect(mirror.inputs).toEqual([{propName: 'inputName', templateName: 'inputPropName'}]);
* expect(mirror.outputs).toEqual([{propName: 'outputName', templateName: 'outputPropName'}]);
* expect(mirror.ngContentSelectors).toEqual([
* '*', // first `<ng-content>` in a template, the selector defaults to `*`
* 'content-selector-a' // second `<ng-content>` in a template
* ]);
* ```
*
* @param component Component class reference.
* @returns An object that allows to retrieve component metadata.
*
* @publicApi
*/
export function reflectComponentType<C>(component: Type<C>): ComponentMirror<C> | null {
const componentDef = getComponentDef(component);
if (!componentDef) return null;
const factory = new ComponentFactory<C>(componentDef);
return {
get selector(): string {
return factory.selector;
},
get type(): Type<C> {
return factory.componentType;
},
get inputs(): ReadonlyArray<{
propName: string;
templateName: string;
transform?: (value: any) => any;
isSignal: boolean;
}> {
return factory.inputs;
},
get outputs(): ReadonlyArray<{propName: string; templateName: string}> {
return factory.outputs;
},
get ngContentSelectors(): ReadonlyArray<string> {
return factory.ngContentSelectors;
},
get isStandalone(): boolean {
return componentDef.standalone;
},
get isSignal(): boolean {
return componentDef.signals;
},
};
}
| {
"end_byte": 7013,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/component.ts"
} |
angular/packages/core/src/render3/pure_function.ts_0_6647 | /**
* @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 {assertIndexInRange} from '../util/assert';
import {
bindingUpdated,
bindingUpdated2,
bindingUpdated3,
bindingUpdated4,
getBinding,
updateBinding,
} from './bindings';
import {LView} from './interfaces/view';
import {getBindingRoot, getLView} from './state';
import {NO_CHANGE} from './tokens';
/**
* Bindings for pure functions are stored after regular bindings.
*
* |-------decls------|---------vars---------| |----- hostVars (dir1) ------|
* ------------------------------------------------------------------------------------------
* | nodes/refs/pipes | bindings | fn slots | injector | dir1 | host bindings | host slots |
* ------------------------------------------------------------------------------------------
* ^ ^
* TView.bindingStartIndex TView.expandoStartIndex
*
* Pure function instructions are given an offset from the binding root. Adding the offset to the
* binding root gives the first index where the bindings are stored. In component views, the binding
* root is the bindingStartIndex. In host bindings, the binding root is the expandoStartIndex +
* any directive instances + any hostVars in directives evaluated before it.
*
* See VIEW_DATA.md for more information about host binding resolution.
*/
/**
* If the value hasn't been saved, calls the pure function to store and return the
* value. If it has been saved, returns the saved value.
*
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn Function that returns a value
* @param thisArg Optional calling context of pureFn
* @returns value
*
* @codeGenApi
*/
export function ɵɵpureFunction0<T>(slotOffset: number, pureFn: () => T, thisArg?: any): T {
const bindingIndex = getBindingRoot() + slotOffset;
const lView = getLView();
return lView[bindingIndex] === NO_CHANGE
? updateBinding(lView, bindingIndex, thisArg ? pureFn.call(thisArg) : pureFn())
: getBinding(lView, bindingIndex);
}
/**
* If the value of the provided exp has changed, calls the pure function to return
* an updated value. Or if the value has not changed, returns cached value.
*
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn Function that returns an updated value
* @param exp Updated expression value
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*
* @codeGenApi
*/
export function ɵɵpureFunction1(
slotOffset: number,
pureFn: (v: any) => any,
exp: any,
thisArg?: any,
): any {
return pureFunction1Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp, thisArg);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn
* @param exp1
* @param exp2
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*
* @codeGenApi
*/
export function ɵɵpureFunction2(
slotOffset: number,
pureFn: (v1: any, v2: any) => any,
exp1: any,
exp2: any,
thisArg?: any,
): any {
return pureFunction2Internal(
getLView(),
getBindingRoot(),
slotOffset,
pureFn,
exp1,
exp2,
thisArg,
);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn
* @param exp1
* @param exp2
* @param exp3
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*
* @codeGenApi
*/
export function ɵɵpureFunction3(
slotOffset: number,
pureFn: (v1: any, v2: any, v3: any) => any,
exp1: any,
exp2: any,
exp3: any,
thisArg?: any,
): any {
return pureFunction3Internal(
getLView(),
getBindingRoot(),
slotOffset,
pureFn,
exp1,
exp2,
exp3,
thisArg,
);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn
* @param exp1
* @param exp2
* @param exp3
* @param exp4
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*
* @codeGenApi
*/
export function ɵɵpureFunction4(
slotOffset: number,
pureFn: (v1: any, v2: any, v3: any, v4: any) => any,
exp1: any,
exp2: any,
exp3: any,
exp4: any,
thisArg?: any,
): any {
return pureFunction4Internal(
getLView(),
getBindingRoot(),
slotOffset,
pureFn,
exp1,
exp2,
exp3,
exp4,
thisArg,
);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn
* @param exp1
* @param exp2
* @param exp3
* @param exp4
* @param exp5
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*
* @codeGenApi
*/
export function ɵɵpureFunction5(
slotOffset: number,
pureFn: (v1: any, v2: any, v3: any, v4: any, v5: any) => any,
exp1: any,
exp2: any,
exp3: any,
exp4: any,
exp5: any,
thisArg?: any,
): any {
const bindingIndex = getBindingRoot() + slotOffset;
const lView = getLView();
const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
return bindingUpdated(lView, bindingIndex + 4, exp5) || different
? updateBinding(
lView,
bindingIndex + 5,
thisArg
? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5)
: pureFn(exp1, exp2, exp3, exp4, exp5),
)
: getBinding(lView, bindingIndex + 5);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn
* @param exp1
* @param exp2
* @param exp3
* @param exp4
* @param exp5
* @param exp6
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*
* @codeGenApi
*/
export func | {
"end_byte": 6647,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/pure_function.ts"
} |
angular/packages/core/src/render3/pure_function.ts_6648_13325 | ion ɵɵpureFunction6(
slotOffset: number,
pureFn: (v1: any, v2: any, v3: any, v4: any, v5: any, v6: any) => any,
exp1: any,
exp2: any,
exp3: any,
exp4: any,
exp5: any,
exp6: any,
thisArg?: any,
): any {
const bindingIndex = getBindingRoot() + slotOffset;
const lView = getLView();
const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
return bindingUpdated2(lView, bindingIndex + 4, exp5, exp6) || different
? updateBinding(
lView,
bindingIndex + 6,
thisArg
? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6)
: pureFn(exp1, exp2, exp3, exp4, exp5, exp6),
)
: getBinding(lView, bindingIndex + 6);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn
* @param exp1
* @param exp2
* @param exp3
* @param exp4
* @param exp5
* @param exp6
* @param exp7
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*
* @codeGenApi
*/
export function ɵɵpureFunction7(
slotOffset: number,
pureFn: (v1: any, v2: any, v3: any, v4: any, v5: any, v6: any, v7: any) => any,
exp1: any,
exp2: any,
exp3: any,
exp4: any,
exp5: any,
exp6: any,
exp7: any,
thisArg?: any,
): any {
const bindingIndex = getBindingRoot() + slotOffset;
const lView = getLView();
let different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
return bindingUpdated3(lView, bindingIndex + 4, exp5, exp6, exp7) || different
? updateBinding(
lView,
bindingIndex + 7,
thisArg
? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7)
: pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7),
)
: getBinding(lView, bindingIndex + 7);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn
* @param exp1
* @param exp2
* @param exp3
* @param exp4
* @param exp5
* @param exp6
* @param exp7
* @param exp8
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*
* @codeGenApi
*/
export function ɵɵpureFunction8(
slotOffset: number,
pureFn: (v1: any, v2: any, v3: any, v4: any, v5: any, v6: any, v7: any, v8: any) => any,
exp1: any,
exp2: any,
exp3: any,
exp4: any,
exp5: any,
exp6: any,
exp7: any,
exp8: any,
thisArg?: any,
): any {
const bindingIndex = getBindingRoot() + slotOffset;
const lView = getLView();
const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
return bindingUpdated4(lView, bindingIndex + 4, exp5, exp6, exp7, exp8) || different
? updateBinding(
lView,
bindingIndex + 8,
thisArg
? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8)
: pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8),
)
: getBinding(lView, bindingIndex + 8);
}
/**
* pureFunction instruction that can support any number of bindings.
*
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn A pure function that takes binding values and builds an object or array
* containing those values.
* @param exps An array of binding values
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*
* @codeGenApi
*/
export function ɵɵpureFunctionV(
slotOffset: number,
pureFn: (...v: any[]) => any,
exps: any[],
thisArg?: any,
): any {
return pureFunctionVInternal(getLView(), getBindingRoot(), slotOffset, pureFn, exps, thisArg);
}
/**
* Results of a pure function invocation are stored in LView in a dedicated slot that is initialized
* to NO_CHANGE. In rare situations a pure pipe might throw an exception on the very first
* invocation and not produce any valid results. In this case LView would keep holding the NO_CHANGE
* value. The NO_CHANGE is not something that we can use in expressions / bindings thus we convert
* it to `undefined`.
*/
function getPureFunctionReturnValue(lView: LView, returnValueIndex: number) {
ngDevMode && assertIndexInRange(lView, returnValueIndex);
const lastReturnValue = lView[returnValueIndex];
return lastReturnValue === NO_CHANGE ? undefined : lastReturnValue;
}
/**
* If the value of the provided exp has changed, calls the pure function to return
* an updated value. Or if the value has not changed, returns cached value.
*
* @param lView LView in which the function is being executed.
* @param bindingRoot Binding root index.
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn Function that returns an updated value
* @param exp Updated expression value
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*/
export function pureFunction1Internal(
lView: LView,
bindingRoot: number,
slotOffset: number,
pureFn: (v: any) => any,
exp: any,
thisArg?: any,
): any {
const bindingIndex = bindingRoot + slotOffset;
return bindingUpdated(lView, bindingIndex, exp)
? updateBinding(lView, bindingIndex + 1, thisArg ? pureFn.call(thisArg, exp) : pureFn(exp))
: getPureFunctionReturnValue(lView, bindingIndex + 1);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param lView LView in which the function is being executed.
* @param bindingRoot Binding root index.
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn
* @param exp1
* @param exp2
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*/
export function pureFunction2Internal(
lView: LView,
bindingRoot: number,
slotOffset: number,
pureFn: (v1: any, v2: any) => any,
exp1: any,
exp2: any,
thisArg?: any,
): any {
const bindingIndex = bindingRoot + slotOffset;
return bindingUpdated2(lView, bindingIndex, exp1, exp2)
? updateBinding(
lView,
bindingIndex + 2,
thisArg ? pureFn.call(thisArg, exp1, exp2) : pureFn(exp1, exp2),
)
: getPureFunctionReturnValue(lView, bindingIndex + 2);
}
/**
* If the valu | {
"end_byte": 13325,
"start_byte": 6648,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/pure_function.ts"
} |
angular/packages/core/src/render3/pure_function.ts_13327_16628 | of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param lView LView in which the function is being executed.
* @param bindingRoot Binding root index.
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn
* @param exp1
* @param exp2
* @param exp3
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*/
export function pureFunction3Internal(
lView: LView,
bindingRoot: number,
slotOffset: number,
pureFn: (v1: any, v2: any, v3: any) => any,
exp1: any,
exp2: any,
exp3: any,
thisArg?: any,
): any {
const bindingIndex = bindingRoot + slotOffset;
return bindingUpdated3(lView, bindingIndex, exp1, exp2, exp3)
? updateBinding(
lView,
bindingIndex + 3,
thisArg ? pureFn.call(thisArg, exp1, exp2, exp3) : pureFn(exp1, exp2, exp3),
)
: getPureFunctionReturnValue(lView, bindingIndex + 3);
}
/**
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param lView LView in which the function is being executed.
* @param bindingRoot Binding root index.
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn
* @param exp1
* @param exp2
* @param exp3
* @param exp4
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*
*/
export function pureFunction4Internal(
lView: LView,
bindingRoot: number,
slotOffset: number,
pureFn: (v1: any, v2: any, v3: any, v4: any) => any,
exp1: any,
exp2: any,
exp3: any,
exp4: any,
thisArg?: any,
): any {
const bindingIndex = bindingRoot + slotOffset;
return bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4)
? updateBinding(
lView,
bindingIndex + 4,
thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4) : pureFn(exp1, exp2, exp3, exp4),
)
: getPureFunctionReturnValue(lView, bindingIndex + 4);
}
/**
* pureFunction instruction that can support any number of bindings.
*
* If the value of any provided exp has changed, calls the pure function to return
* an updated value. Or if no values have changed, returns cached value.
*
* @param lView LView in which the function is being executed.
* @param bindingRoot Binding root index.
* @param slotOffset the offset from binding root to the reserved slot
* @param pureFn A pure function that takes binding values and builds an object or array
* containing those values.
* @param exps An array of binding values
* @param thisArg Optional calling context of pureFn
* @returns Updated or cached value
*/
export function pureFunctionVInternal(
lView: LView,
bindingRoot: number,
slotOffset: number,
pureFn: (...v: any[]) => any,
exps: any[],
thisArg?: any,
): any {
let bindingIndex = bindingRoot + slotOffset;
let different = false;
for (let i = 0; i < exps.length; i++) {
bindingUpdated(lView, bindingIndex++, exps[i]) && (different = true);
}
return different
? updateBinding(lView, bindingIndex, pureFn.apply(thisArg, exps))
: getPureFunctionReturnValue(lView, bindingIndex);
}
| {
"end_byte": 16628,
"start_byte": 13327,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/pure_function.ts"
} |
angular/packages/core/src/render3/collect_native_nodes.ts_0_4098 | /**
* @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 {assertParentView} from './assert';
import {icuContainerIterate} from './i18n/i18n_tree_shaking';
import {CONTAINER_HEADER_OFFSET, LContainer, NATIVE} from './interfaces/container';
import {TIcuContainerNode, TNode, TNodeType} from './interfaces/node';
import {RNode} from './interfaces/renderer_dom';
import {isLContainer} from './interfaces/type_checks';
import {DECLARATION_COMPONENT_VIEW, HOST, LView, TVIEW, TView} from './interfaces/view';
import {assertTNodeType} from './node_assert';
import {getProjectionNodes} from './node_manipulation';
import {getLViewParent, unwrapRNode} from './util/view_utils';
export function collectNativeNodes(
tView: TView,
lView: LView,
tNode: TNode | null,
result: any[],
isProjection: boolean = false,
): any[] {
while (tNode !== null) {
// Let declarations don't have corresponding DOM nodes so we skip over them.
if (tNode.type === TNodeType.LetDeclaration) {
tNode = isProjection ? tNode.projectionNext : tNode.next;
continue;
}
ngDevMode &&
assertTNodeType(
tNode,
TNodeType.AnyRNode | TNodeType.AnyContainer | TNodeType.Projection | TNodeType.Icu,
);
const lNode = lView[tNode.index];
if (lNode !== null) {
result.push(unwrapRNode(lNode));
}
// A given lNode can represent either a native node or a LContainer (when it is a host of a
// ViewContainerRef). When we find a LContainer we need to descend into it to collect root nodes
// from the views in this container.
if (isLContainer(lNode)) {
collectNativeNodesInLContainer(lNode, result);
}
const tNodeType = tNode.type;
if (tNodeType & TNodeType.ElementContainer) {
collectNativeNodes(tView, lView, tNode.child, result);
} else if (tNodeType & TNodeType.Icu) {
const nextRNode = icuContainerIterate(tNode as TIcuContainerNode, lView);
let rNode: RNode | null;
while ((rNode = nextRNode())) {
result.push(rNode);
}
} else if (tNodeType & TNodeType.Projection) {
const nodesInSlot = getProjectionNodes(lView, tNode);
if (Array.isArray(nodesInSlot)) {
result.push(...nodesInSlot);
} else {
const parentView = getLViewParent(lView[DECLARATION_COMPONENT_VIEW])!;
ngDevMode && assertParentView(parentView);
collectNativeNodes(parentView[TVIEW], parentView, nodesInSlot, result, true);
}
}
tNode = isProjection ? tNode.projectionNext : tNode.next;
}
return result;
}
/**
* Collects all root nodes in all views in a given LContainer.
*/
export function collectNativeNodesInLContainer(lContainer: LContainer, result: any[]) {
for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
const lViewInAContainer = lContainer[i];
const lViewFirstChildTNode = lViewInAContainer[TVIEW].firstChild;
if (lViewFirstChildTNode !== null) {
collectNativeNodes(lViewInAContainer[TVIEW], lViewInAContainer, lViewFirstChildTNode, result);
}
}
// When an LContainer is created, the anchor (comment) node is:
// - (1) either reused in case of an ElementContainer (<ng-container>)
// - (2) or a new comment node is created
// In the first case, the anchor comment node would be added to the final
// list by the code in the `collectNativeNodes` function
// (see the `result.push(unwrapRNode(lNode))` line), but the second
// case requires extra handling: the anchor node needs to be added to the
// final list manually. See additional information in the `createAnchorNode`
// function in the `view_container_ref.ts`.
//
// In the first case, the same reference would be stored in the `NATIVE`
// and `HOST` slots in an LContainer. Otherwise, this is the second case and
// we should add an element to the final list.
if (lContainer[NATIVE] !== lContainer[HOST]) {
result.push(lContainer[NATIVE]);
}
}
| {
"end_byte": 4098,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/collect_native_nodes.ts"
} |
angular/packages/core/src/render3/di_setup.ts_0_2675 | /**
* @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 {resolveForwardRef} from '../di/forward_ref';
import {ClassProvider, Provider} from '../di/interface/provider';
import {isClassProvider, isTypeProvider, SingleProvider} from '../di/provider_collection';
import {providerToFactory} from '../di/r3_injector';
import {assertDefined} from '../util/assert';
import {emitProviderConfiguredEvent, runInInjectorProfilerContext} from './debug/injector_profiler';
import {
diPublicInInjector,
getNodeInjectable,
getOrCreateNodeInjectorForNode,
NodeInjector,
} from './di';
import {ɵɵdirectiveInject} from './instructions/all';
import {DirectiveDef} from './interfaces/definition';
import {NodeInjectorFactory} from './interfaces/injector';
import {
TContainerNode,
TDirectiveHostNode,
TElementContainerNode,
TElementNode,
TNodeProviderIndexes,
} from './interfaces/node';
import {isComponentDef} from './interfaces/type_checks';
import {DestroyHookData, LView, TData, TVIEW, TView} from './interfaces/view';
import {getCurrentTNode, getLView, getTView} from './state';
/**
* Resolves the providers which are defined in the DirectiveDef.
*
* When inserting the tokens and the factories in their respective arrays, we can assume that
* this method is called first for the component (if any), and then for other directives on the same
* node.
* As a consequence,the providers are always processed in that order:
* 1) The view providers of the component
* 2) The providers of the component
* 3) The providers of the other directives
* This matches the structure of the injectables arrays of a view (for each node).
* So the tokens and the factories can be pushed at the end of the arrays, except
* in one case for multi providers.
*
* @param def the directive definition
* @param providers: Array of `providers`.
* @param viewProviders: Array of `viewProviders`.
*/
export function providersResolver<T>(
def: DirectiveDef<T>,
providers: Provider[],
viewProviders: Provider[],
): void {
const tView = getTView();
if (tView.firstCreatePass) {
const isComponent = isComponentDef(def);
// The list of view providers is processed first, and the flags are updated
resolveProvider(viewProviders, tView.data, tView.blueprint, isComponent, true);
// Then, the list of providers is processed, and the flags are updated
resolveProvider(providers, tView.data, tView.blueprint, isComponent, false);
}
}
/**
* Resolves a provider and publishes it to the DI system.
*/
f | {
"end_byte": 2675,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/di_setup.ts"
} |
angular/packages/core/src/render3/di_setup.ts_2676_11720 | nction resolveProvider(
provider: Provider,
tInjectables: TData,
lInjectablesBlueprint: NodeInjectorFactory[],
isComponent: boolean,
isViewProvider: boolean,
): void {
provider = resolveForwardRef(provider);
if (Array.isArray(provider)) {
// Recursively call `resolveProvider`
// Recursion is OK in this case because this code will not be in hot-path once we implement
// cloning of the initial state.
for (let i = 0; i < provider.length; i++) {
resolveProvider(
provider[i],
tInjectables,
lInjectablesBlueprint,
isComponent,
isViewProvider,
);
}
} else {
const tView = getTView();
const lView = getLView();
const tNode = getCurrentTNode()!;
let token: any = isTypeProvider(provider) ? provider : resolveForwardRef(provider.provide);
const providerFactory = providerToFactory(provider);
if (ngDevMode) {
const injector = new NodeInjector(
tNode as TElementNode | TContainerNode | TElementContainerNode,
lView,
);
runInInjectorProfilerContext(injector, token, () => {
emitProviderConfiguredEvent(provider as SingleProvider, isViewProvider);
});
}
const beginIndex = tNode.providerIndexes & TNodeProviderIndexes.ProvidersStartIndexMask;
const endIndex = tNode.directiveStart;
const cptViewProvidersCount =
tNode.providerIndexes >> TNodeProviderIndexes.CptViewProvidersCountShift;
if (isTypeProvider(provider) || !provider.multi) {
// Single provider case: the factory is created and pushed immediately
const factory = new NodeInjectorFactory(providerFactory, isViewProvider, ɵɵdirectiveInject);
const existingFactoryIndex = indexOf(
token,
tInjectables,
isViewProvider ? beginIndex : beginIndex + cptViewProvidersCount,
endIndex,
);
if (existingFactoryIndex === -1) {
diPublicInInjector(
getOrCreateNodeInjectorForNode(
tNode as TElementNode | TContainerNode | TElementContainerNode,
lView,
),
tView,
token,
);
registerDestroyHooksIfSupported(tView, provider, tInjectables.length);
tInjectables.push(token);
tNode.directiveStart++;
tNode.directiveEnd++;
if (isViewProvider) {
tNode.providerIndexes += TNodeProviderIndexes.CptViewProvidersCountShifter;
}
lInjectablesBlueprint.push(factory);
lView.push(factory);
} else {
lInjectablesBlueprint[existingFactoryIndex] = factory;
lView[existingFactoryIndex] = factory;
}
} else {
// Multi provider case:
// We create a multi factory which is going to aggregate all the values.
// Since the output of such a factory depends on content or view injection,
// we create two of them, which are linked together.
//
// The first one (for view providers) is always in the first block of the injectables array,
// and the second one (for providers) is always in the second block.
// This is important because view providers have higher priority. When a multi token
// is being looked up, the view providers should be found first.
// Note that it is not possible to have a multi factory in the third block (directive block).
//
// The algorithm to process multi providers is as follows:
// 1) If the multi provider comes from the `viewProviders` of the component:
// a) If the special view providers factory doesn't exist, it is created and pushed.
// b) Else, the multi provider is added to the existing multi factory.
// 2) If the multi provider comes from the `providers` of the component or of another
// directive:
// a) If the multi factory doesn't exist, it is created and provider pushed into it.
// It is also linked to the multi factory for view providers, if it exists.
// b) Else, the multi provider is added to the existing multi factory.
const existingProvidersFactoryIndex = indexOf(
token,
tInjectables,
beginIndex + cptViewProvidersCount,
endIndex,
);
const existingViewProvidersFactoryIndex = indexOf(
token,
tInjectables,
beginIndex,
beginIndex + cptViewProvidersCount,
);
const doesProvidersFactoryExist =
existingProvidersFactoryIndex >= 0 && lInjectablesBlueprint[existingProvidersFactoryIndex];
const doesViewProvidersFactoryExist =
existingViewProvidersFactoryIndex >= 0 &&
lInjectablesBlueprint[existingViewProvidersFactoryIndex];
if (
(isViewProvider && !doesViewProvidersFactoryExist) ||
(!isViewProvider && !doesProvidersFactoryExist)
) {
// Cases 1.a and 2.a
diPublicInInjector(
getOrCreateNodeInjectorForNode(
tNode as TElementNode | TContainerNode | TElementContainerNode,
lView,
),
tView,
token,
);
const factory = multiFactory(
isViewProvider ? multiViewProvidersFactoryResolver : multiProvidersFactoryResolver,
lInjectablesBlueprint.length,
isViewProvider,
isComponent,
providerFactory,
);
if (!isViewProvider && doesViewProvidersFactoryExist) {
lInjectablesBlueprint[existingViewProvidersFactoryIndex].providerFactory = factory;
}
registerDestroyHooksIfSupported(tView, provider, tInjectables.length, 0);
tInjectables.push(token);
tNode.directiveStart++;
tNode.directiveEnd++;
if (isViewProvider) {
tNode.providerIndexes += TNodeProviderIndexes.CptViewProvidersCountShifter;
}
lInjectablesBlueprint.push(factory);
lView.push(factory);
} else {
// Cases 1.b and 2.b
const indexInFactory = multiFactoryAdd(
lInjectablesBlueprint![
isViewProvider ? existingViewProvidersFactoryIndex : existingProvidersFactoryIndex
],
providerFactory,
!isViewProvider && isComponent,
);
registerDestroyHooksIfSupported(
tView,
provider,
existingProvidersFactoryIndex > -1
? existingProvidersFactoryIndex
: existingViewProvidersFactoryIndex,
indexInFactory,
);
}
if (!isViewProvider && isComponent && doesViewProvidersFactoryExist) {
lInjectablesBlueprint[existingViewProvidersFactoryIndex].componentProviders!++;
}
}
}
}
/**
* Registers the `ngOnDestroy` hook of a provider, if the provider supports destroy hooks.
* @param tView `TView` in which to register the hook.
* @param provider Provider whose hook should be registered.
* @param contextIndex Index under which to find the context for the hook when it's being invoked.
* @param indexInFactory Only required for `multi` providers. Index of the provider in the multi
* provider factory.
*/
function registerDestroyHooksIfSupported(
tView: TView,
provider: Exclude<Provider, any[]>,
contextIndex: number,
indexInFactory?: number,
) {
const providerIsTypeProvider = isTypeProvider(provider);
const providerIsClassProvider = isClassProvider(provider);
if (providerIsTypeProvider || providerIsClassProvider) {
// Resolve forward references as `useClass` can hold a forward reference.
const classToken = providerIsClassProvider ? resolveForwardRef(provider.useClass) : provider;
const prototype = classToken.prototype;
const ngOnDestroy = prototype.ngOnDestroy;
if (ngOnDestroy) {
const hooks = tView.destroyHooks || (tView.destroyHooks = []);
if (!providerIsTypeProvider && (provider as ClassProvider).multi) {
ngDevMode &&
assertDefined(
indexInFactory,
'indexInFactory when registering multi factory destroy hook',
);
const existingCallbacksIndex = hooks.indexOf(contextIndex);
if (existingCallbacksIndex === -1) {
hooks.push(contextIndex, [indexInFactory, ngOnDestroy]);
} else {
(hooks[existingCallbacksIndex + 1] as DestroyHookData).push(indexInFactory!, ngOnDestroy);
}
} else {
hooks.push(contextIndex, ngOnDestroy);
}
}
}
}
/**
* Add a factory in a multi factory.
* @returns Index at which the factory was inserted.
*/
function multiFactoryAdd(
multiFactory: NodeInjectorFactory,
factory: () => any,
isComponentProvider: boolean,
): number {
if (isComponentProvider) {
multiFactory.componentProviders!++;
}
return multiFactory.multi!.push(factory) - 1;
}
/**
* Returns the index of item in the array, but only in the begin to end range.
*/
function indexOf(item: any, arr: any[], begin: number, end: number) {
for (let i = begin; i < end; i++) {
if (arr[i] === item) return i;
}
return -1;
}
/**
* Use this with `multi` `providers`.
*/
fun | {
"end_byte": 11720,
"start_byte": 2676,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/di_setup.ts"
} |
angular/packages/core/src/render3/di_setup.ts_11721_13925 | tion multiProvidersFactoryResolver(
this: NodeInjectorFactory,
_: undefined,
tData: TData,
lData: LView,
tNode: TDirectiveHostNode,
): any[] {
return multiResolve(this.multi!, []);
}
/**
* Use this with `multi` `viewProviders`.
*
* This factory knows how to concatenate itself with the existing `multi` `providers`.
*/
function multiViewProvidersFactoryResolver(
this: NodeInjectorFactory,
_: undefined,
tData: TData,
lView: LView,
tNode: TDirectiveHostNode,
): any[] {
const factories = this.multi!;
let result: any[];
if (this.providerFactory) {
const componentCount = this.providerFactory.componentProviders!;
const multiProviders = getNodeInjectable(
lView,
lView[TVIEW],
this.providerFactory!.index!,
tNode,
);
// Copy the section of the array which contains `multi` `providers` from the component
result = multiProviders.slice(0, componentCount);
// Insert the `viewProvider` instances.
multiResolve(factories, result);
// Copy the section of the array which contains `multi` `providers` from other directives
for (let i = componentCount; i < multiProviders.length; i++) {
result.push(multiProviders[i]);
}
} else {
result = [];
// Insert the `viewProvider` instances.
multiResolve(factories, result);
}
return result;
}
/**
* Maps an array of factories into an array of values.
*/
function multiResolve(factories: Array<() => any>, result: any[]): any[] {
for (let i = 0; i < factories.length; i++) {
const factory = factories[i]! as () => null;
result.push(factory());
}
return result;
}
/**
* Creates a multi factory.
*/
function multiFactory(
factoryFn: (
this: NodeInjectorFactory,
_: undefined,
tData: TData,
lData: LView,
tNode: TDirectiveHostNode,
) => any,
index: number,
isViewProvider: boolean,
isComponent: boolean,
f: () => any,
): NodeInjectorFactory {
const factory = new NodeInjectorFactory(factoryFn, isViewProvider, ɵɵdirectiveInject);
factory.multi = [];
factory.index = index;
factory.componentProviders = 0;
multiFactoryAdd(factory, f, isComponent && !isViewProvider);
return factory;
}
| {
"end_byte": 13925,
"start_byte": 11721,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/di_setup.ts"
} |
angular/packages/core/src/render3/component_ref.ts_0_5542 | /**
* @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 {setActiveConsumer} from '@angular/core/primitives/signals';
import {ChangeDetectorRef} from '../change_detection/change_detector_ref';
import {
ChangeDetectionScheduler,
NotificationSource,
} from '../change_detection/scheduling/zoneless_scheduling';
import {Injector} from '../di/injector';
import {EnvironmentInjector} from '../di/r3_injector';
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {DehydratedView} from '../hydration/interfaces';
import {retrieveHydrationInfo} from '../hydration/utils';
import {Type} from '../interface/type';
import {
ComponentFactory as AbstractComponentFactory,
ComponentRef as AbstractComponentRef,
} from '../linker/component_factory';
import {ComponentFactoryResolver as AbstractComponentFactoryResolver} from '../linker/component_factory_resolver';
import {createElementRef, ElementRef} from '../linker/element_ref';
import {NgModuleRef} from '../linker/ng_module_factory';
import {Renderer2, RendererFactory2} from '../render/api';
import {Sanitizer} from '../sanitization/sanitizer';
import {assertDefined, assertGreaterThan, assertIndexInRange} from '../util/assert';
import {assertComponentType, assertNoDuplicateDirectives} from './assert';
import {attachPatchData} from './context_discovery';
import {getComponentDef} from './def_getters';
import {depsTracker} from './deps_tracker/deps_tracker';
import {getNodeInjectable, NodeInjector} from './di';
import {registerPostOrderHooks} from './hooks';
import {reportUnknownPropertyError} from './instructions/element_validation';
import {markViewDirty} from './instructions/mark_view_dirty';
import {renderView} from './instructions/render';
import {
addToEndOfViewTree,
createLView,
createTView,
executeContentQueries,
getInitialLViewFlagsFromDef,
getOrCreateComponentTView,
getOrCreateTNode,
initializeDirectives,
invokeDirectivesHostBindings,
locateHostElement,
markAsComponentHost,
setInputsForProperty,
} from './instructions/shared';
import {ComponentDef, DirectiveDef, HostDirectiveDefs} from './interfaces/definition';
import {InputFlags} from './interfaces/input_flags';
import {
NodeInputBindings,
TContainerNode,
TElementContainerNode,
TElementNode,
TNode,
TNodeType,
} from './interfaces/node';
import {Renderer} from './interfaces/renderer';
import {RElement, RNode} from './interfaces/renderer_dom';
import {
CONTEXT,
HEADER_OFFSET,
INJECTOR,
LView,
LViewEnvironment,
LViewFlags,
TVIEW,
TViewType,
} from './interfaces/view';
import {MATH_ML_NAMESPACE, SVG_NAMESPACE} from './namespaces';
import {createElementNode, setupStaticAttributes, writeDirectClass} from './node_manipulation';
import {
extractAttrsAndClassesFromSelector,
stringifyCSSSelectorList,
} from './node_selector_matcher';
import {enterView, getCurrentTNode, getLView, leaveView} from './state';
import {computeStaticStyling} from './styling/static_styling';
import {mergeHostAttrs, setUpAttributes} from './util/attrs_utils';
import {debugStringifyTypeForError, stringifyForError} from './util/stringify_utils';
import {getComponentLViewByIndex, getNativeByTNode, getTNode} from './util/view_utils';
import {ViewRef} from './view_ref';
import {ChainedInjector} from './chained_injector';
import {unregisterLView} from './interfaces/lview_tracking';
export class ComponentFactoryResolver extends AbstractComponentFactoryResolver {
/**
* @param ngModule The NgModuleRef to which all resolved factories are bound.
*/
constructor(private ngModule?: NgModuleRef<any>) {
super();
}
override resolveComponentFactory<T>(component: Type<T>): AbstractComponentFactory<T> {
ngDevMode && assertComponentType(component);
const componentDef = getComponentDef(component)!;
return new ComponentFactory(componentDef, this.ngModule);
}
}
function toRefArray<T>(
map: DirectiveDef<T>['inputs'],
isInputMap: true,
): ComponentFactory<T>['inputs'];
function toRefArray<T>(
map: DirectiveDef<T>['outputs'],
isInput: false,
): ComponentFactory<T>['outputs'];
function toRefArray<
T,
IsInputMap extends boolean,
Return extends IsInputMap extends true
? ComponentFactory<T>['inputs']
: ComponentFactory<T>['outputs'],
>(map: DirectiveDef<T>['inputs'] | DirectiveDef<T>['outputs'], isInputMap: IsInputMap): Return {
const array: Return = [] as unknown as Return;
for (const publicName in map) {
if (!map.hasOwnProperty(publicName)) {
continue;
}
const value = map[publicName];
if (value === undefined) {
continue;
}
const isArray = Array.isArray(value);
const propName: string = isArray ? value[0] : value;
const flags: InputFlags = isArray ? value[1] : InputFlags.None;
if (isInputMap) {
(array as ComponentFactory<T>['inputs']).push({
propName: propName,
templateName: publicName,
isSignal: (flags & InputFlags.SignalBased) !== 0,
});
} else {
(array as ComponentFactory<T>['outputs']).push({
propName: propName,
templateName: publicName,
});
}
}
return array;
}
function getNamespace(elementName: string): string | null {
const name = elementName.toLowerCase();
return name === 'svg' ? SVG_NAMESPACE : name === 'math' ? MATH_ML_NAMESPACE : null;
}
/**
* ComponentFactory interface implementation.
*/ | {
"end_byte": 5542,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/component_ref.ts"
} |
angular/packages/core/src/render3/component_ref.ts_5543_14579 | export class ComponentFactory<T> extends AbstractComponentFactory<T> {
override selector: string;
override componentType: Type<any>;
override ngContentSelectors: string[];
isBoundToModule: boolean;
override get inputs(): {
propName: string;
templateName: string;
isSignal: boolean;
transform?: (value: any) => any;
}[] {
const componentDef = this.componentDef;
const inputTransforms = componentDef.inputTransforms;
const refArray = toRefArray(componentDef.inputs, true);
if (inputTransforms !== null) {
for (const input of refArray) {
if (inputTransforms.hasOwnProperty(input.propName)) {
input.transform = inputTransforms[input.propName];
}
}
}
return refArray;
}
override get outputs(): {propName: string; templateName: string}[] {
return toRefArray(this.componentDef.outputs, false);
}
/**
* @param componentDef The component definition.
* @param ngModule The NgModuleRef to which the factory is bound.
*/
constructor(
private componentDef: ComponentDef<any>,
private ngModule?: NgModuleRef<any>,
) {
super();
this.componentType = componentDef.type;
this.selector = stringifyCSSSelectorList(componentDef.selectors);
this.ngContentSelectors = componentDef.ngContentSelectors
? componentDef.ngContentSelectors
: [];
this.isBoundToModule = !!ngModule;
}
override create(
injector: Injector,
projectableNodes?: any[][] | undefined,
rootSelectorOrNode?: any,
environmentInjector?: NgModuleRef<any> | EnvironmentInjector | undefined,
): AbstractComponentRef<T> {
const prevConsumer = setActiveConsumer(null);
try {
// Check if the component is orphan
if (
ngDevMode &&
(typeof ngJitMode === 'undefined' || ngJitMode) &&
this.componentDef.debugInfo?.forbidOrphanRendering
) {
if (depsTracker.isOrphanComponent(this.componentType)) {
throw new RuntimeError(
RuntimeErrorCode.RUNTIME_DEPS_ORPHAN_COMPONENT,
`Orphan component found! Trying to render the component ${debugStringifyTypeForError(
this.componentType,
)} without first loading the NgModule that declares it. It is recommended to make this component standalone in order to avoid this error. If this is not possible now, import the component's NgModule in the appropriate NgModule, or the standalone component in which you are trying to render this component. If this is a lazy import, load the NgModule lazily as well and use its module injector.`,
);
}
}
environmentInjector = environmentInjector || this.ngModule;
let realEnvironmentInjector =
environmentInjector instanceof EnvironmentInjector
? environmentInjector
: environmentInjector?.injector;
if (realEnvironmentInjector && this.componentDef.getStandaloneInjector !== null) {
realEnvironmentInjector =
this.componentDef.getStandaloneInjector(realEnvironmentInjector) ||
realEnvironmentInjector;
}
const rootViewInjector = realEnvironmentInjector
? new ChainedInjector(injector, realEnvironmentInjector)
: injector;
const rendererFactory = rootViewInjector.get(RendererFactory2, null);
if (rendererFactory === null) {
throw new RuntimeError(
RuntimeErrorCode.RENDERER_NOT_FOUND,
ngDevMode &&
'Angular was not able to inject a renderer (RendererFactory2). ' +
'Likely this is due to a broken DI hierarchy. ' +
'Make sure that any injector used to create this component has a correct parent.',
);
}
const sanitizer = rootViewInjector.get(Sanitizer, null);
const changeDetectionScheduler = rootViewInjector.get(ChangeDetectionScheduler, null);
const environment: LViewEnvironment = {
rendererFactory,
sanitizer,
changeDetectionScheduler,
};
const hostRenderer = rendererFactory.createRenderer(null, this.componentDef);
// Determine a tag name used for creating host elements when this component is created
// dynamically. Default to 'div' if this component did not specify any tag name in its
// selector.
const elementName = (this.componentDef.selectors[0][0] as string) || 'div';
const hostRNode = rootSelectorOrNode
? locateHostElement(
hostRenderer,
rootSelectorOrNode,
this.componentDef.encapsulation,
rootViewInjector,
)
: createElementNode(hostRenderer, elementName, getNamespace(elementName));
let rootFlags = LViewFlags.IsRoot;
if (this.componentDef.signals) {
rootFlags |= LViewFlags.SignalView;
} else if (!this.componentDef.onPush) {
rootFlags |= LViewFlags.CheckAlways;
}
let hydrationInfo: DehydratedView | null = null;
if (hostRNode !== null) {
hydrationInfo = retrieveHydrationInfo(hostRNode, rootViewInjector, true /* isRootView */);
}
// Create the root view. Uses empty TView and ContentTemplate.
const rootTView = createTView(
TViewType.Root,
null,
null,
1,
0,
null,
null,
null,
null,
null,
null,
);
const rootLView = createLView(
null,
rootTView,
null,
rootFlags,
null,
null,
environment,
hostRenderer,
rootViewInjector,
null,
hydrationInfo,
);
// rootView is the parent when bootstrapping
// TODO(misko): it looks like we are entering view here but we don't really need to as
// `renderView` does that. However as the code is written it is needed because
// `createRootComponentView` and `createRootComponent` both read global state. Fixing those
// issues would allow us to drop this.
enterView(rootLView);
let component: T;
let tElementNode: TElementNode;
let componentView: LView | null = null;
try {
const rootComponentDef = this.componentDef;
let rootDirectives: DirectiveDef<unknown>[];
let hostDirectiveDefs: HostDirectiveDefs | null = null;
if (rootComponentDef.findHostDirectiveDefs) {
rootDirectives = [];
hostDirectiveDefs = new Map();
rootComponentDef.findHostDirectiveDefs(
rootComponentDef,
rootDirectives,
hostDirectiveDefs,
);
rootDirectives.push(rootComponentDef);
ngDevMode && assertNoDuplicateDirectives(rootDirectives);
} else {
rootDirectives = [rootComponentDef];
}
const hostTNode = createRootComponentTNode(rootLView, hostRNode);
componentView = createRootComponentView(
hostTNode,
hostRNode,
rootComponentDef,
rootDirectives,
rootLView,
environment,
hostRenderer,
);
tElementNode = getTNode(rootTView, HEADER_OFFSET) as TElementNode;
// TODO(crisbeto): in practice `hostRNode` should always be defined, but there are some
// tests where the renderer is mocked out and `undefined` is returned. We should update the
// tests so that this check can be removed.
if (hostRNode) {
setRootNodeAttributes(hostRenderer, rootComponentDef, hostRNode, rootSelectorOrNode);
}
if (projectableNodes !== undefined) {
projectNodes(tElementNode, this.ngContentSelectors, projectableNodes);
}
// TODO: should LifecycleHooksFeature and other host features be generated by the compiler
// and executed here? Angular 5 reference: https://stackblitz.com/edit/lifecycle-hooks-vcref
component = createRootComponent(
componentView,
rootComponentDef,
rootDirectives,
hostDirectiveDefs,
rootLView,
[LifecycleHooksFeature],
);
renderView(rootTView, rootLView, null);
} catch (e) {
// Stop tracking the views if creation failed since
// the consumer won't have a way to dereference them.
if (componentView !== null) {
unregisterLView(componentView);
}
unregisterLView(rootLView);
throw e;
} finally {
leaveView();
}
return new ComponentRef(
this.componentType,
component,
createElementRef(tElementNode, rootLView),
rootLView,
tElementNode,
);
} finally {
setActiveConsumer(prevConsumer);
}
}
}
/**
* Represents an instance of a Component created via a {@link ComponentFactory}.
*
* `ComponentRef` provides access to the Component Instance as well other objects related to this
* Component Instance and allows you to destroy the Component Instance via the {@link #destroy}
* method.
*
*/ | {
"end_byte": 14579,
"start_byte": 5543,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/component_ref.ts"
} |
angular/packages/core/src/render3/component_ref.ts_14580_21727 | export class ComponentRef<T> extends AbstractComponentRef<T> {
override instance: T;
override hostView: ViewRef<T>;
override changeDetectorRef: ChangeDetectorRef;
override componentType: Type<T>;
private previousInputValues: Map<string, unknown> | null = null;
constructor(
componentType: Type<T>,
instance: T,
public location: ElementRef,
private _rootLView: LView,
private _tNode: TElementNode | TContainerNode | TElementContainerNode,
) {
super();
this.instance = instance;
this.hostView = this.changeDetectorRef = new ViewRef<T>(
_rootLView,
undefined /* _cdRefInjectingView */,
false /* notifyErrorHandler */,
);
this.componentType = componentType;
}
override setInput(name: string, value: unknown): void {
const inputData = this._tNode.inputs;
let dataValue: NodeInputBindings[typeof name] | undefined;
if (inputData !== null && (dataValue = inputData[name])) {
this.previousInputValues ??= new Map();
// Do not set the input if it is the same as the last value
// This behavior matches `bindingUpdated` when binding inputs in templates.
if (
this.previousInputValues.has(name) &&
Object.is(this.previousInputValues.get(name), value)
) {
return;
}
const lView = this._rootLView;
setInputsForProperty(lView[TVIEW], lView, dataValue, name, value);
this.previousInputValues.set(name, value);
const childComponentLView = getComponentLViewByIndex(this._tNode.index, lView);
markViewDirty(childComponentLView, NotificationSource.SetInput);
} else {
if (ngDevMode) {
const cmpNameForError = stringifyForError(this.componentType);
let message = `Can't set value of the '${name}' input on the '${cmpNameForError}' component. `;
message += `Make sure that the '${name}' property is annotated with @Input() or a mapped @Input('${name}') exists.`;
reportUnknownPropertyError(message);
}
}
}
override get injector(): Injector {
return new NodeInjector(this._tNode, this._rootLView);
}
override destroy(): void {
this.hostView.destroy();
}
override onDestroy(callback: () => void): void {
this.hostView.onDestroy(callback);
}
}
/** Represents a HostFeature function. */
type HostFeature = <T>(component: T, componentDef: ComponentDef<T>) => void;
/** Creates a TNode that can be used to instantiate a root component. */
function createRootComponentTNode(lView: LView, rNode: RNode): TElementNode {
const tView = lView[TVIEW];
const index = HEADER_OFFSET;
ngDevMode && assertIndexInRange(lView, index);
lView[index] = rNode;
// '#host' is added here as we don't know the real host DOM name (we don't want to read it) and at
// the same time we want to communicate the debug `TNode` that this is a special `TNode`
// representing a host element.
return getOrCreateTNode(tView, index, TNodeType.Element, '#host', null);
}
/**
* Creates the root component view and the root component node.
*
* @param hostRNode Render host element.
* @param rootComponentDef ComponentDef
* @param rootView The parent view where the host node is stored
* @param rendererFactory Factory to be used for creating child renderers.
* @param hostRenderer The current renderer
* @param sanitizer The sanitizer, if provided
*
* @returns Component view created
*/
function createRootComponentView(
tNode: TElementNode,
hostRNode: RElement | null,
rootComponentDef: ComponentDef<any>,
rootDirectives: DirectiveDef<any>[],
rootView: LView,
environment: LViewEnvironment,
hostRenderer: Renderer,
): LView {
const tView = rootView[TVIEW];
applyRootComponentStyling(rootDirectives, tNode, hostRNode, hostRenderer);
// Hydration info is on the host element and needs to be retrieved
// and passed to the component LView.
let hydrationInfo: DehydratedView | null = null;
if (hostRNode !== null) {
hydrationInfo = retrieveHydrationInfo(hostRNode, rootView[INJECTOR]!);
}
const viewRenderer = environment.rendererFactory.createRenderer(hostRNode, rootComponentDef);
const componentView = createLView(
rootView,
getOrCreateComponentTView(rootComponentDef),
null,
getInitialLViewFlagsFromDef(rootComponentDef),
rootView[tNode.index],
tNode,
environment,
viewRenderer,
null,
null,
hydrationInfo,
);
if (tView.firstCreatePass) {
markAsComponentHost(tView, tNode, rootDirectives.length - 1);
}
addToEndOfViewTree(rootView, componentView);
// Store component view at node index, with node as the HOST
return (rootView[tNode.index] = componentView);
}
/** Sets up the styling information on a root component. */
function applyRootComponentStyling(
rootDirectives: DirectiveDef<any>[],
tNode: TElementNode,
rNode: RElement | null,
hostRenderer: Renderer,
): void {
for (const def of rootDirectives) {
tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, def.hostAttrs);
}
if (tNode.mergedAttrs !== null) {
computeStaticStyling(tNode, tNode.mergedAttrs, true);
if (rNode !== null) {
setupStaticAttributes(hostRenderer, rNode, tNode);
}
}
}
/**
* Creates a root component and sets it up with features and host bindings.Shared by
* renderComponent() and ViewContainerRef.createComponent().
*/
function createRootComponent<T>(
componentView: LView,
rootComponentDef: ComponentDef<T>,
rootDirectives: DirectiveDef<any>[],
hostDirectiveDefs: HostDirectiveDefs | null,
rootLView: LView,
hostFeatures: HostFeature[] | null,
): any {
const rootTNode = getCurrentTNode() as TElementNode;
ngDevMode && assertDefined(rootTNode, 'tNode should have been already created');
const tView = rootLView[TVIEW];
const native = getNativeByTNode(rootTNode, rootLView);
initializeDirectives(tView, rootLView, rootTNode, rootDirectives, null, hostDirectiveDefs);
for (let i = 0; i < rootDirectives.length; i++) {
const directiveIndex = rootTNode.directiveStart + i;
const directiveInstance = getNodeInjectable(rootLView, tView, directiveIndex, rootTNode);
attachPatchData(directiveInstance, rootLView);
}
invokeDirectivesHostBindings(tView, rootLView, rootTNode);
if (native) {
attachPatchData(native, rootLView);
}
// We're guaranteed for the `componentOffset` to be positive here
// since a root component always matches a component def.
ngDevMode &&
assertGreaterThan(rootTNode.componentOffset, -1, 'componentOffset must be great than -1');
const component = getNodeInjectable(
rootLView,
tView,
rootTNode.directiveStart + rootTNode.componentOffset,
rootTNode,
);
componentView[CONTEXT] = rootLView[CONTEXT] = component;
if (hostFeatures !== null) {
for (const feature of hostFeatures) {
feature(component, rootComponentDef);
}
}
// We want to generate an empty QueryList for root content queries for backwards
// compatibility with ViewEngine.
executeContentQueries(tView, rootTNode, rootLView);
return component;
}
/** Sets the static attributes on a root component. */ | {
"end_byte": 21727,
"start_byte": 14580,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/component_ref.ts"
} |
angular/packages/core/src/render3/component_ref.ts_21728_24050 | function setRootNodeAttributes(
hostRenderer: Renderer2,
componentDef: ComponentDef<unknown>,
hostRNode: RElement,
rootSelectorOrNode: any,
) {
if (rootSelectorOrNode) {
// The placeholder will be replaced with the actual version at build time.
setUpAttributes(hostRenderer, hostRNode, ['ng-version', '0.0.0-PLACEHOLDER']);
} else {
// If host element is created as a part of this function call (i.e. `rootSelectorOrNode`
// is not defined), also apply attributes and classes extracted from component selector.
// Extract attributes and classes from the first selector only to match VE behavior.
const {attrs, classes} = extractAttrsAndClassesFromSelector(componentDef.selectors[0]);
if (attrs) {
setUpAttributes(hostRenderer, hostRNode, attrs);
}
if (classes && classes.length > 0) {
writeDirectClass(hostRenderer, hostRNode, classes.join(' '));
}
}
}
/** Projects the `projectableNodes` that were specified when creating a root component. */
function projectNodes(
tNode: TElementNode,
ngContentSelectors: string[],
projectableNodes: any[][],
) {
const projection: (TNode | RNode[] | null)[] = (tNode.projection = []);
for (let i = 0; i < ngContentSelectors.length; i++) {
const nodesforSlot = projectableNodes[i];
// Projectable nodes can be passed as array of arrays or an array of iterables (ngUpgrade
// case). Here we do normalize passed data structure to be an array of arrays to avoid
// complex checks down the line.
// We also normalize the length of the passed in projectable nodes (to match the number of
// <ng-container> slots defined by a component).
projection.push(nodesforSlot != null && nodesforSlot.length ? Array.from(nodesforSlot) : null);
}
}
/**
* Used to enable lifecycle hooks on the root component.
*
* Include this feature when calling `renderComponent` if the root component
* you are rendering has lifecycle hooks defined. Otherwise, the hooks won't
* be called properly.
*
* Example:
*
* ```
* renderComponent(AppComponent, {hostFeatures: [LifecycleHooksFeature]});
* ```
*/
export function LifecycleHooksFeature(): void {
const tNode = getCurrentTNode()!;
ngDevMode && assertDefined(tNode, 'TNode is required');
registerPostOrderHooks(getLView()[TVIEW], tNode);
} | {
"end_byte": 24050,
"start_byte": 21728,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/component_ref.ts"
} |
angular/packages/core/src/render3/apply_value_input_field.ts_0_603 | /**
* @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 {InputSignalNode} from '../authoring/input/input_signal_node';
export function applyValueToInputField<T>(
instance: T,
inputSignalNode: null | InputSignalNode<unknown, unknown>,
privateName: string,
value: unknown,
) {
if (inputSignalNode !== null) {
inputSignalNode.applyValueToInputSignal(inputSignalNode, value);
} else {
(instance as any)[privateName] = value;
}
}
| {
"end_byte": 603,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/apply_value_input_field.ts"
} |
angular/packages/core/src/render3/view_context.ts_0_657 | /**
* @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 type {TNode} from './interfaces/node';
import type {LView} from './interfaces/view';
import {getCurrentTNode, getLView} from './state';
export class ViewContext {
constructor(
readonly view: LView,
readonly node: TNode,
) {}
/**
* @internal
* @nocollapse
*/
static __NG_ELEMENT_ID__ = injectViewContext;
}
export function injectViewContext(): ViewContext {
return new ViewContext(getLView()!, getCurrentTNode()!);
}
| {
"end_byte": 657,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/view_context.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.