id
stringlengths
6
6
text
stringlengths
20
17.2k
title
stringclasses
1 value
009606
describe('validator', () => { it('should run validator with the initial value', () => { const c = new FormControl('value', Validators.required); expect(c.valid).toEqual(true); }); it('should rerun the validator when the value changes', () => { const c = new FormControl('value', Validators.required); c.setValue(null); expect(c.valid).toEqual(false); }); it('should support arrays of validator functions if passed', () => { const c = new FormControl('value', [Validators.required, Validators.minLength(3)]); c.setValue('a'); expect(c.valid).toEqual(false); c.setValue('aaa'); expect(c.valid).toEqual(true); }); it('should support single validator from options obj', () => { const c: FormControl = new FormControl(null, {validators: Validators.required}); expect(c.valid).toEqual(false); expect(c.errors).toEqual({required: true}); c.setValue('value'); expect(c.valid).toEqual(true); }); it('should support multiple validators from options obj', () => { const c: FormControl = new FormControl(null, { validators: [Validators.required, Validators.minLength(3)], }); expect(c.valid).toEqual(false); expect(c.errors).toEqual({required: true}); c.setValue('aa'); expect(c.valid).toEqual(false); expect(c.errors).toEqual({minlength: {requiredLength: 3, actualLength: 2}}); c.setValue('aaa'); expect(c.valid).toEqual(true); }); it('should support a null validators value', () => { const c = new FormControl(null, {validators: null}); expect(c.valid).toEqual(true); }); it('should support an empty options obj', () => { const c = new FormControl(null, {}); expect(c.valid).toEqual(true); }); it('should return errors', () => { const c = new FormControl(null, Validators.required); expect(c.errors).toEqual({'required': true}); }); it('should set single validator', () => { const c: FormControl = new FormControl(null); expect(c.valid).toEqual(true); c.setValidators(Validators.required); c.setValue(null); expect(c.valid).toEqual(false); c.setValue('abc'); expect(c.valid).toEqual(true); }); it('should set multiple validators from array', () => { const c = new FormControl(''); expect(c.valid).toEqual(true); c.setValidators([Validators.minLength(5), Validators.required]); c.setValue(''); expect(c.valid).toEqual(false); c.setValue('abc'); expect(c.valid).toEqual(false); c.setValue('abcde'); expect(c.valid).toEqual(true); }); it('should override validators using `setValidators` function', () => { const c = new FormControl(''); expect(c.valid).toEqual(true); c.setValidators([Validators.minLength(5), Validators.required]); c.setValue(''); expect(c.valid).toEqual(false); c.setValue('abc'); expect(c.valid).toEqual(false); c.setValue('abcde'); expect(c.valid).toEqual(true); // Define new set of validators, overriding previously applied ones. c.setValidators([Validators.maxLength(2)]); c.setValue('abcdef'); expect(c.valid).toEqual(false); c.setValue('a'); expect(c.valid).toEqual(true); }); it('should not mutate the validators array when overriding using setValidators', () => { const control = new FormControl(''); const originalValidators = [Validators.required]; control.setValidators(originalValidators); control.addValidators(Validators.minLength(10)); expect(originalValidators.length).toBe(1); }); it('should override validators by setting `control.validator` field value', () => { const c = new FormControl(''); expect(c.valid).toEqual(true); // Define new set of validators, overriding previously applied ones. c.validator = Validators.compose([Validators.minLength(5), Validators.required]); c.setValue(''); expect(c.valid).toEqual(false); c.setValue('abc'); expect(c.valid).toEqual(false); c.setValue('abcde'); expect(c.valid).toEqual(true); // Define new set of validators, overriding previously applied ones. c.validator = Validators.compose([Validators.maxLength(2)]); c.setValue('abcdef'); expect(c.valid).toEqual(false); c.setValue('a'); expect(c.valid).toEqual(true); }); it('should clear validators', () => { const c = new FormControl('', Validators.required); expect(c.valid).toEqual(false); c.clearValidators(); expect(c.validator).toEqual(null); c.setValue(''); expect(c.valid).toEqual(true); }); it('should add after clearing', () => { const c = new FormControl('', Validators.required); expect(c.valid).toEqual(false); c.clearValidators(); expect(c.validator).toEqual(null); c.setValidators([Validators.required]); expect(c.validator).not.toBe(null); }); it('should check presence of and remove a validator set in the control constructor', () => { const c = new FormControl('', Validators.required); expect(c.hasValidator(Validators.required)).toEqual(true); c.removeValidators(Validators.required); expect(c.hasValidator(Validators.required)).toEqual(false); c.addValidators(Validators.required); expect(c.hasValidator(Validators.required)).toEqual(true); }); it('should check presence of and remove a validator set with addValidators', () => { const c = new FormControl(''); expect(c.hasValidator(Validators.required)).toEqual(false); c.addValidators(Validators.required); expect(c.hasValidator(Validators.required)).toEqual(true); c.removeValidators(Validators.required); expect(c.hasValidator(Validators.required)).toEqual(false); }); it('should check presence of and remove multiple validators set at the same time', () => { const c = new FormControl('3'); const minValidator = Validators.min(4); c.addValidators([Validators.required, minValidator]); expect(c.hasValidator(Validators.required)).toEqual(true); expect(c.hasValidator(minValidator)).toEqual(true); c.removeValidators([Validators.required, minValidator]); expect(c.hasValidator(Validators.required)).toEqual(false); expect(c.hasValidator(minValidator)).toEqual(false); }); it('should be able to remove a validator added multiple times', () => { const c = new FormControl('', Validators.required); c.addValidators(Validators.required); c.addValidators(Validators.required); expect(c.hasValidator(Validators.required)).toEqual(true); c.removeValidators(Validators.required); expect(c.hasValidator(Validators.required)).toEqual(false); }); it('should not mutate the validators array when adding/removing sync validators', () => { const originalValidators = [Validators.required]; const control = new FormControl('', originalValidators); control.addValidators(Validators.min(10)); expect(originalValidators.length).toBe(1); control.removeValidators(Validators.required); expect(originalValidators.length).toBe(1); }); it('should not mutate the validators array when adding/removing async validators', () => { const firstValidator = asyncValidator('one'); const secondValidator = asyncValidator('two'); const originalValidators = [firstValidator]; const control = new FormControl('', null, originalValidators); control.addAsyncValidators(secondValidator); expect(originalValidators.length).toBe(1); control.removeAsyncValidators(firstValidator); expect(originalValidators.length).toBe(1); }); it('should return false when checking presence of a validator not identical by reference', () => { const minValidator = Validators.min(5); const c = new FormControl('1', minValidator); expect(c.hasValidator(minValidator)).toEqual(true); expect(c.hasValidator(Validators.min(5))).toEqual(false); }); });
009610
describe('valueChanges & statusChanges', () => { let c: FormControl; beforeEach(() => { c = new FormControl('old', Validators.required); }); it('should fire an event after the value has been updated', (done) => { c.valueChanges.subscribe({ next: (value: any) => { expect(c.value).toEqual('new'); expect(value).toEqual('new'); done(); }, }); c.setValue('new'); }); it('should fire an event after the status has been updated to invalid', fakeAsync(() => { c.statusChanges.subscribe({ next: (status: any) => { expect(c.status).toEqual('INVALID'); expect(status).toEqual('INVALID'); }, }); c.setValue(''); tick(); })); it('should fire statusChanges events for async validators added via options object', fakeAsync(() => { // The behavior can be tested for each of the model types. let statuses: string[] = []; // Create a form control with an async validator added via options object. const asc = new FormControl('', {asyncValidators: [() => Promise.resolve(null)]}); // Subscribe to status changes. asc.statusChanges.subscribe((status: any) => statuses.push(status)); // After a tick, the async validator should change status PENDING -> VALID. tick(); expect(statuses).toEqual(['VALID']); })); it('should fire an event after the status has been updated to pending', fakeAsync(() => { const c = new FormControl('old', Validators.required, asyncValidator('expected')); const log: string[] = []; c.valueChanges.subscribe({next: (value: any) => log.push(`value: '${value}'`)}); c.statusChanges.subscribe({next: (status: any) => log.push(`status: '${status}'`)}); c.setValue(''); tick(); c.setValue('nonEmpty'); tick(); c.setValue('expected'); tick(); expect(log).toEqual([ "value: ''", "status: 'INVALID'", "value: 'nonEmpty'", "status: 'PENDING'", "status: 'INVALID'", "value: 'expected'", "status: 'PENDING'", "status: 'VALID'", ]); })); it('should update set errors and status before emitting an event', fakeAsync(() => { c.setValue(''); tick(); expect(c.valid).toEqual(false); expect(c.errors).toEqual({'required': true}); })); it('should return a cold observable', fakeAsync(() => { let value: string | null = null; c.setValue('will be ignored'); c.valueChanges.subscribe((v) => (value = v)); c.setValue('new'); tick(); // @ts-expect-error see microsoft/TypeScript#9998 expect(value).toEqual('new'); })); }); describe('setErrors', () => { it('should set errors on a control', () => { const c = new FormControl('someValue'); c.setErrors({'someError': true}); expect(c.valid).toEqual(false); expect(c.errors).toEqual({'someError': true}); }); it('should reset the errors and validity when the value changes', () => { const c = new FormControl('someValue', Validators.required); c.setErrors({'someError': true}); c.setValue(''); expect(c.errors).toEqual({'required': true}); }); it("should update the parent group's validity", () => { const c = new FormControl('someValue'); const g = new FormGroup({'one': c}); expect(g.valid).toEqual(true); c.setErrors({'someError': true}); expect(g.valid).toEqual(false); }); it("should not reset parent's errors", () => { const c = new FormControl('someValue'); const g = new FormGroup({'one': c}); g.setErrors({'someGroupError': true}); c.setErrors({'someError': true}); expect(g.errors).toEqual({'someGroupError': true}); }); it('should reset errors when updating a value', () => { const c = new FormControl('oldValue'); const g = new FormGroup({'one': c}); g.setErrors({'someGroupError': true}); c.setErrors({'someError': true}); c.setValue('newValue'); expect(c.errors).toEqual(null); expect(g.errors).toEqual(null); }); });
009630
describe('emit `statusChanges` and `valueChanges` with/without async/sync validators', () => { const attachEventsLogger = ( control: AbstractControl, log: string[], controlName?: string, ) => { const name = controlName ? ` (${controlName})` : ''; control.statusChanges.subscribe((status) => log.push(`status${name}: ${status}`)); control.valueChanges.subscribe((value) => log.push(`value${name}: ${JSON.stringify(value)}`), ); }; describe('stand alone controls', () => { it('should run the async validator on stand alone controls and set status to `INVALID`', fakeAsync(() => { const logs: string[] = []; const c = new FormControl('', null, simpleAsyncValidator({timeout: 0, shouldFail: true})); attachEventsLogger(c, logs); expect(logs.length).toBe(0); tick(1); c.setValue('new!', {emitEvent: true}); tick(1); // Note that above `simpleAsyncValidator` is called with `timeout:0`. When the timeout // is set to `0`, the function returns `of(error)`, and the function behaves in a // synchronous manner. Because of this there is no `PENDING` state as seen in the // `logs`. expect(logs).toEqual([ 'status: INVALID', // status change emitted as a result of initial async validator run 'value: "new!"', // value change emitted by `setValue` 'status: INVALID', // async validator run after `setValue` call ]); })); it('should run the async validator on stand alone controls and set status to `VALID`', fakeAsync(() => { const logs: string[] = []; const c = new FormControl('', null, asyncValidator('new!')); attachEventsLogger(c, logs); expect(logs.length).toBe(0); tick(1); c.setValue('new!', {emitEvent: true}); tick(1); expect(logs).toEqual([ 'status: INVALID', // status change emitted as a result of initial async validator run 'value: "new!"', // value change emitted by `setValue` 'status: PENDING', // status change emitted by `setValue` 'status: VALID', // async validator run after `setValue` call ]); })); it('should run the async validator on stand alone controls, include `PENDING` and set status to `INVALID`', fakeAsync(() => { const logs: string[] = []; const c = new FormControl('', null, simpleAsyncValidator({timeout: 1, shouldFail: true})); attachEventsLogger(c, logs); expect(logs.length).toBe(0); tick(1); c.setValue('new!', {emitEvent: true}); tick(1); expect(logs).toEqual([ 'status: INVALID', // status change emitted as a result of initial async validator run 'value: "new!"', // value change emitted by `setValue` 'status: PENDING', // status change emitted by `setValue` 'status: INVALID', // async validator run after `setValue` call ]); })); it('should run setValue before the initial async validator and set status to `VALID`', fakeAsync(() => { const logs: string[] = []; const c = new FormControl('', null, asyncValidator('new!')); attachEventsLogger(c, logs); expect(logs.length).toBe(0); c.setValue('new!', {emitEvent: true}); tick(1); // The `setValue` call invoked synchronously cancels the initial run of the // `asyncValidator` (which would cause the control status to be changed to `INVALID`), so // the log contains only events after calling `setValue`. expect(logs).toEqual([ 'value: "new!"', // value change emitted by `setValue` 'status: PENDING', // status change emitted by `setValue` 'status: VALID', // async validator run after `setValue` call ]); })); it('should run setValue before the initial async validator and set status to `INVALID`', fakeAsync(() => { const logs: string[] = []; const c = new FormControl('', null, simpleAsyncValidator({timeout: 1, shouldFail: true})); attachEventsLogger(c, logs); expect(logs.length).toBe(0); c.setValue('new!', {emitEvent: true}); tick(1); // The `setValue` call invoked synchronously cancels the initial run of the // `asyncValidator` (which would cause the control status to be changed to `INVALID`), so // the log contains only events after calling `setValue`. expect(logs).toEqual([ 'value: "new!"', // value change emitted by `setValue` 'status: PENDING', // status change emitted by `setValue` 'status: INVALID', // async validator run after `setValue` call ]); })); it('should cancel initial run of the async validator and not emit anything', fakeAsync(() => { const logger: string[] = []; const c = new FormControl('', null, simpleAsyncValidator({timeout: 1, shouldFail: true})); attachEventsLogger(c, logger); expect(logger.length).toBe(0); c.setValue('new!', {emitEvent: false}); tick(1); // Because we are calling `setValue` with `emitEvent: false`, nothing is emitted // and our logger remains empty expect(logger).toEqual([]); })); it('should cancel initial run of the async validator and emit on the event Observable', fakeAsync(() => { const c = new FormControl('', null, simpleAsyncValidator({timeout: 1, shouldFail: true})); const events: ControlEvent[] = []; c.events.subscribe((e) => events.push(e)); expect(events.length).toBe(0); c.setValue('new!'); tick(1); // validator was invoked twice (init + setValue) // but since we cancel pending validators we only get 1 status update cycle expect(events[0]).toBeInstanceOf(ValueChangeEvent); expect(events[1]).toBeInstanceOf(StatusChangeEvent); expect((events[1] as StatusChangeEvent).status).toBe('PENDING'); expect(events[2]).toBeInstanceOf(StatusChangeEvent); expect((events[2] as StatusChangeEvent).status).toBe('INVALID'); })); it('should run the sync validator on stand alone controls and set status to `INVALID`', fakeAsync(() => { const logs: string[] = []; const c = new FormControl('new!', Validators.required); attachEventsLogger(c, logs); expect(logs.length).toBe(0); tick(1); c.setValue('', {emitEvent: true}); tick(1); expect(logs).toEqual([ 'value: ""', // value change emitted by `setValue` 'status: INVALID', // status change emitted by `setValue` ]); })); it('should run the sync validator on stand alone controls and set status to `VALID`', fakeAsync(() => { const logs: string[] = []; const c = new FormControl('', Validators.required); attachEventsLogger(c, logs); expect(logs.length).toBe(0); tick(1); c.setValue('new!', {emitEvent: true}); tick(1); expect(logs).toEqual([ 'value: "new!"', // value change emitted by `setValue` 'status: VALID', // status change emitted by `setValue` ]); })); });
009664
/** * @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 {ɵRuntimeError as RuntimeError} from '@angular/core'; import {RuntimeErrorCode} from '../errors'; import { formArrayNameExample, formControlNameExample, formGroupNameExample, ngModelGroupExample, } from './error_examples'; export function controlParentException(nameOrIndex: string | number | null): Error { return new RuntimeError( RuntimeErrorCode.FORM_CONTROL_NAME_MISSING_PARENT, `formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). ${describeFormControl(nameOrIndex)} Example: ${formControlNameExample}`, ); } function describeFormControl(nameOrIndex: string | number | null): string { if (nameOrIndex == null || nameOrIndex === '') { return ''; } const valueType = typeof nameOrIndex === 'string' ? 'name' : 'index'; return `Affected Form Control ${valueType}: "${nameOrIndex}"`; } export function ngModelGroupException(): Error { return new RuntimeError( RuntimeErrorCode.FORM_CONTROL_NAME_INSIDE_MODEL_GROUP, `formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents that also have a "form" prefix: formGroupName, formArrayName, or formGroup. Option 1: Update the parent to be formGroupName (reactive form strategy) ${formGroupNameExample} Option 2: Use ngModel instead of formControlName (template-driven strategy) ${ngModelGroupExample}`, ); } export function missingFormException(): Error { return new RuntimeError( RuntimeErrorCode.FORM_GROUP_MISSING_INSTANCE, `formGroup expects a FormGroup instance. Please pass one in. Example: ${formControlNameExample}`, ); } export function groupParentException(): Error { return new RuntimeError( RuntimeErrorCode.FORM_GROUP_NAME_MISSING_PARENT, `formGroupName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). Example: ${formGroupNameExample}`, ); } export function arrayParentException(): Error { return new RuntimeError( RuntimeErrorCode.FORM_ARRAY_NAME_MISSING_PARENT, `formArrayName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). Example: ${formArrayNameExample}`, ); } export const disabledAttrWarning = ` It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors. Example: // Specify the \`disabled\` property at control creation time: form = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true}, Validators.required), last: new FormControl('Drew', Validators.required) }); // Controls can also be enabled/disabled after creation: form.get('first')?.enable(); form.get('last')?.disable(); `; export const asyncValidatorsDroppedWithOptsWarning = ` It looks like you're constructing using a FormControl with both an options argument and an async validators argument. Mixing these arguments will cause your async validators to be dropped. You should either put all your validators in the options object, or in separate validators arguments. For example: // Using validators arguments fc = new FormControl(42, Validators.required, myAsyncValidator); // Using AbstractControlOptions fc = new FormControl(42, {validators: Validators.required, asyncValidators: myAV}); // Do NOT mix them: async validators will be dropped! fc = new FormControl(42, {validators: Validators.required}, /* Oops! */ myAsyncValidator); `; export function ngModelWarning(directiveName: string): string { return ` It looks like you're using ngModel on the same form field as ${directiveName}. Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in a future version of Angular. For more information on this, see our API docs here: https://angular.io/api/forms/${ directiveName === 'formControl' ? 'FormControlDirective' : 'FormControlName' }#use-with-ngmodel `; } function describeKey(isFormGroup: boolean, key: string | number): string { return isFormGroup ? `with name: '${key}'` : `at index: ${key}`; } export function noControlsError(isFormGroup: boolean): string { return ` There are no form controls registered with this ${ isFormGroup ? 'group' : 'array' } yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout). `; } export function missingControlError(isFormGroup: boolean, key: string | number): string { return `Cannot find form control ${describeKey(isFormGroup, key)}`; } export function missingControlValueError(isFormGroup: boolean, key: string | number): string { return `Must supply a value for form control ${describeKey(isFormGroup, key)}`; }
009686
/** * @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 { booleanAttribute, Directive, forwardRef, Input, OnChanges, Provider, SimpleChanges, } from '@angular/core'; import {Observable} from 'rxjs'; import type {AbstractControl} from '../model/abstract_model'; import { emailValidator, maxLengthValidator, maxValidator, minLengthValidator, minValidator, NG_VALIDATORS, nullValidator, patternValidator, requiredTrueValidator, requiredValidator, } from '../validators'; /** * Method that updates string to integer if not already a number * * @param value The value to convert to integer. * @returns value of parameter converted to number or integer. */ function toInteger(value: string | number): number { return typeof value === 'number' ? value : parseInt(value, 10); } /** * Method that ensures that provided value is a float (and converts it to float if needed). * * @param value The value to convert to float. * @returns value of parameter converted to number or float. */ function toFloat(value: string | number): number { return typeof value === 'number' ? value : parseFloat(value); } /** * @description * Defines the map of errors returned from failed validation checks. * * @publicApi */ export type ValidationErrors = { [key: string]: any; }; /** * @description * An interface implemented by classes that perform synchronous validation. * * @usageNotes * * ### Provide a custom validator * * The following example implements the `Validator` interface to create a * validator directive with a custom error key. * * ```typescript * @Directive({ * selector: '[customValidator]', * providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}] * }) * class CustomValidatorDirective implements Validator { * validate(control: AbstractControl): ValidationErrors|null { * return {'custom': true}; * } * } * ``` * * @publicApi */ export interface Validator { /** * @description * Method that performs synchronous validation against the provided control. * * @param control The control to validate against. * * @returns A map of validation errors if validation fails, * otherwise null. */ validate(control: AbstractControl): ValidationErrors | null; /** * @description * Registers a callback function to call when the validator inputs change. * * @param fn The callback function */ registerOnValidatorChange?(fn: () => void): void; } /** * A base class for Validator-based Directives. The class contains common logic shared across such * Directives. * * For internal use only, this class is not intended for use outside of the Forms package. */ @Directive() abstract class AbstractValidatorDirective implements Validator, OnChanges { private _validator: ValidatorFn = nullValidator; private _onChange!: () => void; /** * A flag that tracks whether this validator is enabled. * * Marking it `internal` (vs `protected`), so that this flag can be used in host bindings of * directive classes that extend this base class. * @internal */ _enabled?: boolean; /** * Name of an input that matches directive selector attribute (e.g. `minlength` for * `MinLengthDirective`). An input with a given name might contain configuration information (like * `minlength='10'`) or a flag that indicates whether validator should be enabled (like * `[required]='false'`). * * @internal */ abstract inputName: string; /** * Creates an instance of a validator (specific to a directive that extends this base class). * * @internal */ abstract createValidator(input: unknown): ValidatorFn; /** * Performs the necessary input normalization based on a specific logic of a Directive. * For example, the function might be used to convert string-based representation of the * `minlength` input to an integer value that can later be used in the `Validators.minLength` * validator. * * @internal */ abstract normalizeInput(input: unknown): unknown; /** @nodoc */ ngOnChanges(changes: SimpleChanges): void { if (this.inputName in changes) { const input = this.normalizeInput(changes[this.inputName].currentValue); this._enabled = this.enabled(input); this._validator = this._enabled ? this.createValidator(input) : nullValidator; if (this._onChange) { this._onChange(); } } } /** @nodoc */ validate(control: AbstractControl): ValidationErrors | null { return this._validator(control); } /** @nodoc */ registerOnValidatorChange(fn: () => void): void { this._onChange = fn; } /** * @description * Determines whether this validator should be active or not based on an input. * Base class implementation checks whether an input is defined (if the value is different from * `null` and `undefined`). Validator classes that extend this base class can override this * function with the logic specific to a particular validator directive. */ enabled(input: unknown): boolean { return input != null /* both `null` and `undefined` */; } } /** * @description * Provider which adds `MaxValidator` to the `NG_VALIDATORS` multi-provider list. */ export const MAX_VALIDATOR: Provider = { provide: NG_VALIDATORS, useExisting: forwardRef(() => MaxValidator), multi: true, }; /** * A directive which installs the {@link MaxValidator} for any `formControlName`, * `formControl`, or control with `ngModel` that also has a `max` attribute. * * @see [Form Validation](guide/forms/form-validation) * * @usageNotes * * ### Adding a max validator * * The following example shows how to add a max validator to an input attached to an * ngModel binding. * * ```html * <input type="number" ngModel max="4"> * ``` * * @ngModule ReactiveFormsModule * @ngModule FormsModule * @publicApi */ @Directive({ selector: 'input[type=number][max][formControlName],input[type=number][max][formControl],input[type=number][max][ngModel]', providers: [MAX_VALIDATOR], host: {'[attr.max]': '_enabled ? max : null'}, standalone: false, }) export class MaxValidator extends AbstractValidatorDirective { /** * @description * Tracks changes to the max bound to this directive. */ @Input() max!: string | number | null; /** @internal */ override inputName = 'max'; /** @internal */ override normalizeInput = (input: string | number): number => toFloat(input); /** @internal */ override createValidator = (max: number): ValidatorFn => maxValidator(max); } /** * @description * Provider which adds `MinValidator` to the `NG_VALIDATORS` multi-provider list. */ export const MIN_VALIDATOR: Provider = { provide: NG_VALIDATORS, useExisting: forwardRef(() => MinValidator), multi: true, }; /** * A directive which installs the {@link MinValidator} for any `formControlName`, * `formControl`, or control with `ngModel` that also has a `min` attribute. * * @see [Form Validation](guide/forms/form-validation) * * @usageNotes * * ### Adding a min validator * * The following example shows how to add a min validator to an input attached to an * ngModel binding. * * ```html * <input type="number" ngModel min="4"> * ``` * * @ngModule ReactiveFormsModule * @ngModule FormsModule * @publicApi */ @Directive({ selector: 'input[type=number][min][formControlName],input[type=number][min][formControl],input[type=number][min][ngModel]', providers: [MIN_VALIDATOR], host: {'[attr.min]': '_enabled ? min : null'}, standalone: false, }) export class MinValidator extends AbstractValidatorDirective { /** * @description * Tracks changes to the min bound to this directive. */ @Input() min!: string | number | null; /** @internal */ override inputName = 'min'; /** @internal */ override normalizeInput = (input: string | number): number => toFloat(input); /** @internal */ override createValidator = (min: number): ValidatorFn => minValidator(min); }
009687
/** * @description * An interface implemented by classes that perform asynchronous validation. * * @usageNotes * * ### Provide a custom async validator directive * * The following example implements the `AsyncValidator` interface to create an * async validator directive with a custom error key. * * ```typescript * import { of } from 'rxjs'; * * @Directive({ * selector: '[customAsyncValidator]', * providers: [{provide: NG_ASYNC_VALIDATORS, useExisting: CustomAsyncValidatorDirective, multi: * true}] * }) * class CustomAsyncValidatorDirective implements AsyncValidator { * validate(control: AbstractControl): Observable<ValidationErrors|null> { * return of({'custom': true}); * } * } * ``` * * @publicApi */ export interface AsyncValidator extends Validator { /** * @description * Method that performs async validation against the provided control. * * @param control The control to validate against. * * @returns A promise or observable that resolves a map of validation errors * if validation fails, otherwise null. */ validate( control: AbstractControl, ): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>; } /** * @description * Provider which adds `RequiredValidator` to the `NG_VALIDATORS` multi-provider list. */ export const REQUIRED_VALIDATOR: Provider = { provide: NG_VALIDATORS, useExisting: forwardRef(() => RequiredValidator), multi: true, }; /** * @description * Provider which adds `CheckboxRequiredValidator` to the `NG_VALIDATORS` multi-provider list. */ export const CHECKBOX_REQUIRED_VALIDATOR: Provider = { provide: NG_VALIDATORS, useExisting: forwardRef(() => CheckboxRequiredValidator), multi: true, }; /** * @description * A directive that adds the `required` validator to any controls marked with the * `required` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list. * * @see [Form Validation](guide/forms/form-validation) * * @usageNotes * * ### Adding a required validator using template-driven forms * * ``` * <input name="fullName" ngModel required> * ``` * * @ngModule FormsModule * @ngModule ReactiveFormsModule * @publicApi */ @Directive({ selector: ':not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]', providers: [REQUIRED_VALIDATOR], host: {'[attr.required]': '_enabled ? "" : null'}, standalone: false, }) export class RequiredValidator extends AbstractValidatorDirective { /** * @description * Tracks changes to the required attribute bound to this directive. */ @Input() required!: boolean | string; /** @internal */ override inputName = 'required'; /** @internal */ override normalizeInput = booleanAttribute; /** @internal */ override createValidator = (input: boolean): ValidatorFn => requiredValidator; /** @nodoc */ override enabled(input: boolean): boolean { return input; } } /** * A Directive that adds the `required` validator to checkbox controls marked with the * `required` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list. * * @see [Form Validation](guide/forms/form-validation) * * @usageNotes * * ### Adding a required checkbox validator using template-driven forms * * The following example shows how to add a checkbox required validator to an input attached to an * ngModel binding. * * ``` * <input type="checkbox" name="active" ngModel required> * ``` * * @publicApi * @ngModule FormsModule * @ngModule ReactiveFormsModule */ @Directive({ selector: 'input[type=checkbox][required][formControlName],input[type=checkbox][required][formControl],input[type=checkbox][required][ngModel]', providers: [CHECKBOX_REQUIRED_VALIDATOR], host: {'[attr.required]': '_enabled ? "" : null'}, standalone: false, }) export class CheckboxRequiredValidator extends RequiredValidator { /** @internal */ override createValidator = (input: unknown): ValidatorFn => requiredTrueValidator; } /** * @description * Provider which adds `EmailValidator` to the `NG_VALIDATORS` multi-provider list. */ export const EMAIL_VALIDATOR: any = { provide: NG_VALIDATORS, useExisting: forwardRef(() => EmailValidator), multi: true, }; /** * A directive that adds the `email` validator to controls marked with the * `email` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list. * * The email validation is based on the WHATWG HTML specification with some enhancements to * incorporate more RFC rules. More information can be found on the [Validators.email * page](api/forms/Validators#email). * * @see [Form Validation](guide/forms/form-validation) * * @usageNotes * * ### Adding an email validator * * The following example shows how to add an email validator to an input attached to an ngModel * binding. * * ``` * <input type="email" name="email" ngModel email> * <input type="email" name="email" ngModel email="true"> * <input type="email" name="email" ngModel [email]="true"> * ``` * * @publicApi * @ngModule FormsModule * @ngModule ReactiveFormsModule */ @Directive({ selector: '[email][formControlName],[email][formControl],[email][ngModel]', providers: [EMAIL_VALIDATOR], standalone: false, }) export class EmailValidator extends AbstractValidatorDirective { /** * @description * Tracks changes to the email attribute bound to this directive. */ @Input() email!: boolean | string; /** @internal */ override inputName = 'email'; /** @internal */ override normalizeInput = booleanAttribute; /** @internal */ override createValidator = (input: number): ValidatorFn => emailValidator; /** @nodoc */ override enabled(input: boolean): boolean { return input; } } /** * @description * A function that receives a control and synchronously returns a map of * validation errors if present, otherwise null. * * @publicApi */ export interface ValidatorFn { (control: AbstractControl): ValidationErrors | null; } /** * @description * A function that receives a control and returns a Promise or observable * that emits validation errors if present, otherwise null. * * @publicApi */ export interface AsyncValidatorFn { ( control: AbstractControl, ): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>; } /** * @description * Provider which adds `MinLengthValidator` to the `NG_VALIDATORS` multi-provider list. */ export const MIN_LENGTH_VALIDATOR: any = { provide: NG_VALIDATORS, useExisting: forwardRef(() => MinLengthValidator), multi: true, }; /** * A directive that adds minimum length validation to controls marked with the * `minlength` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list. * * @see [Form Validation](guide/forms/form-validation) * * @usageNotes * * ### Adding a minimum length validator * * The following example shows how to add a minimum length validator to an input attached to an * ngModel binding. * * ```html * <input name="firstName" ngModel minlength="4"> * ``` * * @ngModule ReactiveFormsModule * @ngModule FormsModule * @publicApi */ @Directive({ selector: '[minlength][formControlName],[minlength][formControl],[minlength][ngModel]', providers: [MIN_LENGTH_VALIDATOR], host: {'[attr.minlength]': '_enabled ? minlength : null'}, standalone: false, }) export class MinLengthValidator extends AbstractValidatorDirective { /** * @description * Tracks changes to the minimum length bound to this directive. */ @Input() minlength!: string | number | null; /** @internal */ override inputName = 'minlength'; /** @internal */ override normalizeInput = (input: string | number): number => toInteger(input); /** @internal */ override createValidator = (minlength: number): ValidatorFn => minLengthValidator(minlength); } /** * @description * Provider which adds `MaxLengthValidator` to the `NG_VALIDATORS` multi-provider list. */ export const MAX_LENGTH_VALIDATOR: any = { provide: NG_VALIDATORS, useExisting: forwardRef(() => MaxLengthValidator), multi: true, };
009692
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Directive, ElementRef, forwardRef, Host, Input, OnDestroy, Optional, Provider, Renderer2, ɵRuntimeError as RuntimeError, } from '@angular/core'; import {RuntimeErrorCode} from '../errors'; import { BuiltInControlValueAccessor, ControlValueAccessor, NG_VALUE_ACCESSOR, } from './control_value_accessor'; const SELECT_VALUE_ACCESSOR: Provider = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => SelectControlValueAccessor), multi: true, }; function _buildValueString(id: string | null, value: any): string { if (id == null) return `${value}`; if (value && typeof value === 'object') value = 'Object'; return `${id}: ${value}`.slice(0, 50); } function _extractId(valueString: string): string { return valueString.split(':')[0]; } /** * @description * The `ControlValueAccessor` for writing select control values and listening to select control * changes. The value accessor is used by the `FormControlDirective`, `FormControlName`, and * `NgModel` directives. * * @usageNotes * * ### Using select controls in a reactive form * * The following examples show how to use a select control in a reactive form. * * {@example forms/ts/reactiveSelectControl/reactive_select_control_example.ts region='Component'} * * ### Using select controls in a template-driven form * * To use a select in a template-driven form, simply add an `ngModel` and a `name` * attribute to the main `<select>` tag. * * {@example forms/ts/selectControl/select_control_example.ts region='Component'} * * ### Customizing option selection * * Angular uses object identity to select option. It's possible for the identities of items * to change while the data does not. This can happen, for example, if the items are produced * from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the * second response will produce objects with different identities. * * To customize the default option comparison algorithm, `<select>` supports `compareWith` input. * `compareWith` takes a **function** which has two arguments: `option1` and `option2`. * If `compareWith` is given, Angular selects option by the return value of the function. * * ```ts * const selectedCountriesControl = new FormControl(); * ``` * * ``` * <select [compareWith]="compareFn" [formControl]="selectedCountriesControl"> * <option *ngFor="let country of countries" [ngValue]="country"> * {{country.name}} * </option> * </select> * * compareFn(c1: Country, c2: Country): boolean { * return c1 && c2 ? c1.id === c2.id : c1 === c2; * } * ``` * * **Note:** We listen to the 'change' event because 'input' events aren't fired * for selects in IE, see: * https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event#browser_compatibility * * @ngModule ReactiveFormsModule * @ngModule FormsModule * @publicApi */ @Directive({ selector: 'select:not([multiple])[formControlName],select:not([multiple])[formControl],select:not([multiple])[ngModel]', host: {'(change)': 'onChange($event.target.value)', '(blur)': 'onTouched()'}, providers: [SELECT_VALUE_ACCESSOR], standalone: false, }) export class SelectControlValueAccessor extends BuiltInControlValueAccessor implements ControlValueAccessor { /** @nodoc */ value: any; /** @internal */ _optionMap: Map<string, any> = new Map<string, any>(); /** @internal */ _idCounter: number = 0; /** * @description * Tracks the option comparison algorithm for tracking identities when * checking for changes. */ @Input() set compareWith(fn: (o1: any, o2: any) => boolean) { if (typeof fn !== 'function' && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw new RuntimeError( RuntimeErrorCode.COMPAREWITH_NOT_A_FN, `compareWith must be a function, but received ${JSON.stringify(fn)}`, ); } this._compareWith = fn; } private _compareWith: (o1: any, o2: any) => boolean = Object.is; /** * Sets the "value" property on the select element. * @nodoc */ writeValue(value: any): void { this.value = value; const id: string | null = this._getOptionId(value); const valueString = _buildValueString(id, value); this.setProperty('value', valueString); } /** * Registers a function called when the control value changes. * @nodoc */ override registerOnChange(fn: (value: any) => any): void { this.onChange = (valueString: string) => { this.value = this._getOptionValue(valueString); fn(this.value); }; } /** @internal */ _registerOption(): string { return (this._idCounter++).toString(); } /** @internal */ _getOptionId(value: any): string | null { for (const id of this._optionMap.keys()) { if (this._compareWith(this._optionMap.get(id), value)) return id; } return null; } /** @internal */ _getOptionValue(valueString: string): any { const id: string = _extractId(valueString); return this._optionMap.has(id) ? this._optionMap.get(id) : valueString; } } /** * @description * Marks `<option>` as dynamic, so Angular can be notified when options change. * * @see {@link SelectControlValueAccessor} * * @ngModule ReactiveFormsModule * @ngModule FormsModule * @publicApi */ @Directive({ selector: 'option', standalone: false, }) export class NgSelectOption implements OnDestroy { /** * @description * ID of the option element */ // TODO(issue/24571): remove '!'. id!: string; constructor( private _element: ElementRef, private _renderer: Renderer2, @Optional() @Host() private _select: SelectControlValueAccessor, ) { if (this._select) this.id = this._select._registerOption(); } /** * @description * Tracks the value bound to the option element. Unlike the value binding, * ngValue supports binding to objects. */ @Input('ngValue') set ngValue(value: any) { if (this._select == null) return; this._select._optionMap.set(this.id, value); this._setElementValue(_buildValueString(this.id, value)); this._select.writeValue(this._select.value); } /** * @description * Tracks simple string values bound to the option element. * For objects, use the `ngValue` input binding. */ @Input('value') set value(value: any) { this._setElementValue(value); if (this._select) this._select.writeValue(this._select.value); } /** @internal */ _setElementValue(value: string): void { this._renderer.setProperty(this._element.nativeElement, 'value', value); } /** @nodoc */ ngOnDestroy(): void { if (this._select) { this._select._optionMap.delete(this.id); this._select.writeValue(this._select.value); } } }
009693
/** * @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 formControlNameExample = ` <div [formGroup]="myGroup"> <input formControlName="firstName"> </div> In your class: this.myGroup = new FormGroup({ firstName: new FormControl() });`; export const formGroupNameExample = ` <div [formGroup]="myGroup"> <div formGroupName="person"> <input formControlName="firstName"> </div> </div> In your class: this.myGroup = new FormGroup({ person: new FormGroup({ firstName: new FormControl() }) });`; export const formArrayNameExample = ` <div [formGroup]="myGroup"> <div formArrayName="cities"> <div *ngFor="let city of cityArray.controls; index as i"> <input [formControlName]="i"> </div> </div> </div> In your class: this.cityArray = new FormArray([new FormControl('SF')]); this.myGroup = new FormGroup({ cities: this.cityArray });`; export const ngModelGroupExample = ` <form> <div ngModelGroup="person"> <input [(ngModel)]="person.name" name="firstName"> </div> </form>`; export const ngModelWithFormGroupExample = ` <div [formGroup]="myGroup"> <input formControlName="firstName"> <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}"> </div> `;
009694
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Directive, forwardRef, Host, Inject, Input, OnDestroy, OnInit, Optional, Provider, Self, SkipSelf, } from '@angular/core'; import {FormArray} from '../../model/form_array'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators'; import {AbstractFormGroupDirective} from '../abstract_form_group_directive'; import {ControlContainer} from '../control_container'; import {arrayParentException, groupParentException} from '../reactive_errors'; import {controlPath} from '../shared'; import {AsyncValidator, AsyncValidatorFn, Validator, ValidatorFn} from '../validators'; import {FormGroupDirective} from './form_group_directive'; const formGroupNameProvider: Provider = { provide: ControlContainer, useExisting: forwardRef(() => FormGroupName), }; /** * @description * * Syncs a nested `FormGroup` or `FormRecord` to a DOM element. * * This directive can only be used with a parent `FormGroupDirective`. * * It accepts the string name of the nested `FormGroup` or `FormRecord` to link, and * looks for a `FormGroup` or `FormRecord` registered with that name in the parent * `FormGroup` instance you passed into `FormGroupDirective`. * * Use nested form groups to validate a sub-group of a * form separately from the rest or to group the values of certain * controls into their own nested object. * * @see [Reactive Forms Guide](guide/forms/reactive-forms) * * @usageNotes * * ### Access the group by name * * The following example uses the `AbstractControl.get` method to access the * associated `FormGroup` * * ```ts * this.form.get('name'); * ``` * * ### Access individual controls in the group * * The following example uses the `AbstractControl.get` method to access * individual controls within the group using dot syntax. * * ```ts * this.form.get('name.first'); * ``` * * ### Register a nested `FormGroup`. * * The following example registers a nested *name* `FormGroup` within an existing `FormGroup`, * and provides methods to retrieve the nested `FormGroup` and individual controls. * * {@example forms/ts/nestedFormGroup/nested_form_group_example.ts region='Component'} * * @ngModule ReactiveFormsModule * @publicApi */ @Directive({ selector: '[formGroupName]', providers: [formGroupNameProvider], standalone: false, }) export class FormGroupName extends AbstractFormGroupDirective implements OnInit, OnDestroy { /** * @description * Tracks the name of the `FormGroup` bound to the directive. The name corresponds * to a key in the parent `FormGroup` or `FormArray`. * Accepts a name as a string or a number. * The name in the form of a string is useful for individual forms, * while the numerical form allows for form groups to be bound * to indices when iterating over groups in a `FormArray`. */ @Input('formGroupName') override name: string | number | null = null; constructor( @Optional() @Host() @SkipSelf() parent: ControlContainer, @Optional() @Self() @Inject(NG_VALIDATORS) validators: (Validator | ValidatorFn)[], @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: (AsyncValidator | AsyncValidatorFn)[], ) { super(); this._parent = parent; this._setValidators(validators); this._setAsyncValidators(asyncValidators); } /** @internal */ override _checkParentType(): void { if (_hasInvalidParent(this._parent) && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw groupParentException(); } } } export const formArrayNameProvider: any = { provide: ControlContainer, useExisting: forwardRef(() => FormArrayName), }; /** * @description * * Syncs a nested `FormArray` to a DOM element. * * This directive is designed to be used with a parent `FormGroupDirective` (selector: * `[formGroup]`). * * It accepts the string name of the nested `FormArray` you want to link, and * will look for a `FormArray` registered with that name in the parent * `FormGroup` instance you passed into `FormGroupDirective`. * * @see [Reactive Forms Guide](guide/forms/reactive-forms) * @see {@link AbstractControl} * * @usageNotes * * ### Example * * {@example forms/ts/nestedFormArray/nested_form_array_example.ts region='Component'} * * @ngModule ReactiveFormsModule * @publicApi */ @Directive({ selector: '[formArrayName]', providers: [formArrayNameProvider], standalone: false, }) export class FormArrayName extends ControlContainer implements OnInit, OnDestroy { /** @internal */ _parent: ControlContainer; /** * @description * Tracks the name of the `FormArray` bound to the directive. The name corresponds * to a key in the parent `FormGroup` or `FormArray`. * Accepts a name as a string or a number. * The name in the form of a string is useful for individual forms, * while the numerical form allows for form arrays to be bound * to indices when iterating over arrays in a `FormArray`. */ @Input('formArrayName') override name: string | number | null = null; constructor( @Optional() @Host() @SkipSelf() parent: ControlContainer, @Optional() @Self() @Inject(NG_VALIDATORS) validators: (Validator | ValidatorFn)[], @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: (AsyncValidator | AsyncValidatorFn)[], ) { super(); this._parent = parent; this._setValidators(validators); this._setAsyncValidators(asyncValidators); } /** * A lifecycle method called when the directive's inputs are initialized. For internal use only. * @throws If the directive does not have a valid parent. * @nodoc */ ngOnInit(): void { this._checkParentType(); this.formDirective!.addFormArray(this); } /** * A lifecycle method called before the directive's instance is destroyed. For internal use only. * @nodoc */ ngOnDestroy(): void { if (this.formDirective) { this.formDirective.removeFormArray(this); } } /** * @description * The `FormArray` bound to this directive. */ override get control(): FormArray { return this.formDirective!.getFormArray(this); } /** * @description * The top-level directive for this group if present, otherwise null. */ override get formDirective(): FormGroupDirective | null { return this._parent ? <FormGroupDirective>this._parent.formDirective : null; } /** * @description * Returns an array that represents the path from the top-level form to this control. * Each index is the string name of the control on that level. */ override get path(): string[] { return controlPath(this.name == null ? this.name : this.name.toString(), this._parent); } private _checkParentType(): void { if (_hasInvalidParent(this._parent) && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw arrayParentException(); } } } function _hasInvalidParent(parent: ControlContainer): boolean { return ( !(parent instanceof FormGroupName) && !(parent instanceof FormGroupDirective) && !(parent instanceof FormArrayName) ); }
009703
/** * @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 {ɵWritable as Writable} from '@angular/core'; import {AsyncValidatorFn, ValidatorFn} from '../directives/validators'; import { AbstractControl, AbstractControlOptions, assertAllValuesPresent, assertControlPresent, pickAsyncValidators, pickValidators, ɵRawValue, ɵTypedOrUntyped, ɵValue, } from './abstract_model'; /** * FormGroupValue extracts the type of `.value` from a FormGroup's inner object type. The untyped * case falls back to {[key: string]: any}. * * Angular uses this type internally to support Typed Forms; do not use it directly. * * For internal use only. */ export type ɵFormGroupValue<T extends {[K in keyof T]?: AbstractControl<any>}> = ɵTypedOrUntyped< T, Partial<{[K in keyof T]: ɵValue<T[K]>}>, {[key: string]: any} >; /** * FormGroupRawValue extracts the type of `.getRawValue()` from a FormGroup's inner object type. The * untyped case falls back to {[key: string]: any}. * * Angular uses this type internally to support Typed Forms; do not use it directly. * * For internal use only. */ export type ɵFormGroupRawValue<T extends {[K in keyof T]?: AbstractControl<any>}> = ɵTypedOrUntyped< T, {[K in keyof T]: ɵRawValue<T[K]>}, {[key: string]: any} >; /** * OptionalKeys returns the union of all optional keys in the object. * * Angular uses this type internally to support Typed Forms; do not use it directly. */ export type ɵOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? K : never; }[keyof T]; /** * Tracks the value and validity state of a group of `FormControl` instances. * * A `FormGroup` aggregates the values of each child `FormControl` into one object, * with each control name as the key. It calculates its status by reducing the status values * of its children. For example, if one of the controls in a group is invalid, the entire * group becomes invalid. * * `FormGroup` is one of the four fundamental building blocks used to define forms in Angular, * along with `FormControl`, `FormArray`, and `FormRecord`. * * When instantiating a `FormGroup`, pass in a collection of child controls as the first * argument. The key for each child registers the name for the control. * * `FormGroup` is intended for use cases where the keys are known ahead of time. * If you need to dynamically add and remove controls, use {@link FormRecord} instead. * * `FormGroup` accepts an optional type parameter `TControl`, which is an object type with inner * control types as values. * * @usageNotes * * ### Create a form group with 2 controls * * ``` * const form = new FormGroup({ * first: new FormControl('Nancy', Validators.minLength(2)), * last: new FormControl('Drew'), * }); * * console.log(form.value); // {first: 'Nancy', last; 'Drew'} * console.log(form.status); // 'VALID' * ``` * * ### The type argument, and optional controls * * `FormGroup` accepts one generic argument, which is an object containing its inner controls. * This type will usually be inferred automatically, but you can always specify it explicitly if you * wish. * * If you have controls that are optional (i.e. they can be removed, you can use the `?` in the * type): * * ``` * const form = new FormGroup<{ * first: FormControl<string|null>, * middle?: FormControl<string|null>, // Middle name is optional. * last: FormControl<string|null>, * }>({ * first: new FormControl('Nancy'), * last: new FormControl('Drew'), * }); * ``` * * ### Create a form group with a group-level validator * * You include group-level validators as the second arg, or group-level async * validators as the third arg. These come in handy when you want to perform validation * that considers the value of more than one child control. * * ``` * const form = new FormGroup({ * password: new FormControl('', Validators.minLength(2)), * passwordConfirm: new FormControl('', Validators.minLength(2)), * }, passwordMatchValidator); * * * function passwordMatchValidator(g: FormGroup) { * return g.get('password').value === g.get('passwordConfirm').value * ? null : {'mismatch': true}; * } * ``` * * Like `FormControl` instances, you choose to pass in * validators and async validators as part of an options object. * * ``` * const form = new FormGroup({ * password: new FormControl('') * passwordConfirm: new FormControl('') * }, { validators: passwordMatchValidator, asyncValidators: otherValidator }); * ``` * * ### Set the updateOn property for all controls in a form group * * The options object is used to set a default value for each child * control's `updateOn` property. If you set `updateOn` to `'blur'` at the * group level, all child controls default to 'blur', unless the child * has explicitly specified a different `updateOn` value. * * ```ts * const c = new FormGroup({ * one: new FormControl() * }, { updateOn: 'blur' }); * ``` * * ### Using a FormGroup with optional controls * * It is possible to have optional controls in a FormGroup. An optional control can be removed later * using `removeControl`, and can be omitted when calling `reset`. Optional controls must be * declared optional in the group's type. * * ```ts * const c = new FormGroup<{one?: FormControl<string>}>({ * one: new FormControl('') * }); * ``` * * Notice that `c.value.one` has type `string|null|undefined`. This is because calling `c.reset({})` * without providing the optional key `one` will cause it to become `null`. * * @publicApi */ export cla
009704
s FormGroup< TControl extends {[K in keyof TControl]: AbstractControl<any>} = any, > extends AbstractControl< ɵTypedOrUntyped<TControl, ɵFormGroupValue<TControl>, any>, ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any> > { /** * Creates a new `FormGroup` instance. * * @param controls A collection of child controls. The key for each child is the name * under which it is registered. * * @param validatorOrOpts A synchronous validator function, or an array of * such functions, or an `AbstractControlOptions` object that contains validation functions * and a validation trigger. * * @param asyncValidator A single async validator or array of async validator functions * */ constructor( controls: TControl, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null, ) { super(pickValidators(validatorOrOpts), pickAsyncValidators(asyncValidator, validatorOrOpts)); (typeof ngDevMode === 'undefined' || ngDevMode) && validateFormGroupControls(controls); this.controls = controls; this._initObservables(); this._setUpdateStrategy(validatorOrOpts); this._setUpControls(); this.updateValueAndValidity({ onlySelf: true, // If `asyncValidator` is present, it will trigger control status change from `PENDING` to // `VALID` or `INVALID`. The status should be broadcasted via the `statusChanges` observable, // so we set `emitEvent` to `true` to allow that during the control creation process. emitEvent: !!this.asyncValidator, }); } public controls: ɵTypedOrUntyped<TControl, TControl, {[key: string]: AbstractControl<any>}>; /** * Registers a control with the group's list of controls. In a strongly-typed group, the control * must be in the group's type (possibly as an optional key). * * This method does not update the value or validity of the control. * Use {@link FormGroup#addControl addControl} instead. * * @param name The control name to register in the collection * @param control Provides the control for the given name */ registerControl<K extends string & keyof TControl>(name: K, control: TControl[K]): TControl[K]; registerControl( this: FormGroup<{[key: string]: AbstractControl<any>}>, name: string, control: AbstractControl<any>, ): AbstractControl<any>; registerControl<K extends string & keyof TControl>(name: K, control: TControl[K]): TControl[K] { if (this.controls[name]) return (this.controls as any)[name]; this.controls[name] = control; control.setParent(this as FormGroup); control._registerOnCollectionChange(this._onCollectionChange); return control; } /** * Add a control to this group. In a strongly-typed group, the control must be in the group's type * (possibly as an optional key). * * If a control with a given name already exists, it would *not* be replaced with a new one. * If you want to replace an existing control, use the {@link FormGroup#setControl setControl} * method instead. This method also updates the value and validity of the control. * * @param name The control name to add to the collection * @param control Provides the control for the given name * @param options Specifies whether this FormGroup instance should emit events after a new * control is added. * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` observables emit events with the latest status and value when the control is * added. When false, no events are emitted. */ addControl( this: FormGroup<{[key: string]: AbstractControl<any>}>, name: string, control: AbstractControl, options?: {emitEvent?: boolean}, ): void; addControl<K extends string & keyof TControl>( name: K, control: Required<TControl>[K], options?: { emitEvent?: boolean; }, ): void; addControl<K extends string & keyof TControl>( name: K, control: Required<TControl>[K], options: { emitEvent?: boolean; } = {}, ): void { this.registerControl(name, control); this.updateValueAndValidity({emitEvent: options.emitEvent}); this._onCollectionChange(); } removeControl( this: FormGroup<{[key: string]: AbstractControl<any>}>, name: string, options?: { emitEvent?: boolean; }, ): void; removeControl<S extends string>( name: ɵOptionalKeys<TControl> & S, options?: { emitEvent?: boolean; }, ): void; /** * Remove a control from this group. In a strongly-typed group, required controls cannot be * removed. * * This method also updates the value and validity of the control. * * @param name The control name to remove from the collection * @param options Specifies whether this FormGroup instance should emit events after a * control is removed. * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` observables emit events with the latest status and value when the control is * removed. When false, no events are emitted. */ removeControl(name: string, options: {emitEvent?: boolean} = {}): void { if ((this.controls as any)[name]) (this.controls as any)[name]._registerOnCollectionChange(() => {}); delete (this.controls as any)[name]; this.updateValueAndValidity({emitEvent: options.emitEvent}); this._onCollectionChange(); } /** * Replace an existing control. In a strongly-typed group, the control must be in the group's type * (possibly as an optional key). * * If a control with a given name does not exist in this `FormGroup`, it will be added. * * @param name The control name to replace in the collection * @param control Provides the control for the given name * @param options Specifies whether this FormGroup instance should emit events after an * existing control is replaced. * * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and * `valueChanges` observables emit events with the latest status and value when the control is * replaced with a new one. When false, no events are emitted. */ setControl<K extends string & keyof TControl>( name: K, control: TControl[K], options?: { emitEvent?: boolean; }, ): void; setControl( this: FormGroup<{[key: string]: AbstractControl<any>}>, name: string, control: AbstractControl, options?: {emitEvent?: boolean}, ): void; setControl<K extends string & keyof TControl>( name: K, control: TControl[K], options: { emitEvent?: boolean; } = {}, ): void { if (this.controls[name]) this.controls[name]._registerOnCollectionChange(() => {}); delete this.controls[name]; if (control) this.registerControl(name, control); this.updateValueAndValidity({emitEvent: options.emitEvent}); this._onCollectionChange(); } /** * Check whether there is an enabled control with the given name in the group. * * Reports false for disabled controls. If you'd like to check for existence in the group * only, use {@link AbstractControl#get get} instead. * * @param controlName The control name to check for existence in the collection * * @returns false for disabled controls, true otherwise. */ contains<K extends string>(controlName: K): boolean; contains(this: FormGroup<{[key: string]: AbstractControl<any>}>, controlName: string): boolean; contains<K extends string & keyof TControl>(controlName: K): boolean { return this.controls.hasOwnProperty(controlName) && this.controls[controlName].enabled; } /** * Sets
009710
observable that emits an event every time the state of the control changes. * It emits for value, status, pristine or touched changes. * * **Note**: On value change, the emit happens right after a value of this control is updated. The * value of a parent control (for example if this FormControl is a part of a FormGroup) is updated * later, so accessing a value of a parent control (using the `value` property) from the callback * of this event might result in getting a value that has not been updated yet. Subscribe to the * `events` of the parent control instead. * For other event types, the events are emitted after the parent control has been updated. * */ public readonly events = this._events.asObservable(); /** * A multicasting observable that emits an event every time the value of the control changes, in * the UI or programmatically. It also emits an event each time you call enable() or disable() * without passing along {emitEvent: false} as a function argument. * * **Note**: the emit happens right after a value of this control is updated. The value of a * parent control (for example if this FormControl is a part of a FormGroup) is updated later, so * accessing a value of a parent control (using the `value` property) from the callback of this * event might result in getting a value that has not been updated yet. Subscribe to the * `valueChanges` event of the parent control instead. * * TODO: this should be piped from events() but is breaking in G3 */ public readonly valueChanges!: Observable<TValue>; /** * A multicasting observable that emits an event every time the validation `status` of the control * recalculates. * * @see {@link FormControlStatus} * @see {@link AbstractControl.status} * * TODO: this should be piped from events() but is breaking in G3 */ public readonly statusChanges!: Observable<FormControlStatus>; /** * Reports the update strategy of the `AbstractControl` (meaning * the event on which the control updates itself). * Possible values: `'change'` | `'blur'` | `'submit'` * Default value: `'change'` */ get updateOn(): FormHooks { return this._updateOn ? this._updateOn : this.parent ? this.parent.updateOn : 'change'; } /** * Sets the synchronous validators that are active on this control. Calling * this overwrites any existing synchronous validators. * * When you add or remove a validator at run time, you must call * `updateValueAndValidity()` for the new validation to take effect. * * If you want to add a new validator without affecting existing ones, consider * using `addValidators()` method instead. */ setValidators(validators: ValidatorFn | ValidatorFn[] | null): void { this._assignValidators(validators); } /** * Sets the asynchronous validators that are active on this control. Calling this * overwrites any existing asynchronous validators. * * When you add or remove a validator at run time, you must call * `updateValueAndValidity()` for the new validation to take effect. * * If you want to add a new validator without affecting existing ones, consider * using `addAsyncValidators()` method instead. */ setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[] | null): void { this._assignAsyncValidators(validators); } /** * Add a synchronous validator or validators to this control, without affecting other validators. * * When you add or remove a validator at run time, you must call * `updateValueAndValidity()` for the new validation to take effect. * * Adding a validator that already exists will have no effect. If duplicate validator functions * are present in the `validators` array, only the first instance would be added to a form * control. * * @param validators The new validator function or functions to add to this control. */ addValidators(validators: ValidatorFn | ValidatorFn[]): void { this.setValidators(addValidators(validators, this._rawValidators)); } /** * Add an asynchronous validator or validators to this control, without affecting other * validators. * * When you add or remove a validator at run time, you must call * `updateValueAndValidity()` for the new validation to take effect. * * Adding a validator that already exists will have no effect. * * @param validators The new asynchronous validator function or functions to add to this control. */ addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void { this.setAsyncValidators(addValidators(validators, this._rawAsyncValidators)); } /** * Remove a synchronous validator from this control, without affecting other validators. * Validators are compared by function reference; you must pass a reference to the exact same * validator function as the one that was originally set. If a provided validator is not found, * it is ignored. * * @usageNotes * * ### Reference to a ValidatorFn * * ``` * // Reference to the RequiredValidator * const ctrl = new FormControl<string | null>('', Validators.required); * ctrl.removeValidators(Validators.required); * * // Reference to anonymous function inside MinValidator * const minValidator = Validators.min(3); * const ctrl = new FormControl<string | null>('', minValidator); * expect(ctrl.hasValidator(minValidator)).toEqual(true) * expect(ctrl.hasValidator(Validators.min(3))).toEqual(false) * * ctrl.removeValidators(minValidator); * ``` * * When you add or remove a validator at run time, you must call * `updateValueAndValidity()` for the new validation to take effect. * * @param validators The validator or validators to remove. */ removeValidators(validators: ValidatorFn | ValidatorFn[]): void { this.setValidators(removeValidators(validators, this._rawValidators)); } /** * Remove an asynchronous validator from this control, without affecting other validators. * Validators are compared by function reference; you must pass a reference to the exact same * validator function as the one that was originally set. If a provided validator is not found, it * is ignored. * * When you add or remove a validator at run time, you must call * `updateValueAndValidity()` for the new validation to take effect. * * @param validators The asynchronous validator or validators to remove. */ removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void { this.setAsyncValidators(removeValidators(validators, this._rawAsyncValidators)); } /** * Check whether a synchronous validator function is present on this control. The provided * validator must be a reference to the exact same function that was provided. * * @usageNotes * * ### Reference to a ValidatorFn * * ``` * // Reference to the RequiredValidator * const ctrl = new FormControl<number | null>(0, Validators.required); * expect(ctrl.hasValidator(Validators.required)).toEqual(true) * * // Reference to anonymous function inside MinValidator * const minValidator = Validators.min(3); * const ctrl = new FormControl<number | null>(0, minValidator); * expect(ctrl.hasValidator(minValidator)).toEqual(true) * expect(ctrl.hasValidator(Validators.min(3))).toEqual(false) * ``` * * @param validator The validator to check for presence. Compared by function reference. * @returns Whether the provided validator was found on this control. */ hasValidator(validator: ValidatorFn): boolean { return hasValidator(this._rawValidators, validator); } /** * Check whether an asynchronous validator function is present on this control. The provided * validator must be a reference to the exact same function that was provided. * * @param validator The asynchronous validator to check for presence. Compared by function * reference. * @returns Whether the provided asynchronous validator was found on this control. */ hasAsyncValidator(validator: AsyncValidatorFn): boolean { return hasValidator(this._rawAsyncValidators, validator); } /** * Empties out the synchronous validator list. * * When you add or remove a validator at run time, you must call * `updateValueAndValidity()` for the new validation to take effect. * */ clearValidators(): void { this.validator = null; } /** * Empties out the async validator list. * * When you add or remove a validator at run time, you must call * `updateValueAndValidity()` for the new validation to take effect. * */ clearAsyncValidators(): void { this.asyncValidator = null; } /** * Marks the c
009713
or(shouldHaveEmitted: boolean, emitEvent?: boolean): void { if (this.asyncValidator) { this.status = PENDING; this._hasOwnPendingAsyncValidator = {emitEvent: emitEvent !== false}; const obs = toObservable(this.asyncValidator(this)); this._asyncValidationSubscription = obs.subscribe((errors: ValidationErrors | null) => { this._hasOwnPendingAsyncValidator = null; // This will trigger the recalculation of the validation status, which depends on // the state of the asynchronous validation (whether it is in progress or not). So, it is // necessary that we have updated the `_hasOwnPendingAsyncValidator` boolean flag first. this.setErrors(errors, {emitEvent, shouldHaveEmitted}); }); } } private _cancelExistingSubscription(): boolean { if (this._asyncValidationSubscription) { this._asyncValidationSubscription.unsubscribe(); // we're cancelling the validator subscribtion, we keep if it should have emitted // because we want to emit eventually if it was required at least once. const shouldHaveEmitted = this._hasOwnPendingAsyncValidator?.emitEvent ?? false; this._hasOwnPendingAsyncValidator = null; return shouldHaveEmitted; } return false; } /** * Sets errors on a form control when running validations manually, rather than automatically. * * Calling `setErrors` also updates the validity of the parent control. * * @param opts Configuration options that determine how the control propagates * changes and emits events after the control errors are set. * * `emitEvent`: When true or not supplied (the default), the `statusChanges` * observable emits an event after the errors are set. * * @usageNotes * * ### Manually set the errors for a control * * ``` * const login = new FormControl('someLogin'); * login.setErrors({ * notUnique: true * }); * * expect(login.valid).toEqual(false); * expect(login.errors).toEqual({ notUnique: true }); * * login.setValue('someOtherLogin'); * * expect(login.valid).toEqual(true); * ``` */ setErrors(errors: ValidationErrors | null, opts?: {emitEvent?: boolean}): void; /** @internal */ setErrors( errors: ValidationErrors | null, opts?: {emitEvent?: boolean; shouldHaveEmitted?: boolean}, ): void; setErrors( errors: ValidationErrors | null, opts: {emitEvent?: boolean; shouldHaveEmitted?: boolean} = {}, ): void { (this as Writable<this>).errors = errors; this._updateControlsErrors(opts.emitEvent !== false, this, opts.shouldHaveEmitted); } /** * Retrieves a child control given the control's name or path. * * This signature for get supports strings and `const` arrays (`.get(['foo', 'bar'] as const)`). */ get<P extends string | readonly (string | number)[]>( path: P, ): AbstractControl<ɵGetProperty<TRawValue, P>> | null; /** * Retrieves a child control given the control's name or path. * * This signature for `get` supports non-const (mutable) arrays. Inferred type * information will not be as robust, so prefer to pass a `readonly` array if possible. */ get<P extends string | Array<string | number>>( path: P, ): AbstractControl<ɵGetProperty<TRawValue, P>> | null; /** * Retrieves a child control given the control's name or path. * * @param path A dot-delimited string or array of string/number values that define the path to the * control. If a string is provided, passing it as a string literal will result in improved type * information. Likewise, if an array is provided, passing it `as const` will cause improved type * information to be available. * * @usageNotes * ### Retrieve a nested control * * For example, to get a `name` control nested within a `person` sub-group: * * * `this.form.get('person.name');` * * -OR- * * * `this.form.get(['person', 'name'] as const);` // `as const` gives improved typings * * ### Retrieve a control in a FormArray * * When accessing an element inside a FormArray, you can use an element index. * For example, to get a `price` control from the first element in an `items` array you can use: * * * `this.form.get('items.0.price');` * * -OR- * * * `this.form.get(['items', 0, 'price']);` */ get<P extends string | (string | number)[]>( path: P, ): AbstractControl<ɵGetProperty<TRawValue, P>> | null { let currPath: Array<string | number> | string = path; if (currPath == null) return null; if (!Array.isArray(currPath)) currPath = currPath.split('.'); if (currPath.length === 0) return null; return currPath.reduce( (control: AbstractControl | null, name) => control && control._find(name), this, ); } /** * @description * Reports error data for the control with the given path. * * @param errorCode The code of the error to check * @param path A list of control names that designates how to move from the current control * to the control that should be queried for errors. * * @usageNotes * For example, for the following `FormGroup`: * * ``` * form = new FormGroup({ * address: new FormGroup({ street: new FormControl() }) * }); * ``` * * The path to the 'street' control from the root form would be 'address' -> 'street'. * * It can be provided to this method in one of two formats: * * 1. An array of string control names, e.g. `['address', 'street']` * 1. A period-delimited list of control names in one string, e.g. `'address.street'` * * @returns error data for that particular error. If the control or error is not present, * null is returned. */ getError(errorCode: string, path?: Array<string | number> | string): any { const control = path ? this.get(path) : this; return control && control.errors ? control.errors[errorCode] : null; } /** * @description * Reports whether the control with the given path has the error specified. * * @param errorCode The code of the error to check * @param path A list of control names that designates how to move from the current control * to the control that should be queried for errors. * * @usageNotes * For example, for the following `FormGroup`: * * ``` * form = new FormGroup({ * address: new FormGroup({ street: new FormControl() }) * }); * ``` * * The path to the 'street' control from the root form would be 'address' -> 'street'. * * It can be provided to this method in one of two formats: * * 1. An array of string control names, e.g. `['address', 'street']` * 1. A period-delimited list of control names in one string, e.g. `'address.street'` * * If no path is given, this method checks for the error on the current control. * * @returns whether the given error is present in the control at the given path. * * If the control is not present, false is returned. */ hasError(errorCode: string, path?: Array<string | number> | string): boolean { return !!this.getError(errorCode, path); } /** * Retrieves the top-level ancestor of this control. */ get root(): AbstractControl { let x: AbstractControl = this; while (x._parent) { x = x._parent; } return x; } /** @internal */ _updateControlsErrors(
009726
describe('Angular with zoneless enabled', () => { async function createFixture<T>(type: Type<T>): Promise<ComponentFixture<T>> { const fixture = TestBed.createComponent(type); await fixture.whenStable(); return fixture; } beforeEach(() => { TestBed.configureTestingModule({ providers: [ provideZonelessChangeDetection(), {provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}, ], }); }); describe('notifies scheduler', () => { it('contributes to application stableness', async () => { const val = signal('initial'); @Component({template: '{{val()}}', standalone: true}) class TestComponent { val = val; } const fixture = await createFixture(TestComponent); // Cause another pending CD immediately after render and verify app has not stabilized await fixture.whenStable().then(() => { val.set('new'); }); expect(fixture.isStable()).toBeFalse(); await fixture.whenStable(); expect(fixture.isStable()).toBeTrue(); }); it('when signal updates', async () => { const val = signal('initial'); @Component({template: '{{val()}}', standalone: true}) class TestComponent { val = val; } const fixture = await createFixture(TestComponent); expect(fixture.nativeElement.innerText).toEqual('initial'); val.set('new'); expect(fixture.isStable()).toBeFalse(); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual('new'); }); it('when using markForCheck()', async () => { @Component({template: '{{val}}', standalone: true}) class TestComponent { cdr = inject(ChangeDetectorRef); val = 'initial'; setVal(val: string) { this.val = val; this.cdr.markForCheck(); } } const fixture = await createFixture(TestComponent); expect(fixture.nativeElement.innerText).toEqual('initial'); fixture.componentInstance.setVal('new'); expect(fixture.isStable()).toBe(false); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual('new'); }); it('on input binding', async () => { @Component({template: '{{val}}', standalone: true}) class TestComponent { @Input() val = 'initial'; } const fixture = await createFixture(TestComponent); expect(fixture.nativeElement.innerText).toEqual('initial'); fixture.componentRef.setInput('val', 'new'); expect(fixture.isStable()).toBe(false); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual('new'); }); it('on event listener bound in template', async () => { @Component({template: '<div (click)="updateVal()">{{val}}</div>', standalone: true}) class TestComponent { val = 'initial'; updateVal() { this.val = 'new'; } } const fixture = await createFixture(TestComponent); expect(fixture.nativeElement.innerText).toEqual('initial'); fixture.debugElement .query((p) => p.nativeElement.tagName === 'DIV') .triggerEventHandler('click'); expect(fixture.isStable()).toBe(false); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual('new'); }); it('on event listener bound in host', async () => { @Component({host: {'(click)': 'updateVal()'}, template: '{{val}}', standalone: true}) class TestComponent { val = 'initial'; updateVal() { this.val = 'new'; } } const fixture = await createFixture(TestComponent); expect(fixture.nativeElement.innerText).toEqual('initial'); fixture.debugElement.triggerEventHandler('click'); expect(fixture.isStable()).toBe(false); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual('new'); }); it('with async pipe', async () => { @Component({template: '{{val | async}}', standalone: true, imports: [AsyncPipe]}) class TestComponent { val = new BehaviorSubject('initial'); } const fixture = await createFixture(TestComponent); expect(fixture.nativeElement.innerText).toEqual('initial'); fixture.componentInstance.val.next('new'); expect(fixture.isStable()).toBe(false); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual('new'); }); it('when creating a view', async () => { @Component({ template: '<ng-template #ref>{{"binding"}}</ng-template>', standalone: true, }) class TestComponent { @ViewChild(TemplateRef) template!: TemplateRef<unknown>; @ViewChild('ref', {read: ViewContainerRef}) viewContainer!: ViewContainerRef; createView(): any { this.viewContainer.createEmbeddedView(this.template); } } const fixture = await createFixture(TestComponent); fixture.componentInstance.createView(); expect(fixture.isStable()).toBe(false); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual('binding'); }); it('when inserting a view', async () => { @Component({ template: '{{"binding"}}', standalone: true, }) class DynamicCmp { elementRef = inject(ElementRef); } @Component({ template: '<ng-template #ref></ng-template>', standalone: true, }) class TestComponent { @ViewChild('ref', {read: ViewContainerRef}) viewContainer!: ViewContainerRef; } const fixture = await createFixture(TestComponent); const otherComponent = createComponent(DynamicCmp, { environmentInjector: TestBed.inject(EnvironmentInjector), }); fixture.componentInstance.viewContainer.insert(otherComponent.hostView); expect(fixture.isStable()).toBe(false); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual('binding'); }); it('when destroying a view (with animations)', async () => { @Component({ template: '{{"binding"}}', standalone: true, }) class DynamicCmp { elementRef = inject(ElementRef); } @Component({ template: '<ng-template #ref></ng-template>', standalone: true, }) class TestComponent { @ViewChild('ref', {read: ViewContainerRef}) viewContainer!: ViewContainerRef; } const fixture = await createFixture(TestComponent); const component = createComponent(DynamicCmp, { environmentInjector: TestBed.inject(EnvironmentInjector), }); fixture.componentInstance.viewContainer.insert(component.hostView); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual('binding'); fixture.componentInstance.viewContainer.remove(); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual(''); const component2 = createComponent(DynamicCmp, { environmentInjector: TestBed.inject(EnvironmentInjector), }); fixture.componentInstance.viewContainer.insert(component2.hostView); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual('binding'); component2.destroy(); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toEqual(''); }); function whenStable(): Promise<void> { return TestBed.inject(ApplicationRef).whenStable(); } it( 'when destroying a view (*no* animations)', withBody('<app></app>', async () => { destroyPlatform(); let doCheckCount = 0; let renderHookCalls = 0; @Component({ template: '{{"binding"}}', standalone: true, }) class DynamicCmp { elementRef = inject(ElementRef); } @Component({ selector: 'app', template: '<ng-template #ref></ng-template>', standalone: true, }) class App { @ViewChild('ref', {read: ViewContainerRef}) viewContainer!: ViewContainerRef; unused = afterRender(() => { renderHookCalls++; }); ngDoCheck() { doCheckCount++; } } const applicationRef = await bootstrapApplication(App, { providers: [ provideZonelessChangeDetection(), {provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}, ], }); const appViewRef = (applicationRef as any)._views[0] as {context: App; rootNodes: any[]}; await applicationRef.whenStable(); const component2 = createComponent(DynamicCmp, { environmentInjector: applicationRef.injector, }); appViewRef.context.viewContainer.insert(component2.hostView); expect(isStable(applicationRef.injector)).toBe(false); await applicationRef.whenStable(); component2.destroy(); // destroying the view synchronously removes element from DOM when not using animations expect(appViewRef.rootNodes[0].innerText).toEqual(''); // Destroying the view notifies scheduler because render hooks need to run expect(isStable(applicationRef.injector)).toBe(false); let checkCountBeforeStable = doCheckCount; let renderCountBeforeStable = renderHookCalls; await applicationRef.whenStable(); // The view should not have refreshed expect(doCheckCount).toEqual(checkCountBeforeStable); // but render hooks should have run expect(renderHookCalls).toEqual(renderCountBeforeStable + 1); destroyPlatform(); }), );
009729
describe('Angular with scheduler and ZoneJS', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ {provide: ComponentFixtureAutoDetect, useValue: true}, {provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}, ], }); }); it('requires updates inside Angular zone when using ngZoneOnly', async () => { TestBed.configureTestingModule({ providers: [provideZoneChangeDetection({ignoreChangesOutsideZone: true})], }); @Component({template: '{{thing()}}', standalone: true}) class App { thing = signal('initial'); } const fixture = TestBed.createComponent(App); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toContain('initial'); TestBed.inject(NgZone).runOutsideAngular(() => { fixture.componentInstance.thing.set('new'); }); expect(fixture.isStable()).toBe(true); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toContain('initial'); }); it('will not schedule change detection if listener callback is outside the zone', async () => { let renders = 0; TestBed.runInInjectionContext(() => { afterRender(() => { renders++; }); }); @Component({selector: 'component-with-output', template: '', standalone: true}) class ComponentWithOutput { @Output() out = new EventEmitter(); } let called = false; @Component({ standalone: true, imports: [ComponentWithOutput], template: '<component-with-output (out)="onOut()" />', }) class App { onOut() { called = true; } } const fixture = TestBed.createComponent(App); await fixture.whenStable(); const outComponent = fixture.debugElement.query( (debugNode) => debugNode.providerTokens!.indexOf(ComponentWithOutput) !== -1, ).componentInstance as ComponentWithOutput; TestBed.inject(NgZone).runOutsideAngular(() => { outComponent.out.emit(); }); await fixture.whenStable(); expect(renders).toBe(1); expect(called).toBe(true); expect(renders).toBe(1); }); it('updating signal outside of zone still schedules update when in hybrid mode', async () => { @Component({template: '{{thing()}}', standalone: true}) class App { thing = signal('initial'); } const fixture = TestBed.createComponent(App); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toContain('initial'); TestBed.inject(NgZone).runOutsideAngular(() => { fixture.componentInstance.thing.set('new'); }); expect(fixture.isStable()).toBe(false); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toContain('new'); }); it('updating signal in another "Angular" zone schedules update when in hybrid mode', async () => { @Component({template: '{{thing()}}', standalone: true}) class App { thing = signal('initial'); } const fixture = TestBed.createComponent(App); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toContain('initial'); const differentAngularZone: NgZone = Zone.root.run(() => new NgZone({})); differentAngularZone.run(() => { fixture.componentInstance.thing.set('new'); }); expect(fixture.isStable()).toBe(false); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toContain('new'); }); it('updating signal in a child zone of Angular does not schedule extra CD', async () => { @Component({template: '{{thing()}}', standalone: true}) class App { thing = signal('initial'); } const fixture = TestBed.createComponent(App); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toContain('initial'); const childZone = TestBed.inject(NgZone).run(() => Zone.current.fork({name: 'child'})); childZone.run(() => { fixture.componentInstance.thing.set('new'); expect(TestBed.inject(ChangeDetectionSchedulerImpl)['cancelScheduledCallback']).toBeNull(); }); }); it('updating signal in a child Angular zone of Angular does not schedule extra CD', async () => { @Component({template: '{{thing()}}', standalone: true}) class App { thing = signal('initial'); } const fixture = TestBed.createComponent(App); await fixture.whenStable(); expect(fixture.nativeElement.innerText).toContain('initial'); const childAngularZone = TestBed.inject(NgZone).run(() => new NgZone({})); childAngularZone.run(() => { fixture.componentInstance.thing.set('new'); expect(TestBed.inject(ChangeDetectionSchedulerImpl)['cancelScheduledCallback']).toBeNull(); }); }); it('should not run change detection twice if notified during AppRef.tick', async () => { TestBed.configureTestingModule({ providers: [ provideZoneChangeDetection({ignoreChangesOutsideZone: false}), {provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}, ], }); let changeDetectionRuns = 0; TestBed.runInInjectionContext(() => { afterRender(() => { changeDetectionRuns++; }); }); @Component({template: '', standalone: true}) class MyComponent { cdr = inject(ChangeDetectorRef); ngDoCheck() { // notify scheduler every time this component is checked this.cdr.markForCheck(); } } const fixture = TestBed.createComponent(MyComponent); await fixture.whenStable(); expect(changeDetectionRuns).toEqual(1); // call tick manually TestBed.inject(ApplicationRef).tick(); await fixture.whenStable(); // ensure we only ran render hook 1 more time rather than once for tick and once for the // scheduled run expect(changeDetectionRuns).toEqual(2); }); it('does not cause double change detection with run coalescing', async () => { if (isNode) { return; } TestBed.configureTestingModule({ providers: [ provideZoneChangeDetection({runCoalescing: true, ignoreChangesOutsideZone: false}), ], }); @Component({template: '{{thing()}}', standalone: true}) class App { thing = signal('initial'); } const fixture = TestBed.createComponent(App); await fixture.whenStable(); let ticks = 0; TestBed.runInInjectionContext(() => { afterRender(() => { ticks++; }); }); fixture.componentInstance.thing.set('new'); await fixture.whenStable(); expect(ticks).toBe(1); }); it('does not cause double change detection with run coalescing when both schedulers are notified', async () => { if (isNode) { return; } TestBed.configureTestingModule({ providers: [ provideZoneChangeDetection({runCoalescing: true, ignoreChangesOutsideZone: false}), ], }); @Component({template: '{{thing()}}', standalone: true}) class App { thing = signal('initial'); } const fixture = TestBed.createComponent(App); await fixture.whenStable(); let ticks = 0; TestBed.runInInjectionContext(() => { afterRender(() => { ticks++; }); }); // notifies the zoneless scheduler fixture.componentInstance.thing.set('new'); // notifies the zone scheduler TestBed.inject(NgZone).run(() => {}); await fixture.whenStable(); expect(ticks).toBe(1); }); it('can run inside fakeAsync zone', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideZoneChangeDetection({scheduleInRootZone: false} as any)], }); let didRun = false; @Component({standalone: true, template: ''}) class App { ngDoCheck() { didRun = true; } } // create component runs inside the zone and triggers CD as a result const fixture = TestBed.createComponent(App); didRun = false; // schedules change detection fixture.debugElement.injector.get(ChangeDetectorRef).markForCheck(); expect(didRun).toBe(false); tick(); expect(didRun).toBe(true); })); });
009731
/** * @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 { ApplicationRef, ChangeDetectionStrategy, Component, effect, inject, Injector, Input, NgZone, provideZoneChangeDetection, signal, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {setUseMicrotaskEffectsByDefault} from '../src/render3/reactivity/effect'; describe('effects in TestBed', () => { let prev: boolean; beforeEach(() => { prev = setUseMicrotaskEffectsByDefault(false); }); afterEach(() => setUseMicrotaskEffectsByDefault(prev)); it('created in the constructor should run with detectChanges()', () => { const log: string[] = []; @Component({ selector: 'test-cmp', standalone: true, template: '', }) class Cmp { constructor() { log.push('Ctor'); effect(() => { log.push('Effect'); }); } ngDoCheck() { log.push('DoCheck'); } } TestBed.createComponent(Cmp).detectChanges(); expect(log).toEqual([ // The component gets constructed, which creates the effect. Since the effect is created in a // component, it doesn't get scheduled until the component is first change detected. 'Ctor', // Next, the first change detection (update pass) happens. 'DoCheck', // Then the effect runs. 'Effect', ]); }); it('created in ngOnInit should run with detectChanges()', () => { const log: string[] = []; @Component({ selector: 'test-cmp', standalone: true, template: '', }) class Cmp { private injector = inject(Injector); constructor() { log.push('Ctor'); } ngOnInit() { effect( () => { log.push('Effect'); }, {injector: this.injector}, ); } ngDoCheck() { log.push('DoCheck'); } } TestBed.createComponent(Cmp).detectChanges(); expect(log).toEqual([ // The component gets constructed. 'Ctor', // Next, the first change detection (update pass) happens, which creates the effect and // schedules it for execution. 'DoCheck', // Then the effect runs. 'Effect', ]); }); it('will flush effects automatically when using autoDetectChanges', async () => { const val = signal('initial'); let observed = ''; @Component({ selector: 'test-cmp', standalone: true, template: '', }) class Cmp { constructor() { effect(() => { observed = val(); }); } } const fixture = TestBed.createComponent(Cmp); fixture.autoDetectChanges(); expect(observed).toBe('initial'); val.set('new'); expect(observed).toBe('initial'); await fixture.whenStable(); expect(observed).toBe('new'); }); it('will run an effect with an input signal on the first CD', () => { let observed: string | null = null; @Component({ standalone: true, template: '', }) class Cmp { @Input() input!: string; constructor() { effect(() => { observed = this.input; }); } } const fix = TestBed.createComponent(Cmp); fix.componentRef.setInput('input', 'hello'); fix.detectChanges(); expect(observed as string | null).toBe('hello'); }); it('should run root effects before detectChanges() when in zone mode', async () => { TestBed.configureTestingModule({ providers: [provideZoneChangeDetection()], }); const log: string[] = []; @Component({ standalone: true, template: `{{ sentinel }}`, }) class TestCmp { get sentinel(): string { log.push('CD'); return ''; } } // Instantiate the component and CD it once. const fix = TestBed.createComponent(TestCmp); fix.detectChanges(); // Instantiate a root effect and run it once. const counter = signal(0); const appRef = TestBed.inject(ApplicationRef); effect(() => log.push(`effect: ${counter()}`), {injector: appRef.injector}); await appRef.whenStable(); log.length = 0; // Trigger the effect and call `detectChanges()` on the fixture. counter.set(1); fix.detectChanges(false); // The effect should run before the component CD. expect(log).toEqual(['effect: 1', 'CD']); }); });
009744
describe('injection flags', () => { it('should be able to optionally inject a token', () => { const TOKEN = new InjectionToken<string>('TOKEN'); expect(TestBed.inject(TOKEN, undefined, {optional: true})).toBeNull(); expect(TestBed.inject(TOKEN, undefined, InjectFlags.Optional)).toBeNull(); expect(TestBed.inject(TOKEN, undefined, {optional: true})).toBeNull(); expect(TestBed.inject(TOKEN, undefined, InjectFlags.Optional)).toBeNull(); }); it('should include `null` into the result type when the optional flag is used', () => { const TOKEN = new InjectionToken<string>('TOKEN'); const flags: InjectOptions = {optional: true}; let result = TestBed.inject(TOKEN, undefined, flags); expect(result).toBe(null); // Verify that `null` can be a valid value (from typing standpoint), // the line below would fail a type check in case the result doesn't // have `null` in the type. result = null; }); it('should be able to use skipSelf injection', () => { const TOKEN = new InjectionToken<string>('TOKEN'); TestBed.configureTestingModule({ providers: [{provide: TOKEN, useValue: 'from TestBed'}], }); expect(TestBed.inject(TOKEN)).toBe('from TestBed'); expect(TestBed.inject(TOKEN, undefined, {skipSelf: true, optional: true})).toBeNull(); expect( TestBed.inject(TOKEN, undefined, InjectFlags.SkipSelf | InjectFlags.Optional), ).toBeNull(); }); }); }); it('should be able to call Testbed.runInInjectionContext in tests', () => { const expectedValue = 'testValue'; @Injectable({providedIn: 'root'}) class SomeInjectable { readonly instanceValue = expectedValue; } function functionThatUsesInject(): string { return inject(SomeInjectable).instanceValue; } expect(TestBed.runInInjectionContext(functionThatUsesInject)).toEqual(expectedValue); }); }); describe('TestBed defer block behavior', () => { beforeEach(() => { TestBed.resetTestingModule(); }); it('should default defer block behavior to playthrough', () => { expect(TestBedImpl.INSTANCE.getDeferBlockBehavior()).toBe(DeferBlockBehavior.Playthrough); }); it('should be able to configure defer block behavior', () => { TestBed.configureTestingModule({deferBlockBehavior: DeferBlockBehavior.Manual}); expect(TestBedImpl.INSTANCE.getDeferBlockBehavior()).toBe(DeferBlockBehavior.Manual); }); it('should reset the defer block behavior back to the default when TestBed is reset', () => { TestBed.configureTestingModule({deferBlockBehavior: DeferBlockBehavior.Manual}); expect(TestBedImpl.INSTANCE.getDeferBlockBehavior()).toBe(DeferBlockBehavior.Manual); TestBed.resetTestingModule(); expect(TestBedImpl.INSTANCE.getDeferBlockBehavior()).toBe(DeferBlockBehavior.Playthrough); }); }); describe('TestBed module teardown', (
009753
describe('No NgZone', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{provide: ComponentFixtureNoNgZone, useValue: true}], }); }); it('calling autoDetectChanges raises an error', () => { const componentFixture = TestBed.createComponent(SimpleComp); expect(() => { componentFixture.autoDetectChanges(); }).toThrowError(/Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set/); }); it('should instantiate a component with valid DOM', waitForAsync(() => { const componentFixture = TestBed.createComponent(SimpleComp); expect(componentFixture.ngZone).toBeNull(); componentFixture.detectChanges(); expect(componentFixture.nativeElement).toHaveText('Original Simple'); })); it('should allow changing members of the component', waitForAsync(() => { const componentFixture = TestBed.createComponent(MyIfComp); componentFixture.detectChanges(); expect(componentFixture.nativeElement).toHaveText('MyIf()'); componentFixture.componentInstance.showMore = true; componentFixture.detectChanges(); expect(componentFixture.nativeElement).toHaveText('MyIf(More)'); })); it('throws errors that happen during detectChanges', () => { @Component({ template: '', standalone: true, }) class App { ngOnInit() { throw new Error(); } } const fixture = TestBed.createComponent(App); expect(() => fixture.detectChanges()).toThrow(); }); }); it('reports errors from autoDetect change detection to error handler', () => { let throwError = false; @Component({ template: '', standalone: false, }) class TestComponent { ngDoCheck() { if (throwError) { throw new Error(); } } } const fixture = TestBed.createComponent(TestComponent); fixture.autoDetectChanges(); const errorHandler = TestBed.inject(ErrorHandler); const spy = spyOn(errorHandler, 'handleError').and.callThrough(); throwError = true; TestBed.inject(NgZone).run(() => {}); expect(spy).toHaveBeenCalled(); }); it('reports errors from checkNoChanges in autoDetect to error handler', () => { let throwError = false; @Component({ template: '{{thing}}', standalone: false, }) class TestComponent { thing = 'initial'; ngAfterViewChecked() { if (throwError) { this.thing = 'new'; } } } const fixture = TestBed.createComponent(TestComponent); fixture.autoDetectChanges(); const errorHandler = TestBed.inject(ErrorHandler); const spy = spyOn(errorHandler, 'handleError').and.callThrough(); throwError = true; TestBed.inject(NgZone).run(() => {}); expect(spy).toHaveBeenCalled(); }); }); describe('ComponentFixture with zoneless', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ provideExperimentalZonelessChangeDetection(), {provide: ErrorHandler, useValue: {handleError: () => {}}}, ], }); }); it('will not refresh CheckAlways views when detectChanges is called if not marked dirty', () => { @Component({standalone: true, template: '{{signalThing()}}|{{regularThing}}'}) class CheckAlwaysCmp { regularThing = 'initial'; signalThing = signal('initial'); } const fixture = TestBed.createComponent(CheckAlwaysCmp); // components are created dirty fixture.detectChanges(); expect(fixture.nativeElement.innerText).toEqual('initial|initial'); fixture.componentInstance.regularThing = 'new'; // Expression changed after checked expect(() => fixture.detectChanges()).toThrow(); expect(fixture.nativeElement.innerText).toEqual('initial|initial'); fixture.componentInstance.signalThing.set('new'); fixture.detectChanges(); expect(fixture.nativeElement.innerText).toEqual('new|new'); }); it('throws errors that happen during detectChanges', () => { @Component({ template: '', standalone: true, }) class App { ngOnInit() { throw new Error(); } } const fixture = TestBed.createComponent(App); expect(() => fixture.detectChanges()).toThrow(); }); it('rejects whenStable promise when errors happen during detectChanges', async () => { @Component({ template: '', standalone: true, }) class App { ngOnInit() { throw new Error(); } } const fixture = TestBed.createComponent(App); await expectAsync(fixture.whenStable()).toBeRejected(); }); it('can disable checkNoChanges', () => { @Component({ template: '{{thing}}', standalone: true, }) class App { thing = 1; ngAfterViewChecked() { ++this.thing; } } const fixture = TestBed.createComponent(App); expect(() => fixture.detectChanges(false /*checkNoChanges*/)).not.toThrow(); // still throws if checkNoChanges is not disabled expect(() => fixture.detectChanges()).toThrowError(/ExpressionChanged/); }); it('runs change detection when autoDetect is false', () => { @Component({ template: '{{thing()}}', standalone: true, }) class App { thing = signal(1); } const fixture = TestBed.createComponent(App); fixture.autoDetectChanges(false); fixture.componentInstance.thing.set(2); fixture.detectChanges(); expect(fixture.nativeElement.innerText).toBe('2'); }); });
009817
escribe('projectable nodes', () => { @Component({ selector: 'test', template: '', standalone: false, }) class TestComponent { constructor(public vcr: ViewContainerRef) {} } @Component({ selector: 'with-content', template: '', standalone: false, }) class WithContentCmpt { @ViewChild('ref', {static: true}) directiveRef: any; } @Component({ selector: 're-project', template: '<ng-content></ng-content>', standalone: false, }) class ReProjectCmpt {} @Directive({ selector: '[insert]', standalone: false, }) class InsertTplRef implements OnInit { constructor( private _vcRef: ViewContainerRef, private _tplRef: TemplateRef<{}>, ) {} ngOnInit() { this._vcRef.createEmbeddedView(this._tplRef); } } @Directive({ selector: '[delayedInsert]', exportAs: 'delayedInsert', standalone: false, }) class DelayedInsertTplRef { constructor( public vc: ViewContainerRef, public templateRef: TemplateRef<Object>, ) {} show() { this.vc.createEmbeddedView(this.templateRef); } hide() { this.vc.clear(); } } let fixture: ComponentFixture<TestComponent>; function createCmptInstance( tpl: string, projectableNodes: any[][], ): ComponentRef<WithContentCmpt> { TestBed.configureTestingModule({ declarations: [ WithContentCmpt, InsertTplRef, DelayedInsertTplRef, ReProjectCmpt, TestComponent, ], }); TestBed.overrideTemplate(WithContentCmpt, tpl); fixture = TestBed.createComponent(TestComponent); const vcr = fixture.componentInstance.vcr; const cmptRef = vcr.createComponent(WithContentCmpt, { injector: Injector.NULL, projectableNodes, }); cmptRef.changeDetectorRef.detectChanges(); return cmptRef; } it('should pass nodes to the default ng-content without selectors', () => { const cmptRef = createCmptInstance('<div>(<ng-content></ng-content>)</div>', [ [document.createTextNode('A')], ]); expect(cmptRef.location.nativeElement).toHaveText('(A)'); }); it('should pass nodes to the default ng-content at the root', () => { const cmptRef = createCmptInstance('<ng-content></ng-content>', [ [document.createTextNode('A')], ]); expect(cmptRef.location.nativeElement).toHaveText('A'); }); it('should pass nodes to multiple ng-content tags', () => { const cmptRef = createCmptInstance( 'A:(<ng-content></ng-content>)B:(<ng-content select="b"></ng-content>)C:(<ng-content select="c"></ng-content>)', [ [document.createTextNode('A')], [document.createTextNode('B')], [document.createTextNode('C')], ], ); expect(cmptRef.location.nativeElement).toHaveText('A:(A)B:(B)C:(C)'); }); it('should pass nodes to the default ng-content inside ng-container', () => { const cmptRef = createCmptInstance( 'A<ng-container>(<ng-content></ng-content>)</ng-container>C', [[document.createTextNode('B')]], ); expect(cmptRef.location.nativeElement).toHaveText('A(B)C'); }); it('should pass nodes to the default ng-content inside an embedded view', () => { const cmptRef = createCmptInstance( 'A<ng-template insert>(<ng-content></ng-content>)</ng-template>C', [[document.createTextNode('B')]], ); expect(cmptRef.location.nativeElement).toHaveText('A(B)C'); }); it('should pass nodes to the default ng-content inside a delayed embedded view', () => { const cmptRef = createCmptInstance( 'A(<ng-template #ref="delayedInsert" delayedInsert>[<ng-content></ng-content>]</ng-template>)C', [[document.createTextNode('B')]], ); expect(cmptRef.location.nativeElement).toHaveText('A()C'); const delayedInsert = cmptRef.instance.directiveRef as DelayedInsertTplRef; delayedInsert.show(); cmptRef.changeDetectorRef.detectChanges(); expect(cmptRef.location.nativeElement).toHaveText('A([B])C'); delayedInsert.hide(); cmptRef.changeDetectorRef.detectChanges(); expect(cmptRef.location.nativeElement).toHaveText('A()C'); }); it('should re-project at the root', () => { const cmptRef = createCmptInstance( 'A[<re-project>(<ng-content></ng-content>)</re-project>]C', [[document.createTextNode('B')]], ); expect(cmptRef.location.nativeElement).toHaveText('A[(B)]C'); }); }); }); @Component({ selector: 'main', template: '', standalone: false, }) class MainComp { text: string = ''; } @Component({ selector: 'other', template: '', standalone: false, }) class OtherComp { text: string = ''; } @Component({ selector: 'simple', inputs: ['stringProp'], template: 'SIMPLE(<ng-content></ng-content>)', standalone: false, }) class Simple { stringProp: string = ''; } @Component({ selector: 'simple-shadow-dom1', template: 'SIMPLE1(<slot></slot>)', encapsulation: ViewEncapsulation.ShadowDom, styles: ['div {color: red}'], standalone: false, }) class SimpleShadowDom1 {} @Component({ selector: 'simple-shadow-dom2', template: 'SIMPLE2(<slot></slot>)', encapsulation: ViewEncapsulation.ShadowDom, styles: ['div {color: blue}'], standalone: false, }) class SimpleShadowDom2 {} @Component({ selector: 'empty', template: '', standalone: false, }) class Empty {} @Component({ selector: 'multiple-content-tags', template: '(<ng-content SELECT=".left"></ng-content>, <ng-content></ng-content>)', standalone: false, }) class MultipleContentTagsComponent {} @Component({ selector: 'single-content-tag', template: '<ng-content SELECT=".target"></ng-content>', standalone: false, }) class SingleContentTagComponent {} @Directive({ selector: '[manual]', standalone: false, }) class ManualViewportDirective { constructor( public vc: ViewContainerRef, public templateRef: TemplateRef<Object>, ) {} show() { this.vc.createEmbeddedView(this.templateRef); } hide() { this.vc.clear(); } } @Directive({ selector: '[project]', standalone: false, }) class ProjectDirective { constructor(public vc: ViewContainerRef) {} show(templateRef: TemplateRef<Object>) { this.vc.createEmbeddedView(templateRef); } hide() { this.vc.clear(); } } @Component({ selector: 'outer-with-indirect-nested', template: 'OUTER(<simple><div><ng-content></ng-content></div></simple>)', standalone: false, }) class OuterWithIndirectNestedComponent {} @Component({ selector: 'outer', template: 'OUTER(<inner><ng-content select=".left" class="left"></ng-content><ng-content></ng-content></inner>)', standalone: false, }) class OuterComponent {} @Component({ selector: 'inner', template: 'INNER(<innerinner><ng-content select=".left" class="left"></ng-content><ng-content></ng-content></innerinner>)', standalone: false, }) class InnerComponent {} @Component({ selector: 'innerinner', template: 'INNERINNER(<ng-content select=".left"></ng-content>,<ng-content></ng-content>)', standalone: false, }) class InnerInnerComponent {} @Component({ selector: 'conditional-content', template: '<div>(<div *manual><ng-content select=".left"></ng-content></div>, <ng-content></ng-content>)</div>', standalone: false, }) class ConditionalContentComponent {} @Component({ selector: 'conditional-text', template: 'MAIN(<ng-template manual>FIRST(<ng-template manual>SECOND(<ng-content></ng-content>)</ng-template>)</ng-template>)', standalone: false, }) class ConditionalTextComponent {} @Component({ selector: 'tab', template: '<div><div *manual>TAB(<ng-content></ng-content>)</div></div>', standalone: false, }) class Tab {} @Component({ selector: 'tree2', inputs: ['depth'], template: 'TREE2({{depth}}:<tree *manual [depth]="depth+1"></tree>)', standalone: false, }) class Tree2 { depth = 0; }
009846
describe('enforce no new changes', () => { it('should throw when a record gets changed after it has been checked', fakeAsync(() => { @Directive({ selector: '[changed]', standalone: false, }) class ChangingDirective { @Input() changed: any; } TestBed.configureTestingModule({declarations: [ChangingDirective]}); const ctx = createCompFixture('<div [id]="a" [changed]="b"></div>', TestData); ctx.componentInstance.b = 1; const errMsgRegExp = /Previous value: 'undefined'\. Current value: '1'/g; expect(() => ctx.checkNoChanges()).toThrowError(errMsgRegExp); })); it('should throw when a record gets changed after the first change detection pass', fakeAsync(() => { @Directive({ selector: '[changed]', standalone: false, }) class ChangingDirective { @Input() changed: any; } TestBed.configureTestingModule({declarations: [ChangingDirective]}); const ctx = createCompFixture('<div [id]="a" [changed]="b"></div>', TestData); ctx.componentInstance.b = 1; ctx.detectChanges(); ctx.componentInstance.b = 2; const errMsgRegExp = /Previous value: '1'\. Current value: '2'/g; expect(() => ctx.checkNoChanges()).toThrowError(errMsgRegExp); })); it('should allow view to be created in a cd hook', () => { const ctx = createCompFixture('<div *gh9882>{{ a }}</div>', TestData); ctx.componentInstance.a = 1; ctx.detectChanges(); expect(ctx.nativeElement.innerText).toEqual('1'); }); it('should not throw when two arrays are structurally the same', fakeAsync(() => { const ctx = _bindSimpleValue('a', TestData); ctx.componentInstance.a = ['value']; ctx.detectChanges(false); ctx.componentInstance.a = ['value']; expect(() => ctx.checkNoChanges()).not.toThrow(); })); it('should not break the next run', fakeAsync(() => { const ctx = _bindSimpleValue('a', TestData); ctx.componentInstance.a = 'value'; expect(() => ctx.checkNoChanges()).toThrow(); ctx.detectChanges(); expect(renderLog.loggedValues).toEqual(['value']); })); it('should not break the next run (view engine and ivy)', fakeAsync(() => { const ctx = _bindSimpleValue('a', TestData); ctx.detectChanges(); renderLog.clear(); ctx.componentInstance.a = 'value'; expect(() => ctx.checkNoChanges()).toThrow(); ctx.detectChanges(); expect(renderLog.loggedValues).toEqual(['value']); })); }); describe('mode', () => { it('Detached', fakeAsync(() => { const ctx = createCompFixture('<comp-with-ref></comp-with-ref>'); const cmp: CompWithRef = queryDirs(ctx.debugElement, CompWithRef)[0]; cmp.value = 'hello'; cmp.changeDetectorRef.detach(); ctx.detectChanges(); expect(renderLog.log).toEqual([]); })); it('Detached should disable OnPush', fakeAsync(() => { const ctx = createCompFixture('<push-cmp [value]="value"></push-cmp>'); ctx.componentInstance.value = 0; ctx.detectChanges(); renderLog.clear(); const cmp: CompWithRef = queryDirs(ctx.debugElement, PushComp)[0]; cmp.changeDetectorRef.detach(); ctx.componentInstance.value = 1; ctx.detectChanges(); expect(renderLog.log).toEqual([]); })); it('Detached view can be checked locally', fakeAsync(() => { const ctx = createCompFixture('<wrap-comp-with-ref></wrap-comp-with-ref>'); const cmp: CompWithRef = queryDirs(ctx.debugElement, CompWithRef)[0]; cmp.value = 'hello'; cmp.changeDetectorRef.detach(); expect(renderLog.log).toEqual([]); ctx.detectChanges(); expect(renderLog.log).toEqual([]); cmp.changeDetectorRef.detectChanges(); expect(renderLog.log).toEqual(['{{hello}}']); })); it('Reattaches', fakeAsync(() => { const ctx = createCompFixture('<comp-with-ref></comp-with-ref>'); const cmp: CompWithRef = queryDirs(ctx.debugElement, CompWithRef)[0]; cmp.value = 'hello'; cmp.changeDetectorRef.detach(); ctx.detectChanges(); expect(renderLog.log).toEqual([]); cmp.changeDetectorRef.reattach(); ctx.detectChanges(); expect(renderLog.log).toEqual(['{{hello}}']); })); it('Reattaches in the original cd mode', fakeAsync(() => { const ctx = createCompFixture('<push-cmp></push-cmp>'); const cmp: PushComp = queryDirs(ctx.debugElement, PushComp)[0]; cmp.changeDetectorRef.detach(); cmp.changeDetectorRef.reattach(); // renderCount should NOT be incremented with each CD as CD mode // should be resetted to // on-push ctx.detectChanges(); expect(cmp.renderCount).toBeGreaterThan(0); const count = cmp.renderCount; ctx.detectChanges(); expect(cmp.renderCount).toBe(count); })); });
009866
/** * @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 {computed, signal} from '@angular/core'; import {ReactiveNode, setPostSignalSetFn, SIGNAL} from '@angular/core/primitives/signals'; describe('signals', () => { it('should be a getter which reflects the set value', () => { const state = signal(false); expect(state()).toBeFalse(); state.set(true); expect(state()).toBeTrue(); }); it('should accept update function to set new value based on the previous one', () => { const counter = signal(0); expect(counter()).toEqual(0); counter.update((c) => c + 1); expect(counter()).toEqual(1); }); it('should not update signal when new value is equal to the previous one', () => { const state = signal('aaa', {equal: (a, b) => a.length === b.length}); expect(state()).toEqual('aaa'); // set to a "different" value that is "equal" to the previous one // there should be no change in the signal's value as the new value is determined to be equal // to the previous one state.set('bbb'); expect(state()).toEqual('aaa'); state.update((_) => 'ccc'); expect(state()).toEqual('aaa'); // setting a "non-equal" value state.set('d'); expect(state()).toEqual('d'); }); it('should not propagate change when the new signal value is equal to the previous one', () => { const state = signal('aaa', {equal: (a, b) => a.length === b.length}); const upper = computed(() => state().toUpperCase()); // set to a "different" value that is "equal" to the previous one // there should be no change in the signal's value as the new value is determined to be equal // to the previous one state.set('bbb'); expect(upper()).toEqual('AAA'); state.update((_) => 'ccc'); expect(upper()).toEqual('AAA'); // setting a "non-equal" value state.set('d'); expect(upper()).toEqual('D'); }); it('should consider objects as equal based on their identity with the default equality function', () => { let stateValue: unknown = {}; const state = signal(stateValue); let computeCount = 0; const derived = computed(() => `${typeof state()}:${++computeCount}`); expect(derived()).toEqual('object:1'); // reset signal value to the same object instance, expect NO change notification state.set(stateValue); expect(derived()).toEqual('object:1'); // reset signal value to a different object instance, expect change notification stateValue = {}; state.set(stateValue); expect(derived()).toEqual('object:2'); // reset signal value to a different object type, expect change notification stateValue = []; state.set(stateValue); expect(derived()).toEqual('object:3'); // reset signal value to the same array instance, expect NO change notification state.set(stateValue); expect(derived()).toEqual('object:3'); }); it('should invoke custom equality function even if old / new references are the same', () => { const state = {value: 0}; const stateSignal = signal(state, {equal: (a, b) => false}); let computeCount = 0; const derived = computed(() => `${stateSignal().value}:${++computeCount}`); // derived is re-computed initially expect(derived()).toBe('0:1'); // setting signal with the same reference should propagate change due to the custom equality stateSignal.set(state); expect(derived()).toBe('0:2'); // updating signal with the same reference should propagate change as well stateSignal.update((state) => state); expect(derived()).toBe('0:3'); }); it('should allow converting writable signals to their readonly counterpart', () => { const counter = signal(0); const readOnlyCounter = counter.asReadonly(); // @ts-expect-error expect(readOnlyCounter.set).toBeUndefined(); // @ts-expect-error expect(readOnlyCounter.update).toBeUndefined(); const double = computed(() => readOnlyCounter() * 2); expect(double()).toBe(0); counter.set(2); expect(double()).toBe(4); }); it('should have a toString implementation', () => { const state = signal(false); expect(state + '').toBe('[Signal: false]'); }); it('should set debugName when a debugName is provided', () => { const node = signal(false, {debugName: 'falseSignal'})[SIGNAL] as ReactiveNode; expect(node.debugName).toBe('falseSignal'); }); describe('optimizations', () => { it('should not repeatedly poll status of a non-live node if no signals have changed', () => { const unrelated = signal(0); const source = signal(1); let computations = 0; const derived = computed(() => { computations++; return source() * 2; }); expect(derived()).toBe(2); expect(computations).toBe(1); const sourceNode = source[SIGNAL] as ReactiveNode; // Forcibly increment the version of the source signal. This will cause a mismatch during // polling, and will force the derived signal to recompute if polled (which we should observe // in this test). sourceNode.version++; // Read the derived signal again. This should not recompute (even with the forced version // update) as no signals have been set since the last read. expect(derived()).toBe(2); expect(computations).toBe(1); // Set the `unrelated` signal, which now means that `derived` should poll if read again. // Because of the forced version, that poll will cause a recomputation which we will observe. unrelated.set(1); expect(derived()).toBe(2); expect(computations).toBe(2); }); }); describe('post-signal-set functions', () => { let prevPostSignalSetFn: (() => void) | null = null; let log: number; beforeEach(() => { log = 0; prevPostSignalSetFn = setPostSignalSetFn(() => log++); }); afterEach(() => { setPostSignalSetFn(prevPostSignalSetFn); }); it('should call the post-signal-set fn when invoking .set()', () => { const counter = signal(0); counter.set(1); expect(log).toBe(1); }); it('should call the post-signal-set fn when invoking .update()', () => { const counter = signal(0); counter.update((c) => c + 2); expect(log).toBe(1); }); it("should not call the post-signal-set fn when the value doesn't change", () => { const counter = signal(0); counter.set(0); expect(log).toBe(0); }); }); });
009867
/** * @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 {computed, signal} from '@angular/core'; import {createWatch} from '@angular/core/primitives/signals'; import {flushEffects, resetEffects, testingEffect} from './effect_util'; const NOOP_FN = () => {}; describe('watchers', () => { afterEach(() => { resetEffects(); }); it('should create and run once, even without dependencies', () => { let runs = 0; testingEffect(() => { runs++; }); flushEffects(); expect(runs).toEqual(1); }); it('should schedule on dependencies (signal) change', () => { const count = signal(0); let runLog: number[] = []; const effectRef = testingEffect(() => { runLog.push(count()); }); flushEffects(); expect(runLog).toEqual([0]); count.set(1); flushEffects(); expect(runLog).toEqual([0, 1]); }); it('should not schedule when a previous dependency changes', () => { const increment = (value: number) => value + 1; const countA = signal(0); const countB = signal(100); const useCountA = signal(true); const runLog: number[] = []; testingEffect(() => { runLog.push(useCountA() ? countA() : countB()); }); flushEffects(); expect(runLog).toEqual([0]); countB.update(increment); flushEffects(); // No update expected: updated the wrong signal. expect(runLog).toEqual([0]); countA.update(increment); flushEffects(); expect(runLog).toEqual([0, 1]); useCountA.set(false); flushEffects(); expect(runLog).toEqual([0, 1, 101]); countA.update(increment); flushEffects(); // No update expected: updated the wrong signal. expect(runLog).toEqual([0, 1, 101]); }); it("should not update dependencies when dependencies don't change", () => { const source = signal(0); const isEven = computed(() => source() % 2 === 0); let updateCounter = 0; testingEffect(() => { isEven(); updateCounter++; }); flushEffects(); expect(updateCounter).toEqual(1); source.set(1); flushEffects(); expect(updateCounter).toEqual(2); source.set(3); flushEffects(); expect(updateCounter).toEqual(2); source.set(4); flushEffects(); expect(updateCounter).toEqual(3); }); it('should allow registering cleanup function from the watch logic', () => { const source = signal(0); const seenCounterValues: number[] = []; testingEffect((onCleanup) => { seenCounterValues.push(source()); // register a cleanup function that is executed every time an effect re-runs onCleanup(() => { if (seenCounterValues.length === 2) { seenCounterValues.length = 0; } }); }); flushEffects(); expect(seenCounterValues).toEqual([0]); source.update((c) => c + 1); flushEffects(); expect(seenCounterValues).toEqual([0, 1]); source.update((c) => c + 1); flushEffects(); // cleanup (array trim) should have run before executing effect expect(seenCounterValues).toEqual([2]); }); it('should forget previously registered cleanup function when effect re-runs', () => { const source = signal(0); const seenCounterValues: number[] = []; testingEffect((onCleanup) => { const value = source(); seenCounterValues.push(value); // register a cleanup function that is executed next time an effect re-runs if (value === 0) { onCleanup(() => { seenCounterValues.length = 0; }); } }); flushEffects(); expect(seenCounterValues).toEqual([0]); source.set(2); flushEffects(); // cleanup (array trim) should have run before executing effect expect(seenCounterValues).toEqual([2]); source.set(3); flushEffects(); // cleanup (array trim) should _not_ be registered again expect(seenCounterValues).toEqual([2, 3]); }); it('should throw an error when reading a signal during the notification phase', () => { const source = signal(0); let ranScheduler = false; const w = createWatch( () => { source(); }, () => { ranScheduler = true; expect(() => source()).toThrow(); }, false, ); // Run the effect manually to initiate dependency tracking. w.run(); // Changing the signal will attempt to schedule the effect. source.set(1); expect(ranScheduler).toBeTrue(); }); describe('destroy', () => { it('should not run destroyed watchers', () => { let watchRuns = 0; const watchRef = createWatch( () => { watchRuns++; }, NOOP_FN, false, ); watchRef.run(); expect(watchRuns).toBe(1); watchRef.destroy(); watchRef.run(); expect(watchRuns).toBe(1); }); it('should disconnect destroyed watches from the reactive graph', () => { const counter = signal(0); let scheduleCount = 0; const watchRef = createWatch( () => counter(), () => scheduleCount++, false, ); // watches are _not_ scheduled by default, run it for the first time to capture // dependencies watchRef.run(); expect(scheduleCount).toBe(0); watchRef.destroy(); counter.set(1); expect(scheduleCount).toBe(0); }); it('should not schedule destroyed watches', () => { let scheduleCount = 0; const watchRef = createWatch(NOOP_FN, () => scheduleCount++, false); // watches are _not_ scheduled by default expect(scheduleCount).toBe(0); watchRef.notify(); expect(scheduleCount).toBe(1); watchRef.destroy(); watchRef.notify(); expect(scheduleCount).toBe(1); }); it('should not run cleanup functions after destroy', () => { const counter = signal(0); let cleanupRuns = 0; const watchRef = createWatch( (onCleanup) => { counter(); onCleanup(() => cleanupRuns++); }, NOOP_FN, false, ); // initial run to register cleanup function watchRef.run(); watchRef.destroy(); // cleanup functions run on destroy expect(cleanupRuns).toBe(1); // subsequent destroy should be noop watchRef.destroy(); expect(cleanupRuns).toBe(1); }); }); });
009869
/** * @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 {computed, signal, untracked} from '@angular/core'; import {flushEffects, resetEffects, testingEffect} from './effect_util'; describe('non-reactive reads', () => { afterEach(() => { resetEffects(); }); it('should read the latest value from signal', () => { const counter = signal(0); expect(untracked(counter)).toEqual(0); counter.set(1); expect(untracked(counter)).toEqual(1); }); it('should not add dependencies to computed when reading a value from a signal', () => { const counter = signal(0); const double = computed(() => untracked(counter) * 2); expect(double()).toEqual(0); counter.set(2); expect(double()).toEqual(0); }); it('should refresh computed value if stale and read non-reactively ', () => { const counter = signal(0); const double = computed(() => counter() * 2); expect(untracked(double)).toEqual(0); counter.set(2); expect(untracked(double)).toEqual(4); }); it('should not make surrounding effect depend on the signal', () => { const s = signal(1); const runLog: number[] = []; testingEffect(() => { runLog.push(untracked(s)); }); // an effect will run at least once flushEffects(); expect(runLog).toEqual([1]); // subsequent signal changes should not trigger effects as signal is untracked s.set(2); flushEffects(); expect(runLog).toEqual([1]); }); it('should schedule on dependencies (computed) change', () => { const count = signal(0); const double = computed(() => count() * 2); let runLog: number[] = []; testingEffect(() => { runLog.push(double()); }); flushEffects(); expect(runLog).toEqual([0]); count.set(1); flushEffects(); expect(runLog).toEqual([0, 2]); }); it('should non-reactively read all signals accessed inside untrack', () => { const first = signal('John'); const last = signal('Doe'); let runLog: string[] = []; const effectRef = testingEffect(() => { untracked(() => runLog.push(`${first()} ${last()}`)); }); // effects run at least once flushEffects(); expect(runLog).toEqual(['John Doe']); // change one of the signals - should not update as not read reactively first.set('Patricia'); flushEffects(); expect(runLog).toEqual(['John Doe']); // change one of the signals - should not update as not read reactively last.set('Garcia'); flushEffects(); expect(runLog).toEqual(['John Doe']); }); });
009870
/** * @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 {computed, signal} from '@angular/core'; import {createWatch, ReactiveNode, SIGNAL} from '@angular/core/primitives/signals'; describe('computed', () => { it('should create computed', () => { const counter = signal(0); let computedRunCount = 0; const double = computed(() => `${counter() * 2}:${++computedRunCount}`); expect(double()).toEqual('0:1'); counter.set(1); expect(double()).toEqual('2:2'); expect(double()).toEqual('2:2'); counter.set(2); expect(double()).toEqual('4:3'); expect(double()).toEqual('4:3'); }); it('should not re-compute if there are no dependencies', () => { let tick = 0; const c = computed(() => ++tick); expect(c()).toEqual(1); expect(c()).toEqual(1); }); it('should not re-compute if the dependency is a primitive value and the value did not change', () => { const counter = signal(0); let computedRunCount = 0; const double = computed(() => `${counter() * 2}:${++computedRunCount}`); expect(double()).toEqual('0:1'); counter.set(0); expect(double()).toEqual('0:1'); }); it('should chain computed', () => { const name = signal('abc'); const reverse = computed(() => name().split('').reverse().join('')); const upper = computed(() => reverse().toUpperCase()); expect(upper()).toEqual('CBA'); name.set('foo'); expect(upper()).toEqual('OOF'); }); it('should evaluate computed only when subscribing', () => { const name = signal('John'); const age = signal(25); const show = signal(true); let computeCount = 0; const displayName = computed( () => `${show() ? `${name()} aged ${age()}` : 'anonymous'}:${++computeCount}`, ); expect(displayName()).toEqual('John aged 25:1'); show.set(false); expect(displayName()).toEqual('anonymous:2'); name.set('Bob'); expect(displayName()).toEqual('anonymous:2'); }); it('should detect simple dependency cycles', () => { const a: () => unknown = computed(() => a()); expect(() => a()).toThrowError('Detected cycle in computations.'); }); it('should detect deep dependency cycles', () => { const a: () => unknown = computed(() => b()); const b = computed(() => c()); const c = computed(() => d()); const d = computed(() => a()); expect(() => a()).toThrowError('Detected cycle in computations.'); }); it('should cache exceptions thrown until computed gets dirty again', () => { const toggle = signal('KO'); const c = computed(() => { const val = toggle(); if (val === 'KO') { throw new Error('KO'); } else { return val; } }); expect(() => c()).toThrowError('KO'); expect(() => c()).toThrowError('KO'); toggle.set('OK'); expect(c()).toEqual('OK'); }); it("should not update dependencies of computations when dependencies don't change", () => { const source = signal(0); const isEven = computed(() => source() % 2 === 0); let updateCounter = 0; const updateTracker = computed(() => { isEven(); return updateCounter++; }); updateTracker(); expect(updateCounter).toEqual(1); source.set(1); updateTracker(); expect(updateCounter).toEqual(2); // Setting the counter to another odd value should not trigger `updateTracker` to update. source.set(3); updateTracker(); expect(updateCounter).toEqual(2); source.set(4); updateTracker(); expect(updateCounter).toEqual(3); }); it('should not mark dirty computed signals that are dirty already', () => { const source = signal('a'); const derived = computed(() => source().toUpperCase()); let watchCount = 0; const w = createWatch( () => { derived(); }, () => { watchCount++; }, false, ); w.run(); expect(watchCount).toEqual(0); // change signal, mark downstream dependencies dirty source.set('b'); expect(watchCount).toEqual(1); // change signal again, downstream dependencies should be dirty already and not marked again source.set('c'); expect(watchCount).toEqual(1); // resetting dependencies back to clean w.run(); expect(watchCount).toEqual(1); // expecting another notification at this point source.set('d'); expect(watchCount).toEqual(2); }); it('should allow signal creation within computed', () => { const doubleCounter = computed(() => { const counter = signal(1); return counter() * 2; }); expect(doubleCounter()).toBe(2); }); it('should disallow writing to signals within computed', () => { const source = signal(0); const illegal = computed(() => { source.set(1); return 0; }); expect(illegal).toThrow(); }); it('should have a toString implementation', () => { const counter = signal(1); const double = computed(() => counter() * 2); expect(double + '').toBe('[Computed: 2]'); }); it('should set debugName when a debugName is provided', () => { const primitiveSignal = signal(0); const node = computed(() => primitiveSignal(), {debugName: 'computedSignal'})[ SIGNAL ] as ReactiveNode; expect(node.debugName).toBe('computedSignal'); }); });
009871
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {isSignal, linkedSignal, signal, computed} from '@angular/core'; import {testingEffect} from './effect_util'; describe('linkedSignal', () => { it('should conform to the writable signals contract', () => { const firstLetter = linkedSignal({source: signal<string>('foo'), computation: (str) => str[0]}); expect(isSignal(firstLetter)).toBeTrue(); firstLetter.set('a'); expect(firstLetter()).toBe('a'); firstLetter.update((_) => 'b'); expect(firstLetter()).toBe('b'); const firstLetterReadonly = firstLetter.asReadonly(); expect(firstLetterReadonly()).toBe('b'); firstLetter.set('c'); expect(firstLetterReadonly()).toBe('c'); expect(firstLetter.toString()).toBe('[LinkedSignal: c]'); }); it('should conform to the writable signals contract - shorthand', () => { const str = signal<string>('foo'); const firstLetter = linkedSignal(() => str()[0]); expect(isSignal(firstLetter)).toBeTrue(); firstLetter.set('a'); expect(firstLetter()).toBe('a'); firstLetter.update((_) => 'b'); expect(firstLetter()).toBe('b'); const firstLetterReadonly = firstLetter.asReadonly(); expect(firstLetterReadonly()).toBe('b'); firstLetter.set('c'); expect(firstLetterReadonly()).toBe('c'); }); it('should update when the source changes', () => { const options = signal(['apple', 'banana', 'fig']); const choice = linkedSignal({ source: options, computation: (options) => options[0], }); expect(choice()).toBe('apple'); choice.set('fig'); expect(choice()).toBe('fig'); options.set(['orange', 'apple', 'pomegranate']); expect(choice()).toBe('orange'); }); it('should expose previous source in the computation function', () => { const options = signal(['apple', 'banana', 'fig']); const choice = linkedSignal<string[], string>({ source: options, computation: (options, previous) => { if (previous !== undefined && options.includes(previous.value)) { return previous.value; } else { return options[0]; } }, }); expect(choice()).toBe('apple'); options.set(['orange', 'apple', 'pomegranate']); expect(choice()).toBe('apple'); }); it('should expose previous value in the computation function', () => { const options = signal(['apple', 'banana', 'fig']); const choice = linkedSignal<string[], number>({ source: options, computation: (options, previous) => { if (previous !== undefined) { const prevChoice = previous.source[previous.value]; const newIdx = options.indexOf(prevChoice); return newIdx === -1 ? 0 : newIdx; } else { return 0; } }, }); expect(choice()).toBe(0); choice.set(2); // choosing a fig options.set(['banana', 'fig', 'apple']); // a fig moves to a new place in the updated resource expect(choice()).toBe(1); }); it('should expose previous value in the computation function in larger reactive graph', () => { const options = signal(['apple', 'banana', 'fig']); const choice = linkedSignal<string[], number>({ source: options, computation: (options, previous) => { if (previous !== undefined) { const prevChoice = previous.source[previous.value]; const newIdx = options.indexOf(prevChoice); return newIdx === -1 ? 0 : newIdx; } else { return 0; } }, }); const doubleChoice = computed(() => choice() * 2); expect(doubleChoice()).toBe(0); choice.set(2); // choosing a fig options.set(['banana', 'fig', 'apple']); // a fig moves to a new place in the updated resource expect(doubleChoice()).toBe(2); expect(choice()).toBe(1); }); it('should not update the value if the new choice is considered equal to the previous one', () => { const counter = signal(0); const choice = linkedSignal({ source: counter, computation: (c) => c, equal: (a, b) => true, }); expect(choice()).toBe(0); // updates from the "commanding signal" should follow equality rules counter.update((c) => c + 1); expect(choice()).toBe(0); // the same equality rules should apply to the state signal choice.set(10); expect(choice()).toBe(0); }); it('should support shorthand version', () => { const options = signal(['apple', 'banana', 'fig']); const choice = linkedSignal(() => options()[0]); expect(choice()).toBe('apple'); choice.set('orange'); expect(options()).toEqual(['apple', 'banana', 'fig']); expect(choice()).toBe('orange'); options.set(['banana', 'fig']); expect(choice()).toBe('banana'); }); it('should have explicitly set value', () => { const counter = signal(0); const options = signal(['apple', 'banana', 'fig']); const choice = linkedSignal(() => options()[0]); expect(choice()).toBe('apple'); // state signal is updated while the "commanding" state has pending changes - we assume that the explicit state set is "more important" here options.set(['orange', 'apple', 'pomegranate']); choice.set('watermelon'); // unrelated state changes should not effect the test results counter.update((c) => c + 1); expect(choice()).toBe('watermelon'); // state signal is updated just before changes to the "commanding" state - here we default to the usual situation of the linked state triggering computation choice.set('persimmon'); options.set(['apple', 'banana', 'fig']); expect(choice()).toBe('apple'); // another change using the "update" code-path options.set(['orange', 'apple', 'pomegranate']); choice.update((f) => f.toUpperCase()); expect(choice()).toBe('ORANGE'); }); it('should have explicitly set value - live consumer', () => { const options = signal(['apple', 'banana', 'fig']); const choice = linkedSignal(() => options()[0]); expect(choice()).toBe('apple'); // create an effect to mark the linkedSignal as live consumer const watchDestroy = testingEffect(() => choice()); try { // state signal is updated while the "commanding" state has pending changes - we assume that the explicit state set is "more important" here const counter = signal(0); options.set(['orange', 'apple', 'pomegranate']); choice.set('watermelon'); // unrelated state changes should not effect the test results counter.update((c) => c + 1); expect(choice()).toBe('watermelon'); // state signal is updated just before changes to the "commanding" state - here we default to the usual situation of the linked state triggering computation choice.set('persimmon'); options.set(['apple', 'banana', 'fig']); expect(choice()).toBe('apple'); // another change using the "update" code-path options.set(['orange', 'apple', 'pomegranate']); choice.update((f) => f.toUpperCase()); expect(choice()).toBe('ORANGE'); } finally { watchDestroy(); } }); it('should capture linked signal dependencies even if the value is set before the initial read', () => { const options = signal(['apple', 'banana', 'fig']); const choice = linkedSignal(() => options()[0]); choice.set('watermelon'); expect(choice()).toBe('watermelon'); options.set(['orange', 'apple', 'pomegranate']); expect(choice()).toBe('orange'); }); it('should pull latest dependency values before state update', () => { const options = signal(['apple', 'banana', 'fig']); const choice = linkedSignal(() => options()[0]); choice.update((fruit) => fruit.toUpperCase()); expect(choice()).toBe('APPLE'); }); it('should reset error state after manual state update', () => { const choice = linkedSignal<string>(() => { throw new Error("Can't compute"); }); expect(() => { choice(); }).toThrowError("Can't compute"); choice.set('explicit'); expect(choice()).toBe('explicit'); }); });
009872
/** * @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 {computed, isSignal, signal} from '@angular/core'; describe('isSignal', () => { it('should return true for writable signal', () => { const writableSignal = signal('Angular'); expect(isSignal(writableSignal)).toBe(true); }); it('should return true for readonly signal', () => { const readonlySignal = computed(() => 10); expect(isSignal(readonlySignal)).toBe(true); }); it('should return false for primitive', () => { const primitive = 0; expect(isSignal(primitive)).toBe(false); }); it('should return false for object', () => { const object = {name: 'Angular'}; expect(isSignal(object)).toBe(false); }); it('should return false for function', () => { const fn = () => {}; expect(isSignal(fn)).toBe(false); }); });
009881
nction () { // these tests are only meant to be run within the DOM (for now) if (isNode) return; describe('animation tests', function () { function getLog(): MockAnimationPlayer[] { return MockAnimationDriver.log as MockAnimationPlayer[]; } function resetLog() { MockAnimationDriver.log = []; } beforeEach(() => { resetLog(); TestBed.configureTestingModule({ providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}], imports: [BrowserAnimationsModule], }); }); describe('animation modules', function () { it('should hint at BrowserAnimationsModule being used', () => { TestBed.resetTestingModule(); TestBed.configureTestingModule({ declarations: [SharedAnimationCmp], imports: [BrowserAnimationsModule], }); const fixture = TestBed.createComponent(SharedAnimationCmp); expect(fixture.componentInstance.animationType).toEqual('BrowserAnimations'); }); it('should hint at NoopAnimationsModule being used', () => { TestBed.resetTestingModule(); TestBed.configureTestingModule({ declarations: [SharedAnimationCmp], imports: [NoopAnimationsModule], }); const fixture = TestBed.createComponent(SharedAnimationCmp); expect(fixture.componentInstance.animationType).toEqual('NoopAnimations'); }); it('should hint at NoopAnimationsModule being used when BrowserAnimationsModule is provided with disabled animations', () => { TestBed.resetTestingModule(); TestBed.configureTestingModule({ declarations: [SharedAnimationCmp], imports: [BrowserAnimationsModule.withConfig({disableAnimations: true})], }); const fixture = TestBed.createComponent(SharedAnimationCmp); expect(fixture.componentInstance.animationType).toEqual('NoopAnimations'); }); }); @Component({ template: '<p>template text</p>', standalone: false, }) class SharedAnimationCmp { constructor( @Inject(ANIMATION_MODULE_TYPE) public animationType: 'NoopAnimations' | 'BrowserAnimations', ) {} } describe('fakeAsync testing', () => { it('should only require one flushMicrotasks call to kick off animation callbacks', fakeAsync(() => { @Component({ selector: 'cmp', template: ` <div [@myAnimation]="exp" (@myAnimation.start)="cb('start')" (@myAnimation.done)="cb('done')"></div> `, animations: [ trigger('myAnimation', [ transition('* => on, * => off', [animate(1000, style({opacity: 1}))]), ]), ], standalone: false, }) class Cmp { exp: any = false; status: string = ''; cb(status: string) { this.status = status; } } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'on'; fixture.detectChanges(); expect(cmp.status).toEqual(''); flushMicrotasks(); expect(cmp.status).toEqual('start'); let player = MockAnimationDriver.log.pop()!; player.finish(); expect(cmp.status).toEqual('done'); cmp.status = ''; cmp.exp = 'off'; fixture.detectChanges(); expect(cmp.status).toEqual(''); player = MockAnimationDriver.log.pop()!; player.finish(); expect(cmp.status).toEqual(''); flushMicrotasks(); expect(cmp.status).toEqual('done'); })); it('should always run .start callbacks before .done callbacks even for noop animations', fakeAsync(() => { @Component({ selector: 'cmp', template: ` <div [@myAnimation]="exp" (@myAnimation.start)="cb('start')" (@myAnimation.done)="cb('done')"></div> `, animations: [trigger('myAnimation', [transition('* => go', [])])], standalone: false, }) class Cmp { exp: any = false; log: string[] = []; cb(status: string) { this.log.push(status); } } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'go'; fixture.detectChanges(); expect(cmp.log).toEqual([]); flushMicrotasks(); expect(cmp.log).toEqual(['start', 'done']); })); it('should emit the correct totalTime value for a noop-animation', fakeAsync(() => { @Component({ selector: 'cmp', template: ` <div [@myAnimation]="exp" (@myAnimation.start)="cb($event)" (@myAnimation.done)="cb($event)"></div> `, animations: [ trigger('myAnimation', [transition('* => go', [animate('1s', style({opacity: 0}))])]), ], standalone: false, }) class Cmp { exp: any = false; log: AnimationEvent[] = []; cb(event: AnimationEvent) { this.log.push(event); } } TestBed.configureTestingModule({ declarations: [Cmp], providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}], }); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'go'; fixture.detectChanges(); expect(cmp.log).toEqual([]); flushMicrotasks(); expect(cmp.log.length).toEqual(2); const [start, end] = cmp.log; expect(start.totalTime).toEqual(1000); expect(end.totalTime).toEqual(1000); })); }); describe('component fixture integration', () => { describe('whenRenderingDone', () => { it('should wait until the animations are finished until continuing', fakeAsync(() => { @Component({ selector: 'cmp', template: ` <div [@myAnimation]="exp"></div> `, animations: [ trigger('myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])]), ], standalone: false, }) class Cmp { exp: any = false; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; let isDone = false; fixture.whenRenderingDone().then(() => (isDone = true)); expect(isDone).toBe(false); cmp.exp = 'on'; fixture.detectChanges(); engine.flush(); expect(isDone).toBe(false); const players = engine.players; expect(players.length).toEqual(1); players[0].finish(); expect(isDone).toBe(false); flushMicrotasks(); expect(isDone).toBe(true); })); it('should wait for a noop animation to finish before continuing', fakeAsync(() => { @Component({ selector: 'cmp', template: ` <div [@myAnimation]="exp"></div> `, animations: [ trigger('myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])]), ], standalone: false, }) class Cmp { exp: any = false; } TestBed.configureTestingModule({ providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}], declarations: [Cmp], }); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; let isDone = false; fixture.whenRenderingDone().then(() => (isDone = true)); expect(isDone).toBe(false); cmp.exp = 'off'; fixture.detectChanges(); engine.flush(); expect(isDone).toBe(false); flushMicrotasks(); expect(isDone).toBe(true); })); it('should wait for active animations to finish even if they have already started', fakeAsync(() => { @Component({ selector: 'cmp', template: ` <div [@myAnimation]="exp"></div> `, animations: [ trigger('myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])]), ], standalone: false, }) class Cmp { exp: any = false; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'on'; fixture.detectChanges(); engine.flush(); const players = engine.players; expect(players.length).toEqual(1); let isDone = false; fixture.whenRenderingDone().then(() => (isDone = true)); flushMicrotasks(); expect(isDone).toBe(false); players[0].finish(); flushMicrotasks(); expect(isDone).toBe(true); })); }); });
009897
ransitions', () => { @Component({ selector: 'if-cmp', template: ` <div [@myAnimation]="exp"></div> `, animations: [ trigger('myAnimation', [ transition('void => *', [style({opacity: 0}), animate('0.5s 1s', style({opacity: 1}))]), transition('* => void', [ animate(1000, style({height: 0})), animate(1000, style({opacity: 0})), ]), ]), ], standalone: false, }) class Cmp { exp: any = false; } TestBed.configureTestingModule({declarations: [Cmp]}); expect(() => { TestBed.createComponent(Cmp); }).not.toThrowError(); }); it("should add the transition provided delay to all the transition's timelines", () => { @Component({ selector: 'cmp', template: ` <div @parent *ngIf="exp"> <div @child *ngIf="exp"></div> </div> `, animations: [ trigger('parent', [ transition( ':enter', [ style({background: 'red'}), group( [ animate('1s 3s ease', style({background: 'green'})), query('@child', animateChild()), ], {delay: 111}, ), ], {delay: '2s'}, ), ]), trigger('child', [ transition( ':enter', [style({color: 'white'}), animate('2s 3s ease', style({color: 'black'}))], {delay: 222}, ), ]), ], standalone: false, }) class Cmp { exp: boolean = false; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = true; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(4); // players: // - scp (skipped child player): player for the child animation // - pp1 (parent player 1): player for parent animation (from background red to red) // - pp2 (parent player 2): player for parent animation (from background red to green) // - pcp (parent child player): // player for child animation executed by parent via query and animateChild const [scp, pp1, pp2, pcp] = players; expect(scp.delay).toEqual(222); expect(pp1.delay).toEqual(2000); expect(pp2.delay).toEqual(2111); // 2000 + 111 expect(pcp.delay).toEqual(0); // all the delays are included in the child animation expect(pcp.duration).toEqual(7333); // 2s + 3s + 2000 + 111 + 222 }); it('should keep (transition from/to) styles defined in different timelines', () => { @Component({ selector: 'cmp', template: '<div @animation *ngIf="exp"></div>', animations: [ trigger('animation', [ transition(':enter', [ group([ style({opacity: 0, color: 'red'}), // Note: the objective of this test is to make sure the animation // transitions from opacity 0 and color red to opacity 1 and color blue, // even though the two styles are defined in different timelines animate(500, style({opacity: 1, color: 'blue'})), ]), ]), ]), ], standalone: false, }) class Cmp { exp: boolean = false; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = true; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(1); const [player] = players; expect(player.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0'], ['color', 'red'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '1'], ['color', 'blue'], ['offset', 1], ]), ]); }); describe('errors for not using the animation module', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{provide: RendererFactory2, useExisting: ɵDomRendererFactory2}], }); }); function syntheticPropError(name: string, nameKind: string) { return `NG05105: Unexpected synthetic ${nameKind} ${name} found. Please make sure that: - Either \`BrowserAnimationsModule\` or \`NoopAnimationsModule\` are imported in your application. - There is corresponding configuration for the animation named \`${name}\` defined in the \`animations\` field of the \`@Component\` decorator (see https://angular.io/api/core/Component#animations).`; } describe('when modules are missing', () => { it('should throw when using an @prop binding without the animation module', () => { @Component({ template: `<div [@myAnimation]="true"></div>`, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const comp = TestBed.createComponent(Cmp); expect(() => comp.detectChanges()).toThrowError( syntheticPropError('@myAnimation', 'property'), ); }); it('should throw when using an @prop listener without the animation module', () => { @Component({ template: `<div (@myAnimation.start)="a = true"></div>`, standalone: false, }) class Cmp { a = false; } TestBed.configureTestingModule({declarations: [Cmp]}); expect(() => TestBed.createComponent(Cmp)).toThrowError( syntheticPropError('@myAnimation.start', 'listener'), ); }); }); describe('when modules are present, but animations are missing', () => { it('should throw when using an @prop property, BrowserAnimationModule is imported, but there is no animation rule', () => { @Component({ template: `<div [@myAnimation]="true"></div>`, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp], imports: [BrowserAnimationsModule]}); const comp = TestBed.createComponent(Cmp); expect(() => comp.detectChanges()).toThrowError( syntheticPropError('@myAnimation', 'property'), ); }); it('should throw when using an @prop listener, BrowserAnimationModule is imported, but there is no animation rule', () => { @Component({ template: `<div (@myAnimation.start)="true"></div>`, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp], imports: [BrowserAnimationsModule]}); expect(() => TestBed.createComponent(Cmp)).toThrowError( syntheticPropError('@myAnimation.start', 'listener'), ); }); }); }); describe('non-animatable css props', () => { functio
009899
/** * @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 { animate, animateChild, AnimationPlayer, AUTO_STYLE, group, query, sequence, stagger, state, style, transition, trigger, ɵAnimationGroupPlayer as AnimationGroupPlayer, } from '@angular/animations'; import { AnimationDriver, ɵAnimationEngine, ɵnormalizeKeyframes as normalizeKeyframes, } from '@angular/animations/browser'; import {TransitionAnimationPlayer} from '@angular/animations/browser/src/render/transition_animation_engine'; import {ENTER_CLASSNAME, LEAVE_CLASSNAME} from '@angular/animations/browser/src/util'; import {MockAnimationDriver, MockAnimationPlayer} from '@angular/animations/browser/testing'; import {CommonModule} from '@angular/common'; import {Component, HostBinding, ViewChild} from '@angular/core'; import {fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {HostListener} from '../../src/metadata/directives'; (function () {
009915
/** * @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 { animate, animateChild, group, query, sequence, style, transition, trigger, ɵAnimationGroupPlayer as AnimationGroupPlayer, } from '@angular/animations'; import {AnimationDriver, ɵAnimationEngine} from '@angular/animations/browser'; import {TransitionAnimationPlayer} from '@angular/animations/browser/src/render/transition_animation_engine'; import {MockAnimationDriver, MockAnimationPlayer} from '@angular/animations/browser/testing'; import {Component, HostBinding} from '@angular/core'; import {fakeAsync, flushMicrotasks, TestBed, tick} from '@angular/core/testing'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {ActivatedRoute, Router, RouterModule, RouterOutlet} from '@angular/router'; (function () { // these tests are only meant to be run within the DOM (for now) if (isNode) return; describe('Animation Router Tests', function () { function getLog(): MockAnimationPlayer[] { return MockAnimationDriver.log as MockAnimationPlayer[]; } function resetLog() { MockAnimationDriver.log = []; } beforeEach(() => { resetLog(); TestBed.configureTestingModule({ imports: [RouterModule.forRoot([]), BrowserAnimationsModule], providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}], }); }); it('should query the old and new routes via :leave and :enter', fakeAsync(() => { @Component({ animations: [ trigger('routerAnimations', [ transition('page1 => page2', [ query(':leave', animateChild()), query(':enter', animateChild()), ]), ]), ], template: ` <div [@routerAnimations]="prepareRouteAnimation(r)"> <router-outlet #r="outlet"></router-outlet> </div> `, standalone: false, }) class ContainerCmp { constructor(public router: Router) {} prepareRouteAnimation(r: RouterOutlet) { const animation = r.activatedRouteData['animation']; const value = animation ? animation['value'] : null; return value; } } @Component({ selector: 'page1', template: `page1`, animations: [ trigger('page1Animation', [ transition(':leave', [style({width: '200px'}), animate(1000, style({width: '0px'}))]), ]), ], standalone: false, }) class Page1Cmp { @HostBinding('@page1Animation') public doAnimate = true; } @Component({ selector: 'page2', template: `page2`, animations: [ trigger('page2Animation', [ transition(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), ], standalone: false, }) class Page2Cmp { @HostBinding('@page2Animation') public doAnimate = true; } TestBed.configureTestingModule({ declarations: [Page1Cmp, Page2Cmp, ContainerCmp], imports: [ RouterModule.forRoot([ {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')}, ]), ], }); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ContainerCmp); const cmp = fixture.componentInstance; cmp.router.initialNavigation(); tick(); fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page1'); tick(); fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page2'); tick(); fixture.detectChanges(); engine.flush(); const player = engine.players[0]!; const groupPlayer = ( player as TransitionAnimationPlayer ).getRealPlayer() as AnimationGroupPlayer; const players = groupPlayer.players as MockAnimationPlayer[]; expect(players.length).toEqual(2); const [p1, p2] = players; expect(p1.duration).toEqual(1000); expect(p1.keyframes).toEqual([ new Map<string, string | number>([ ['offset', 0], ['width', '200px'], ]), new Map<string, string | number>([ ['offset', 1], ['width', '0px'], ]), ]); expect(p2.duration).toEqual(2000); expect(p2.keyframes).toEqual([ new Map<string, string | number>([ ['offset', 0], ['opacity', '0'], ]), new Map<string, string | number>([ ['offset', 0.5], ['opacity', '0'], ]), new Map<string, string | number>([ ['offset', 1], ['opacity', '1'], ]), ]); })); it('should allow inner enter animations to be emulated within a routed item', fakeAsync(() => { @Component({ animations: [ trigger('routerAnimations', [ transition('page1 => page2', [query(':enter', animateChild())]), ]), ], template: ` <div [@routerAnimations]="prepareRouteAnimation(r)"> <router-outlet #r="outlet"></router-outlet> </div> `, standalone: false, }) class ContainerCmp { constructor(public router: Router) {} prepareRouteAnimation(r: RouterOutlet) { const animation = r.activatedRouteData['animation']; const value = animation ? animation['value'] : null; return value; } } @Component({ selector: 'page1', template: `page1`, animations: [], standalone: false, }) class Page1Cmp {} @Component({ selector: 'page2', template: ` <h1>Page 2</h1> <div *ngIf="exp" class="if-one" @ifAnimation></div> <div *ngIf="exp" class="if-two" @ifAnimation></div> `, animations: [ trigger('page2Animation', [ transition(':enter', [ query('.if-one', animateChild()), query('.if-two', animateChild()), ]), ]), trigger('ifAnimation', [ transition(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), ], standalone: false, }) class Page2Cmp { @HostBinding('@page2Animation') public doAnimate = true; public exp = true; } TestBed.configureTestingModule({ declarations: [Page1Cmp, Page2Cmp, ContainerCmp], imports: [ RouterModule.forRoot([ {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')}, ]), ], }); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ContainerCmp); const cmp = fixture.componentInstance; cmp.router.initialNavigation(); tick(); fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page1'); tick(); fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page2'); tick(); fixture.detectChanges(); engine.flush(); const player = engine.players[0]!; const groupPlayer = ( player as TransitionAnimationPlayer ).getRealPlayer() as AnimationGroupPlayer; const players = groupPlayer.players as MockAnimationPlayer[]; expect(players.length).toEqual(2); const [p1, p2] = players; expect(p1.keyframes).toEqual([ new Map<string, string | number>([ ['offset', 0], ['opacity', '0'], ]), new Map<string, string | number>([ ['offset', 1], ['opacity', '1'], ]), ]); expect(p2.keyframes).toEqual([ new Map<string, string | number>([ ['offset', 0], ['opacity', '0'], ]), new Map<string, string | number>([ ['offset', 0.5], ['opacity', '0'], ]), new Map<string, string | number>([ ['offset', 1], ['opacity', '1'], ]), ]); }));
009917
/** * @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 {animate, query, state, style, transition, trigger} from '@angular/animations'; import { AnimationDriver, ɵAnimationEngine, ɵWebAnimationsDriver, ɵWebAnimationsPlayer, } from '@angular/animations/browser'; import {TransitionAnimationPlayer} from '@angular/animations/browser/src/render/transition_animation_engine'; import {AnimationGroupPlayer} from '@angular/animations/src/players/animation_group_player'; import {Component, ViewChild} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; (
009928
/** * @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 {computed, isSignal, model, WritableSignal} from '@angular/core'; import {TestBed} from '@angular/core/testing'; describe('model signal', () => { it('should work with computed expressions', () => { const signal = TestBed.runInInjectionContext(() => model(0)); let computedCount = 0; const derived = computed(() => (computedCount++, signal() + 1000)); expect(derived()).toBe(1000); expect(computedCount).toBe(1); signal.set(1); expect(computedCount).toBe(1); expect(derived()).toBe(1001); expect(computedCount).toBe(2); }); it('should allow updates based on the previous value', () => { const signal = TestBed.runInInjectionContext(() => model(2)); signal.update((value) => value * 3); expect(signal()).toBe(6); signal.update((value) => value * 3); expect(signal()).toBe(18); }); it('should return readonly signal', () => { const signal = TestBed.runInInjectionContext(() => model(2)); const readOnly = signal.asReadonly(); expect(isSignal(readOnly)).toBeTrue(); expect(readOnly()).toBe(2); expect((readOnly as WritableSignal<unknown>).set).toBeUndefined(); expect((readOnly as WritableSignal<unknown>).update).toBeUndefined(); }); it('should emit when the value changes', () => { const signal = TestBed.runInInjectionContext(() => model(1)); const values: number[] = []; signal.subscribe((value) => values.push(value)); signal.set(2); expect(values).toEqual([2]); signal.update((previous) => previous * 2); expect(values).toEqual([2, 4]); signal.set(5); expect(values).toEqual([2, 4, 5]); }); it('should error when subscribing to a destroyed model', () => { const signal = TestBed.runInInjectionContext(() => model(1)); const values: number[] = []; signal.subscribe((value) => values.push(value)); TestBed.resetTestingModule(); expect(() => signal.subscribe(() => {})).toThrowError( /Unexpected subscription to destroyed `OutputRef`/, ); }); it('should stop emitting after unsubscribing', () => { const signal = TestBed.runInInjectionContext(() => model(0)); const values: number[] = []; const subscription = signal.subscribe((value) => values.push(value)); signal.set(1); expect(values).toEqual([1]); subscription.unsubscribe(); signal.set(2); expect(values).toEqual([1]); }); it('should not emit if the value does not change', () => { const signal = TestBed.runInInjectionContext(() => model(0)); const values: number[] = []; signal.subscribe((value) => values.push(value)); signal.set(1); expect(values).toEqual([1]); signal.set(1); expect(values).toEqual([1]); signal.update((previous) => previous * 2); expect(values).toEqual([1, 2]); signal.update((previous) => previous * 1); expect(values).toEqual([1, 2]); }); it('should not share subscriptions between models', () => { let emitCount = 0; const signal1 = TestBed.runInInjectionContext(() => model(0)); const signal2 = TestBed.runInInjectionContext(() => model(0)); const callback = () => emitCount++; const subscription1 = signal1.subscribe(callback); const subscription2 = signal2.subscribe(callback); signal1.set(1); expect(emitCount).toBe(1); signal2.set(1); expect(emitCount).toBe(2); subscription1.unsubscribe(); signal2.set(2); expect(emitCount).toBe(3); subscription2.unsubscribe(); signal2.set(3); expect(emitCount).toBe(3); }); it('should throw if there is no value for required model', () => { const signal = TestBed.runInInjectionContext(() => model.required()); expect(() => signal()).toThrowError(/Model is required but no value is available yet\./); signal.set(1); expect(signal()).toBe(1); }); it('should throw if a `computed` depends on an uninitialized required model', () => { const signal = TestBed.runInInjectionContext(() => model.required<number>()); const expr = computed(() => signal() + 1000); expect(() => expr()).toThrowError(/Model is required but no value is available yet\./); signal.set(1); expect(expr()).toBe(1001); }); it('should have a toString implementation', () => { const signal = TestBed.runInInjectionContext(() => model(0)); expect(signal + '').toBe('[Model Signal: 0]'); }); });
009931
report unknown property bindings on ng-content', () => { @Component({ template: `<ng-content *unknownProp="123"></ng-content>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(spy.calls.mostRecent()?.args[0]).toMatch( /Can't bind to 'unknownProp' since it isn't a known property of 'ng-content' \(used in the 'App' component template\)/, ); }); it('should throw an error on unknown property bindings on ng-content when errorOnUnknownProperties is enabled', () => { @Component({ template: `<ng-content *unknownProp="123"></ng-content>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App], errorOnUnknownProperties: true}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).toThrowError( /NG0303: Can't bind to 'unknownProp' since it isn't a known property of 'ng-content' \(used in the 'App' component template\)/g, ); }); it('should report unknown property bindings on ng-container', () => { @Component({ template: `<ng-container [unknown-prop]="123"></ng-container>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(spy.calls.mostRecent()?.args[0]).toMatch( /Can't bind to 'unknown-prop' since it isn't a known property of 'ng-container' \(used in the 'App' component template\)/, ); }); it('should throw error on unknown property bindings on ng-container when errorOnUnknownProperties is enabled', () => { @Component({ template: `<ng-container [unknown-prop]="123"></ng-container>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App], errorOnUnknownProperties: true}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).toThrowError( /NG0303: Can't bind to 'unknown-prop' since it isn't a known property of 'ng-container' \(used in the 'App' component template\)/g, ); }); it('should log an error on unknown props and include a note on Web Components', () => { @Component({ selector: 'may-be-web-component', template: `...`, standalone: false, }) class MaybeWebComp {} @Component({ selector: 'my-comp', template: `<may-be-web-component [unknownProp]="condition"></may-be-web-component>`, standalone: false, }) class MyComp { condition = true; } @NgModule({ declarations: [MyComp, MaybeWebComp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const errorMessage = spy.calls.mostRecent().args[0]; // Split the error message into chunks, so it's easier to debug if needed. const lines = [ `NG0303: Can't bind to 'unknownProp' since it isn't a known property of 'may-be-web-component' \\(used in the 'MyComp' component template\\).`, `1. If 'may-be-web-component' is an Angular component and it has the 'unknownProp' input, then verify that it is a part of an @NgModule where this component is declared.`, `2. If 'may-be-web-component' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`, `3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`, ]; lines.forEach((line) => expect(errorMessage).toMatch(line)); }); KNOWN_CONTROL_FLOW_DIRECTIVES.forEach((correspondingImport, directive) => { it( `should produce a warning when the '${directive}' directive ` + `is used in a template, but not imported in corresponding NgModule`, () => { @Component({ template: `<div *${directive}="expr"></div>`, standalone: false, }) class App { expr = true; } @NgModule({ declarations: [App], }) class Module {} TestBed.configureTestingModule({imports: [Module]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const errorMessage = spy.calls.mostRecent()?.args[0]; // Split the error message into chunks, so it's easier to debug if needed. const lines = [ `NG0303: Can't bind to '${directive}' since it isn't a known property of 'div' \\(used in the 'App' component template\\).`, `If the '${directive}' is an Angular control flow directive, please make sure ` + `that either the '${correspondingImport}' directive or the 'CommonModule' is a part of an @NgModule where this component is declared.`, ]; lines.forEach((line) => expect(errorMessage).toMatch(line)); }, ); it( `should produce a warning when the '${directive}' directive ` + `is used in a template, but not imported in a standalone component`, () => { @Component({ standalone: true, template: `<div *${directive}="expr"></div>`, }) class App { expr = true; } const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const errorMessage = spy.calls.mostRecent()?.args[0]; // Split the error message into chunks, so it's easier to debug if needed. const lines = [ `NG0303: Can't bind to '${directive}' since it isn't a known property of 'div' \\(used in the 'App' component template\\).`, `If the '${directive}' is an Angular control flow directive, please make sure ` + `that either the '${correspondingImport}' directive or the 'CommonModule' is included in the '@Component.imports' of this component.`, ]; lines.forEach((line) => expect(errorMessage).toMatch(line)); }, ); }); descr
009934
/** * @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 {CommonModule} from '@angular/common'; import { ChangeDetectorRef, Component, Directive, EmbeddedViewRef, Injectable, Injector, Input, TemplateRef, ViewChild, ViewContainerRef, ViewRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; describe('view insertion', () => { describe('of a simple template', () => { it('should insert into an empty container, at the front, in the middle, and at the end', () => { let _counter = 0; @Component({ selector: 'increment-comp', template: `<span>created{{counter}}</span>`, standalone: false, }) class IncrementComp { counter = _counter++; } @Component({ template: ` <ng-template #simple><increment-comp></increment-comp></ng-template> <div #container></div> `, standalone: false, }) class App { @ViewChild('container', {read: ViewContainerRef, static: true}) container: ViewContainerRef = null!; @ViewChild('simple', {read: TemplateRef, static: true}) simple: TemplateRef<any> = null!; view0: EmbeddedViewRef<any> = null!; view1: EmbeddedViewRef<any> = null!; view2: EmbeddedViewRef<any> = null!; view3: EmbeddedViewRef<any> = null!; constructor(public changeDetector: ChangeDetectorRef) {} ngAfterViewInit() { // insert at the front this.view1 = this.container.createEmbeddedView(this.simple); // "created0" // insert at the front again this.view0 = this.container.createEmbeddedView(this.simple, {}, 0); // "created1" // insert at the end this.view3 = this.container.createEmbeddedView(this.simple); // "created2" // insert in the middle this.view2 = this.container.createEmbeddedView(this.simple, {}, 2); // "created3" // We need to run change detection here to avoid // ExpressionChangedAfterItHasBeenCheckedError because of the value updating in // increment-comp this.changeDetector.detectChanges(); } } TestBed.configureTestingModule({ declarations: [App, IncrementComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const app = fixture.componentInstance; expect(app.container.indexOf(app.view0)).toBe(0); expect(app.container.indexOf(app.view1)).toBe(1); expect(app.container.indexOf(app.view2)).toBe(2); expect(app.container.indexOf(app.view3)).toBe(3); // The text in each component differs based on *when* it was created. expect(fixture.nativeElement.textContent).toBe('created1created0created3created2'); }); }); describe('of an empty template', () => { it('should insert into an empty container, at the front, in the middle, and at the end', () => { @Component({ template: ` <ng-template #empty></ng-template> <div #container></div> `, standalone: false, }) class App { @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef = null!; @ViewChild('empty', {read: TemplateRef}) empty: TemplateRef<any> = null!; view0: EmbeddedViewRef<any> = null!; view1: EmbeddedViewRef<any> = null!; view2: EmbeddedViewRef<any> = null!; view3: EmbeddedViewRef<any> = null!; ngAfterViewInit() { // insert at the front this.view1 = this.container.createEmbeddedView(this.empty); // insert at the front again this.view0 = this.container.createEmbeddedView(this.empty, {}, 0); // insert at the end this.view3 = this.container.createEmbeddedView(this.empty); // insert in the middle this.view2 = this.container.createEmbeddedView(this.empty, {}, 2); } } TestBed.configureTestingModule({ declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const app = fixture.componentInstance; expect(app.container.indexOf(app.view0)).toBe(0); expect(app.container.indexOf(app.view1)).toBe(1); expect(app.container.indexOf(app.view2)).toBe(2); expect(app.container.indexOf(app.view3)).toBe(3); }); }); describe('of an ng-content projection', () => { it('should insert into an empty container, at the front, in the middle, and at the end', () => { @Component({ selector: 'comp', template: ` <ng-template #projection><ng-content></ng-content></ng-template> <div #container></div> `, standalone: false, }) class Comp { @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef = null!; @ViewChild('projection', {read: TemplateRef}) projection: TemplateRef<any> = null!; view0: EmbeddedViewRef<any> = null!; view1: EmbeddedViewRef<any> = null!; view2: EmbeddedViewRef<any> = null!; view3: EmbeddedViewRef<any> = null!; ngAfterViewInit() { // insert at the front this.view1 = this.container.createEmbeddedView(this.projection); // insert at the front again this.view0 = this.container.createEmbeddedView(this.projection, {}, 0); // insert at the end this.view3 = this.container.createEmbeddedView(this.projection); // insert in the middle this.view2 = this.container.createEmbeddedView(this.projection, {}, 2); } } @Component({ template: ` <comp>test</comp> `, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const comp = fixture.debugElement.query(By.directive(Comp)).injector.get(Comp); expect(comp.container.indexOf(comp.view0)).toBe(0); expect(comp.container.indexOf(comp.view1)).toBe(1); expect(comp.container.indexOf(comp.view2)).toBe(2); expect(comp.container.indexOf(comp.view3)).toBe(3); // Both ViewEngine and Ivy only honor one of the inserted ng-content components, even though // all are inserted. expect(fixture.nativeElement.textContent).toBe('test'); }); }); describe('of another container like ngIf', () => { it('should insert into an empty container, at the front, in the middle, and at the end', () => { @Component({ template: ` <ng-template #subContainer><div class="dynamic" *ngIf="true">test</div></ng-template> <div #container></div> `, standalone: false, }) class App { @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef = null!; @ViewChild('subContainer', {read: TemplateRef}) subContainer: TemplateRef<any> = null!; view0: EmbeddedViewRef<any> = null!; view1: EmbeddedViewRef<any> = null!; view2: EmbeddedViewRef<any> = null!; view3: EmbeddedViewRef<any> = null!; constructor(public changeDetectorRef: ChangeDetectorRef) {} ngAfterViewInit() { // insert at the front this.view1 = this.container.createEmbeddedView(this.subContainer, null, 0); // insert at the front again this.view0 = this.container.createEmbeddedView(this.subContainer, null, 0); // insert at the end this.view3 = this.container.createEmbeddedView(this.subContainer, null, 2); // insert in the middle this.view2 = this.container.createEmbeddedView(this.subContainer, null, 2); // We need to run change detection here to avoid // ExpressionChangedAfterItHasBeenCheckedError because of the value getting passed to ngIf // in the template. this.changeDetectorRef.detectChanges(); } } TestBed.configureTestingModule({ declarations: [App], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const app = fixture.componentInstance; expect(app.container.indexOf(app.view0)).toBe(0); expect(app.container.indexOf(app.view1)).toBe(1); expect(app.container.indexOf(app.view2)).toBe(2); expect(app.container.indexOf(app.view3)).toBe(3); expect(fixture.debugElement.queryAll(By.css('div.dynamic')).length).toBe(4); }); });
009936
describe('before component view', () => { @Directive({ selector: '[viewInserting]', exportAs: 'vi', standalone: false, }) class ViewInsertingDir { constructor(private _vcRef: ViewContainerRef) {} insert(beforeView: ViewRef, insertTpl: TemplateRef<{}>) { this._vcRef.insert(beforeView, 0); this._vcRef.createEmbeddedView(insertTpl, {}, 0); } } @Component({ selector: 'dynamic-cmpt', template: '|before', standalone: false, }) class DynamicComponent {} it('should insert in front a dynamic component view', () => { @Component({ selector: 'test-cmpt', template: ` <ng-template #insert>insert</ng-template> <div><ng-template #vi="vi" viewInserting></ng-template></div> `, standalone: false, }) class TestCmpt { @ViewChild('insert', {static: true}) insertTpl!: TemplateRef<{}>; @ViewChild('vi', {static: true}) viewInsertingDir!: ViewInsertingDir; constructor( private _vcr: ViewContainerRef, private _injector: Injector, ) {} insert() { // create a dynamic component view to act as an "insert before" view const beforeView = this._vcr.createComponent(DynamicComponent, { injector: this._injector, }).hostView; // change-detect the "before view" to create all child views beforeView.detectChanges(); this.viewInsertingDir.insert(beforeView, this.insertTpl); } } TestBed.configureTestingModule({ declarations: [TestCmpt, ViewInsertingDir, DynamicComponent], }); const fixture = TestBed.createComponent(TestCmpt); fixture.detectChanges(); fixture.componentInstance.insert(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('insert|before'); }); }); }); describe('non-regression', () => { // https://github.com/angular/angular/issues/31971 it('should insert component views into ViewContainerRef injected by querying <ng-container>', () => { @Component({ selector: 'dynamic-cmpt', template: 'dynamic', standalone: false, }) class DynamicComponent {} @Component({ selector: 'app-root', template: ` <div>start|</div> <ng-container #container></ng-container> <div>|end</div> <div (click)="click()" >|click</div> `, standalone: false, }) class AppComponent { @ViewChild('container', {read: ViewContainerRef, static: true}) vcr!: ViewContainerRef; click() { this.vcr.createComponent(DynamicComponent); } } TestBed.configureTestingModule({ declarations: [AppComponent, DynamicComponent], }); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('start||end|click'); fixture.componentInstance.click(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('start|dynamic|end|click'); }); // https://github.com/angular/angular/issues/33679 it('should insert embedded views into ViewContainerRef injected by querying <ng-container>', () => { @Component({ selector: 'app-root', template: ` <div>container start|</div> <ng-container #container></ng-container> <div>|container end</div> <ng-template #template >test</ng-template> <div (click)="click()" >|click</div> `, standalone: false, }) class AppComponent { @ViewChild('container', {read: ViewContainerRef, static: true}) vcr!: ViewContainerRef; @ViewChild('template', {read: TemplateRef, static: true}) template!: TemplateRef<any>; click() { this.vcr.createEmbeddedView(this.template, undefined, 0); } } TestBed.configureTestingModule({ declarations: [AppComponent], }); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('container start||container end|click'); fixture.componentInstance.click(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('container start|test|container end|click'); }); it('should properly insert before views in a ViewContainerRef injected on ng-container', () => { @Component({ selector: 'app-root', template: ` <ng-template #parameterListItem let-parameter="parameter"> {{parameter}} </ng-template> <ng-container *ngFor="let parameter of items;" [ngTemplateOutlet]="parameterListItem" [ngTemplateOutletContext]="{parameter:parameter}"> </ng-container> `, standalone: false, }) class AppComponent { items = [1]; } TestBed.configureTestingModule({ declarations: [AppComponent], imports: [CommonModule], }); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toContain('1'); fixture.componentInstance.items = [2, 1]; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toContain('2 1'); }); });
009938
/** * @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 {DOCUMENT, NgIf} from '@angular/common'; import { ApplicationRef, Component, ComponentRef, createComponent, createEnvironmentInjector, Directive, ElementRef, EmbeddedViewRef, EnvironmentInjector, forwardRef, inject, Injectable, InjectionToken, Injector, input, Input, NgModule, OnDestroy, reflectComponentType, Renderer2, Type, ViewChild, ViewContainerRef, ViewEncapsulation, ɵsetClassDebugInfo, ɵsetDocument, ɵɵdefineComponent, } from '@angular/core'; import {stringifyForError} from '@angular/core/src/render3/util/stringify_utils'; import {TestBed} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {global} from '../../src/util/global'; describe('component', () => { describe('view destruction', () => { it('should invoke onDestroy only once when a component is registered as a provider', () => { const testToken = new InjectionToken<ParentWithOnDestroy>('testToken'); let destroyCalls = 0; @Component({ selector: 'comp-with-on-destroy', template: '', providers: [{provide: testToken, useExisting: ParentWithOnDestroy}], standalone: false, }) class ParentWithOnDestroy { ngOnDestroy() { destroyCalls++; } } @Component({ selector: 'child', template: '', standalone: false, }) class ChildComponent { // We need to inject the parent so the provider is instantiated. constructor(_parent: ParentWithOnDestroy) {} } @Component({ template: ` <comp-with-on-destroy> <child></child> </comp-with-on-destroy> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, ParentWithOnDestroy, ChildComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(destroyCalls).toBe(1, 'Expected `ngOnDestroy` to only be called once.'); }); }); it('should be able to dynamically insert a component into a view container at the root of a component', () => { @Component({ template: 'hello', standalone: false, }) class HelloComponent {} @Component({ selector: 'wrapper', template: '<ng-content></ng-content>', standalone: false, }) class Wrapper {} @Component({ template: ` <wrapper> <div #insertionPoint></div> </wrapper> `, standalone: false, }) class App { @ViewChild('insertionPoint', {read: ViewContainerRef}) viewContainerRef!: ViewContainerRef; } TestBed.configureTestingModule({declarations: [App, Wrapper, HelloComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const instance = fixture.componentInstance; instance.viewContainerRef.createComponent(HelloComponent); expect(fixture.nativeElement.textContent.trim()).toBe('hello'); }); it('should not throw when calling `detectChanges` on the ChangeDetectorRef of a destroyed view', () => { @Component({ template: 'hello', standalone: false, }) class HelloComponent {} @Component({ template: `<div #insertionPoint></div>`, standalone: false, }) class App { @ViewChild('insertionPoint', {read: ViewContainerRef}) viewContainerRef!: ViewContainerRef; } TestBed.configureTestingModule({declarations: [App, HelloComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const componentRef = fixture.componentInstance.viewContainerRef.createComponent(HelloComponent); fixture.detectChanges(); expect(() => { componentRef.destroy(); componentRef.changeDetectorRef.detectChanges(); }).not.toThrow(); }); // TODO: add tests with Native once tests run in real browser (domino doesn't support shadow root) describe('encapsulation', () => { @Component({ selector: 'wrapper', encapsulation: ViewEncapsulation.None, template: `<encapsulated></encapsulated>`, standalone: false, }) class WrapperComponent {} @Component({ selector: 'encapsulated', encapsulation: ViewEncapsulation.Emulated, // styles must be non-empty to trigger `ViewEncapsulation.Emulated` styles: `:host {display: block}`, template: `foo<leaf></leaf>`, standalone: false, }) class EncapsulatedComponent {} @Component({ selector: 'leaf', encapsulation: ViewEncapsulation.None, template: `<span>bar</span>`, standalone: false, }) class LeafComponent {} beforeEach(() => { TestBed.configureTestingModule({ declarations: [WrapperComponent, EncapsulatedComponent, LeafComponent], }); }); it('should encapsulate children, but not host nor grand children', () => { const fixture = TestBed.createComponent(WrapperComponent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toMatch( /<encapsulated _nghost-[a-z\-]+(\d+)="">foo<leaf _ngcontent-[a-z\-]+\1=""><span>bar<\/span><\/leaf><\/encapsulated>/, ); }); it('should encapsulate host', () => { const fixture = TestBed.createComponent(EncapsulatedComponent); fixture.detectChanges(); const html = fixture.nativeElement.outerHTML; const match = html.match(/_nghost-([a-z\-]+\d+)/); expect(match).toBeDefined(); expect(html).toMatch(new RegExp(`<leaf _ngcontent-${match[1]}=""><span>bar</span></leaf>`)); }); it('should encapsulate host and children with different attributes', () => { // styles must be non-empty to trigger `ViewEncapsulation.Emulated` TestBed.overrideComponent(LeafComponent, { set: {encapsulation: ViewEncapsulation.Emulated, styles: [`span {color:red}`]}, }); const fixture = TestBed.createComponent(EncapsulatedComponent); fixture.detectChanges(); const html = fixture.nativeElement.outerHTML; const match = html.match(/_nghost-([a-z\-]+\d+)/g); expect(match).toBeDefined(); expect(match.length).toEqual(2); expect(html).toMatch( `<leaf ${match[0].replace('_nghost', '_ngcontent')}="" ${ match[1] }=""><span ${match[1].replace('_nghost', '_ngcontent')}="">bar</span></leaf></div>`, ); }); it('should be off for a component with no styles', () => { TestBed.overrideComponent(EncapsulatedComponent, { set: {styles: undefined}, }); const fixture = TestBed.createComponent(EncapsulatedComponent); fixture.detectChanges(); const html = fixture.nativeElement.outerHTML; expect(html).not.toContain('<encapsulated _nghost-'); expect(html).not.toContain('<leaf _ngcontent-'); }); it('should be off for a component with empty styles', () => { TestBed.overrideComponent(EncapsulatedComponent, { set: {styles: [` `, '', '/*comment*/']}, }); const fixture = TestBed.createComponent(EncapsulatedComponent); fixture.detectChanges(); const html = fixture.nativeElement.outerHTML; expect(html).not.toContain('<encapsulated _nghost-'); expect(html).not.toContain('<leaf _ngcontent-'); }); }); describe('view destruction', () => { it('should invoke onDestroy when directly destroying a root view', () => { let wasOnDestroyCalled = false; @Component({ selector: 'comp-with-destroy', template: ``, standalone: false, }) class ComponentWithOnDestroy implements OnDestroy { ngOnDestroy() { wasOnDestroyCalled = true; } } // This test asserts that the view tree is set up correctly based on the knowledge that this // tree is used during view destruction. If the child view is not correctly attached as a // child of the root view, then the onDestroy hook on the child view will never be called // when the view tree is torn down following the destruction of that root view. @Component({ selector: `test-app`, template: `<comp-with-destroy></comp-with-destroy>`, standalone: false, }) class TestApp {} TestBed.configureTestingModule({declarations: [ComponentWithOnDestroy, TestApp]}); const fixture = TestBed.createComponent(TestApp); fixture.detectChanges(); fixture.destroy(); expect(wasOnDestroyCalled).toBe( true, 'Expected component onDestroy method to be called when its parent view is destroyed', ); }); });
009953
it('should handle nullish coalescing inside templates', () => { @Component({ template: ` <span [title]="'Your last name is ' + (lastName ?? lastNameFallback ?? 'unknown')"> Hello, {{ firstName ?? 'Frodo' }}! You are a Balrog: {{ falsyValue ?? true }} </span> `, standalone: false, }) class App { firstName: string | null = null; lastName: string | null = null; lastNameFallback = 'Baggins'; falsyValue = false; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const content = fixture.nativeElement.innerHTML; expect(content).toContain('Hello, Frodo!'); expect(content).toContain('You are a Balrog: false'); expect(content).toContain(`<span title="Your last name is Baggins">`); }); it('should handle safe keyed reads inside templates', () => { @Component({ template: ` <span [title]="'Your last name is ' + (unknownNames?.[0] || 'unknown')"> Hello, {{ knownNames?.[0]?.[1] }}! You are a Balrog: {{ species?.[0]?.[1]?.[2]?.[3]?.[4]?.[5] || 'unknown' }} You are an Elf: {{ speciesMap?.[keys?.[0] ?? 'key'] }} You are an Orc: {{ speciesMap?.['key'] }} </span> `, standalone: false, }) class App { unknownNames: string[] | null = null; knownNames: string[][] = [['Frodo', 'Bilbo']]; species = null; keys = null; speciesMap: Record<string, string> = {key: 'unknown'}; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const content = fixture.nativeElement.innerHTML; expect(content).toContain('Hello, Bilbo!'); expect(content).toContain('You are a Balrog: unknown'); expect(content).toContain('You are an Elf: unknown'); expect(content).toContain(`<span title="Your last name is unknown">`); }); it('should handle safe keyed reads inside templates', () => { @Component({ template: ` <span [title]="'Your last name is ' + (person.getLastName?.() ?? 'unknown')"> Hello, {{ person.getName?.() }}! You are a Balrog: {{ person.getSpecies?.()?.()?.()?.()?.() || 'unknown' }} </span> `, standalone: false, }) class App { person: { getName: () => string; getLastName?: () => string; getSpecies?: () => () => () => () => () => string; } = {getName: () => 'Bilbo'}; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const content = fixture.nativeElement.innerHTML; expect(content).toContain('Hello, Bilbo!'); expect(content).toContain('You are a Balrog: unknown'); expect(content).toContain(`<span title="Your last name is unknown">`); }); it('should not invoke safe calls more times than plain calls', () => { const returnValue = () => () => () => () => 'hi'; let plainCalls = 0; let safeCalls = 0; @Component({ template: `{{ safe?.()?.()?.()?.()?.() }} {{ plain()()()()() }}`, standalone: false, }) class App { plain() { plainCalls++; return returnValue; } safe() { safeCalls++; return returnValue; } } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(safeCalls).toBeGreaterThan(0); expect(safeCalls).toBe(plainCalls); }); it('should handle nullish coalescing inside host bindings', () => { const logs: string[] = []; @Directive({ selector: '[some-dir]', host: { '[attr.first-name]': `'Hello, ' + (firstName ?? 'Frodo') + '!'`, '(click)': `logLastName(lastName ?? lastNameFallback ?? 'unknown')`, }, standalone: false, }) class Dir { firstName: string | null = null; lastName: string | null = null; lastNameFallback = 'Baggins'; logLastName(name: string) { logs.push(name); } } @Component({ template: `<button some-dir>Click me</button>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); button.click(); fixture.detectChanges(); expect(button.getAttribute('first-name')).toBe('Hello, Frodo!'); expect(logs).toEqual(['Baggins']); }); it('should render SVG nodes placed inside ng-template', () => { @Component({ template: ` <svg> <ng-template [ngIf]="condition"> <text>Hello</text> </ng-template> </svg> `, standalone: false, }) class MyComp { condition = true; } TestBed.configureTestingModule({declarations: [MyComp], imports: [CommonModule]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toContain('<text>Hello</text>'); }); it('should handle shorthand property declarations in templates', () => { @Directive({ selector: '[my-dir]', standalone: false, }) class Dir { @Input('my-dir') value: any; } @Component({ template: `<div [my-dir]="{a, b: 2, someProp}"></div>`, standalone: false, }) class App { @ViewChild(Dir) directive!: Dir; a = 1; someProp = 3; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.directive.value).toEqual({a: 1, b: 2, someProp: 3}); }); it('should handle numeric separators in templates', () => { @Component({ template: 'Balance: ${{ 1_000_000 * multiplier }}', standalone: false, }) class App { multiplier = 5; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Balance: $5000000'); }); it('should handle calls to a safe access in templates', () => { @Component({ template: ` <span>Hello, {{ (person?.getName() || 'unknown') }}!</span> `, standalone: false, }) class App { person = null; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Hello, unknown!'); });
009968
describe('and declaration component is CheckAlways', () => { beforeEach(() => { fixture.componentInstance.showCheckAlwaysDeclare = true; fixture.componentInstance.showOnPushInsert = true; fixture.detectChanges(false); viewExecutionLog.length = 0; }); it('should set up the component under test correctly', () => { expect(viewExecutionLog.length).toEqual(0); expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(world) OnPushInsertComp(Hello) Hello world!', ); }); it('should CD at insertion point only', () => { declareComp.name = 'Angular'; fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(Angular) OnPushInsertComp(Hello) Hello Angular!', 'Expect transplanted LView to be CD because the declaration is CD.', ); onPushInsertComp.greeting = 'Hi'; fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(Angular) OnPushInsertComp(Hello) Hello Angular!', 'expect no change because it is on push.', ); onPushInsertComp.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(Angular) OnPushInsertComp(Hi) Hi Angular!', ); // Destroy insertion should also destroy declaration appComp.showOnPushInsert = false; fixture.detectChanges(false); expect(viewExecutionLog).toEqual([]); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual('DeclareComp(Angular)'); // Restore both appComp.showOnPushInsert = true; fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(Angular) OnPushInsertComp(Hello) Hello Angular!', ); // Destroy declaration, But we should still be able to see updates in insertion appComp.showCheckAlwaysDeclare = false; onPushInsertComp.greeting = 'Hello'; onPushInsertComp.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'OnPushInsertComp(Hello) Hello Angular!', ); }); it('is not checked if detectChanges is called in declaration component', () => { declareComp.name = 'Angular'; declareComp.changeDetector.detectChanges(); expect(viewExecutionLog).toEqual([]); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(Angular) OnPushInsertComp(Hello) Hello world!', ); }); it('is checked as part of CheckNoChanges pass', () => { fixture.detectChanges(true); expect(viewExecutionLog).toEqual([ 'Insert', null /* logName set to null afterViewChecked */, ]); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(world) OnPushInsertComp(Hello) Hello world!', ); }); }); describe('and declaration and insertion components are OnPush', () => { beforeEach(() => { fixture.componentInstance.showOnPushDeclare = true; fixture.componentInstance.showOnPushInsert = true; fixture.detectChanges(false); viewExecutionLog.length = 0; }); it('should set up component under test correctly', () => { expect(viewExecutionLog.length).toEqual(0); expect(trim(fixture.nativeElement.textContent)).toEqual( 'OnPushDeclareComp(world) OnPushInsertComp(Hello) Hello world!', ); }); it('should not check anything when no views are dirty', () => { fixture.detectChanges(false); expect(viewExecutionLog).toEqual([]); }); it('should CD at insertion point only', () => { onPushDeclareComp.name = 'Angular'; onPushInsertComp.greeting = 'Hi'; // mark declaration point dirty onPushDeclareComp.changeDetector.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'OnPushDeclareComp(Angular) OnPushInsertComp(Hello) Hello Angular!', ); // mark insertion point dirty onPushInsertComp.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'OnPushDeclareComp(Angular) OnPushInsertComp(Hi) Hi Angular!', ); // mark both insertion and declaration point dirty onPushInsertComp.changeDetectorRef.markForCheck(); onPushDeclareComp.changeDetector.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; }); it('is checked if detectChanges is called in declaration component', () => { onPushDeclareComp.name = 'Angular'; onPushDeclareComp.changeDetector.detectChanges(); expect(trim(fixture.nativeElement.textContent)).toEqual( 'OnPushDeclareComp(Angular) OnPushInsertComp(Hello) Hello world!', ); }); // TODO(FW-1774): blocked by https://github.com/angular/angular/pull/34443 xit('is checked as part of CheckNoChanges pass', () => { // mark declaration point dirty onPushDeclareComp.changeDetector.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual([ 'Insert', null /* logName set to null in afterViewChecked */, ]); viewExecutionLog.length = 0; // mark insertion point dirty onPushInsertComp.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert', null]); viewExecutionLog.length = 0; // mark both insertion and declaration point dirty onPushInsertComp.changeDetectorRef.markForCheck(); onPushDeclareComp.changeDetector.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert', null]); viewExecutionLog.length = 0; }); it('does not cause infinite change detection if transplanted view is dirty and destroyed before refresh', () => { // mark declaration point dirty onPushDeclareComp.changeDetector.markForCheck(); // detach insertion so the transplanted view doesn't get refreshed when CD runs onPushInsertComp.changeDetectorRef.detach(); // run CD, which will set the `RefreshView` flag on the transplanted view fixture.detectChanges(false); // reattach insertion so the DESCENDANT_VIEWS counters update onPushInsertComp.changeDetectorRef.reattach(); // make it so the insertion is destroyed before getting refreshed fixture.componentInstance.showOnPushInsert = false; // run CD again. If we didn't clear the flag/counters when destroying the view, this // would cause an infinite CD because the counters will be >1 but we will never reach a // view to refresh and decrement the counters. fixture.detectChanges(false); }); }); });
010001
describe('ngOnChanges', () => { it('should invoke ngOnChanges when an input is set on a host directive', () => { let firstDirChangeEvent: SimpleChanges | undefined; let secondDirChangeEvent: SimpleChanges | undefined; @Directive({standalone: true}) class FirstHostDir implements OnChanges { @Input() color?: string; ngOnChanges(changes: SimpleChanges) { firstDirChangeEvent = changes; } } @Directive({standalone: true}) class SecondHostDir implements OnChanges { @Input() color?: string; ngOnChanges(changes: SimpleChanges) { secondDirChangeEvent = changes; } } @Directive({ selector: '[dir]', hostDirectives: [ {directive: FirstHostDir, inputs: ['color']}, {directive: SecondHostDir, inputs: ['color']}, ], standalone: false, }) class Dir {} @Component({ template: '<button dir [color]="color"></button>', standalone: false, }) class App { color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(firstDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(firstDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: false, previousValue: 'red', currentValue: 'green', }), }), ); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: false, previousValue: 'red', currentValue: 'green', }), }), ); }); it('should invoke ngOnChanges when an aliased property is set on a host directive', () => { let firstDirChangeEvent: SimpleChanges | undefined; let secondDirChangeEvent: SimpleChanges | undefined; @Directive({standalone: true}) class FirstHostDir implements OnChanges { @Input('firstAlias') color?: string; ngOnChanges(changes: SimpleChanges) { firstDirChangeEvent = changes; } } @Directive({standalone: true}) class SecondHostDir implements OnChanges { @Input('secondAlias') color?: string; ngOnChanges(changes: SimpleChanges) { secondDirChangeEvent = changes; } } @Directive({ selector: '[dir]', hostDirectives: [ {directive: FirstHostDir, inputs: ['firstAlias: buttonColor']}, {directive: SecondHostDir, inputs: ['secondAlias: buttonColor']}, ], standalone: false, }) class Dir {} @Component({ template: '<button dir [buttonColor]="color"></button>', standalone: false, }) class App { color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(firstDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(firstDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: false, previousValue: 'red', currentValue: 'green', }), }), ); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: false, previousValue: 'red', currentValue: 'green', }), }), ); }); it('should only invoke ngOnChanges on the directives that have exposed an input', () => { let firstDirChangeEvent: SimpleChanges | undefined; let secondDirChangeEvent: SimpleChanges | undefined; @Directive({standalone: true}) class FirstHostDir implements OnChanges { @Input() color?: string; ngOnChanges(changes: SimpleChanges) { firstDirChangeEvent = changes; } } @Directive({standalone: true}) class SecondHostDir implements OnChanges { @Input() color?: string; ngOnChanges(changes: SimpleChanges) { secondDirChangeEvent = changes; } } @Directive({ selector: '[dir]', hostDirectives: [FirstHostDir, {directive: SecondHostDir, inputs: ['color']}], standalone: false, }) class Dir {} @Component({ template: '<button dir [color]="color"></button>', standalone: false, }) class App { color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(firstDirChangeEvent).toBe(undefined); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(firstDirChangeEvent).toBe(undefined); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: false, previousValue: 'red', currentValue: 'green', }), }), ); }); it('should invoke ngOnChanges when a static aliased host directive input is set', () => { let latestChangeEvent: SimpleChanges | undefined; @Directive({standalone: true}) class HostDir implements OnChanges { @Input('colorAlias') color?: string; ngOnChanges(changes: SimpleChanges) { latestChangeEvent = changes; } } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['colorAlias: buttonColor']}], standalone: false, }) class Dir {} @Component({ template: '<button dir buttonColor="red"></button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(latestChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); }); });
010008
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component, Directive} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; describe('@angular/common integration', () => { describe('NgForOf', () => { @Directive({ selector: '[dir]', standalone: false, }) class MyDirective {} @Component({ selector: 'app-child', template: '<div dir>comp text</div>', standalone: false, }) class ChildComponent {} @Component({ selector: 'app-root', template: '', standalone: false, }) class AppComponent { items: string[] = ['first', 'second']; } beforeEach(() => { TestBed.configureTestingModule({declarations: [AppComponent, ChildComponent, MyDirective]}); }); it('should update a loop', () => { TestBed.overrideTemplate( AppComponent, '<ul><li *ngFor="let item of items">{{item}}</li></ul>', ); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); let listItems = Array.from( (fixture.nativeElement as HTMLUListElement).querySelectorAll('li'), ); expect(listItems.map((li) => li.textContent)).toEqual(['first', 'second']); // change detection cycle, no model changes fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map((li) => li.textContent)).toEqual(['first', 'second']); // remove the last item const items = fixture.componentInstance.items; items.length = 1; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map((li) => li.textContent)).toEqual(['first']); // change an item items[0] = 'one'; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map((li) => li.textContent)).toEqual(['one']); // add an item items.push('two'); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map((li) => li.textContent)).toEqual(['one', 'two']); }); it('should support ngForOf context variables', () => { TestBed.overrideTemplate( AppComponent, '<ul><li *ngFor="let item of items; index as myIndex; count as myCount">{{myIndex}} of {{myCount}}: {{item}}</li></ul>', ); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); let listItems = Array.from( (fixture.nativeElement as HTMLUListElement).querySelectorAll('li'), ); expect(listItems.map((li) => li.textContent)).toEqual(['0 of 2: first', '1 of 2: second']); // add an item in the middle const items = fixture.componentInstance.items; items.splice(1, 0, 'middle'); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map((li) => li.textContent)).toEqual([ '0 of 3: first', '1 of 3: middle', '2 of 3: second', ]); }); it('should instantiate directives inside directives properly in an ngFor', () => { TestBed.overrideTemplate(AppComponent, '<app-child *ngFor="let item of items"></app-child>'); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const children = fixture.debugElement.queryAll(By.directive(ChildComponent)); // expect 2 children, each one with a directive expect(children.length).toBe(2); expect(children.map((child) => child.nativeElement.innerHTML)).toEqual([ '<div dir="">comp text</div>', '<div dir="">comp text</div>', ]); let directive = children[0].query(By.directive(MyDirective)); expect(directive).not.toBeNull(); directive = children[1].query(By.directive(MyDirective)); expect(directive).not.toBeNull(); // add an item const items = fixture.componentInstance.items; items.push('third'); fixture.detectChanges(); const childrenAfterAdd = fixture.debugElement.queryAll(By.directive(ChildComponent)); expect(childrenAfterAdd.length).toBe(3); expect(childrenAfterAdd.map((child) => child.nativeElement.innerHTML)).toEqual([ '<div dir="">comp text</div>', '<div dir="">comp text</div>', '<div dir="">comp text</div>', ]); directive = childrenAfterAdd[2].query(By.directive(MyDirective)); expect(directive).not.toBeNull(); }); it('should retain parent view listeners when the NgFor destroy views', () => { @Component({ selector: 'app-toggle', template: `<button (click)="toggle()">Toggle List</button> <ul> <li *ngFor="let item of items">{{item}}</li> </ul>`, standalone: false, }) class ToggleComponent { private _data: number[] = [1, 2, 3]; items: number[] = []; toggle() { if (this.items.length) { this.items = []; } else { this.items = this._data; } } } TestBed.configureTestingModule({declarations: [ToggleComponent]}); const fixture = TestBed.createComponent(ToggleComponent); fixture.detectChanges(); // no elements in the list let listItems = Array.from( (fixture.nativeElement as HTMLUListElement).querySelectorAll('li'), ); expect(listItems.length).toBe(0); // this will fill the list fixture.componentInstance.toggle(); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(3); expect(listItems.map((li) => li.textContent)).toEqual(['1', '2', '3']); // now toggle via the button const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); button.click(); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(0); // toggle again button.click(); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(3); });
010010
it('should support context for 9+ levels of embedded templates', () => { @Component({ selector: 'app-multi', template: `<div *ngFor="let item0 of items"> <span *ngFor="let item1 of item0.data"> <span *ngFor="let item2 of item1.data"> <span *ngFor="let item3 of item2.data"> <span *ngFor="let item4 of item3.data"> <span *ngFor="let item5 of item4.data"> <span *ngFor="let item6 of item5.data"> <span *ngFor="let item7 of item6.data"> <span *ngFor="let item8 of item7.data">{{ item8 }}.{{ item7.value }}.{{ item6.value }}.{{ item5.value }}.{{ item4.value }}.{{ item3.value }}.{{ item2.value }}.{{ item1.value }}.{{ item0.value }}.{{ value }}</span> </span> </span> </span> </span> </span> </span> </span> </div>`, standalone: false, }) class NineLevelsComponent { value = 'App'; items: any[] = [ { // item0 data: [ { // item1 data: [ { // item2 data: [ { // item3 data: [ { // item4 data: [ { // item5 data: [ { // item6 data: [ { // item7 data: [ '1', '2', // item8 ], value: 'h', }, ], value: 'g', }, ], value: 'f', }, ], value: 'e', }, ], value: 'd', }, ], value: 'c', }, ], value: 'b', }, ], value: 'a', }, { // item0 data: [ { // item1 data: [ { // item2 data: [ { // item3 data: [ { // item4 data: [ { // item5 data: [ { // item6 data: [ { // item7 data: [ '3', '4', // item8 ], value: 'H', }, ], value: 'G', }, ], value: 'F', }, ], value: 'E', }, ], value: 'D', }, ], value: 'C', }, ], value: 'B', }, ], value: 'A', }, ]; } TestBed.configureTestingModule({declarations: [NineLevelsComponent]}); const fixture = TestBed.createComponent(NineLevelsComponent); fixture.detectChanges(); const divItems = (fixture.nativeElement as HTMLElement).querySelectorAll('div'); expect(divItems.length).toBe(2); // 2 outer loops let spanItems = divItems[0].querySelectorAll( 'span > span > span > span > span > span > span > span', ); expect(spanItems.length).toBe(2); // 2 inner elements expect(spanItems[0].textContent).toBe('1.h.g.f.e.d.c.b.a.App'); expect(spanItems[1].textContent).toBe('2.h.g.f.e.d.c.b.a.App'); spanItems = divItems[1].querySelectorAll( 'span > span > span > span > span > span > span > span', ); expect(spanItems.length).toBe(2); // 2 inner elements expect(spanItems[0].textContent).toBe('3.H.G.F.E.D.C.B.A.App'); expect(spanItems[1].textContent).toBe('4.H.G.F.E.D.C.B.A.App'); }); }); describe('ngIf', () => { it('should support sibling ngIfs', () => { @Component({ selector: 'app-multi', template: ` <div *ngIf="showing">{{ valueOne }}</div> <div *ngIf="showing">{{ valueTwo }}</div> `, standalone: false, }) class SimpleConditionComponent { showing = true; valueOne = 'one'; valueTwo = 'two'; } TestBed.configureTestingModule({declarations: [SimpleConditionComponent]}); const fixture = TestBed.createComponent(SimpleConditionComponent); fixture.detectChanges(); const elements = fixture.nativeElement.querySelectorAll('div'); expect(elements.length).toBe(2); expect(elements[0].textContent).toBe('one'); expect(elements[1].textContent).toBe('two'); fixture.componentInstance.valueOne = '$$one$$'; fixture.componentInstance.valueTwo = '$$two$$'; fixture.detectChanges(); expect(elements[0].textContent).toBe('$$one$$'); expect(elements[1].textContent).toBe('$$two$$'); }); it('should handle nested ngIfs with no intermediate context vars', () => { @Component({ selector: 'app-multi', template: `<div *ngIf="showing"> <div *ngIf="outerShowing"> <div *ngIf="innerShowing">{{ name }}</div> </div> </div> `, standalone: false, }) class NestedConditionsComponent { showing = true; outerShowing = true; innerShowing = true; name = 'App name'; } TestBed.configureTestingModule({declarations: [NestedConditionsComponent]}); const fixture = TestBed.createComponent(NestedConditionsComponent); fixture.detectChanges(); const elements = fixture.nativeElement.querySelectorAll('div'); expect(elements.length).toBe(3); expect(elements[2].textContent).toBe('App name'); fixture.componentInstance.name = 'Other name'; fixture.detectChanges(); expect(elements[2].textContent).toBe('Other name'); }); }); describe('NgTemplateOutlet', () => { it('should create and remove embedded views', () => { @Component({ selector: 'app-multi', template: `<ng-template #tpl>from tpl</ng-template> <ng-template [ngTemplateOutlet]="showing ? tpl : null"></ng-template> `, standalone: false, }) class EmbeddedViewsComponent { showing = false; } TestBed.configureTestingModule({declarations: [EmbeddedViewsComponent]}); const fixture = TestBed.createComponent(EmbeddedViewsComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); fixture.componentInstance.showing = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('from tpl'); fixture.componentInstance.showing = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); }); it('should create and remove embedded views', () => { @Component({ selector: 'app-multi', template: `<ng-template #tpl>from tpl</ng-template> <ng-container [ngTemplateOutlet]="showing ? tpl : null"></ng-container> `, standalone: false, }) class NgContainerComponent { showing = false; } TestBed.configureTestingModule({declarations: [NgContainerComponent]}); const fixture = TestBed.createComponent(NgContainerComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); fixture.componentInstance.showing = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('from tpl'); fixture.componentInstance.showing = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); }); }); });
010038
/** * @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 {NgFor} from '@angular/common'; import { ChangeDetectorRef, Component, Directive, inject, Input, OnInit, Pipe, PipeTransform, TemplateRef, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; // Basic shared pipe used during testing. @Pipe({name: 'multiply', pure: true, standalone: true}) class MultiplyPipe implements PipeTransform { transform(value: number, amount: number) { return value * amount; } } describe('control flow - if', () => { it('should add and remove views based on conditions change', () => { @Component({standalone: true, template: '@if (show) {Something} @else {Nothing}'}) class TestComponent { show = true; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Something'); fixture.componentInstance.show = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Nothing'); }); it('should expose expression value in context', () => { @Component({ standalone: true, template: '@if (show; as alias) {{{show}} aliased to {{alias}}}', }) class TestComponent { show: any = true; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('true aliased to true'); fixture.componentInstance.show = 1; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1 aliased to 1'); }); it('should not expose the aliased expression to `if` and `else if` blocks', () => { @Component({ standalone: true, template: ` @if (value === 1; as alias) { If: {{value}} as {{alias || 'unavailable'}} } @else if (value === 2) { ElseIf: {{value}} as {{alias || 'unavailable'}} } @else { Else: {{value}} as {{alias || 'unavailable'}} } `, }) class TestComponent { value = 1; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('If: 1 as true'); fixture.componentInstance.value = 2; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('ElseIf: 2 as unavailable'); fixture.componentInstance.value = 3; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Else: 3 as unavailable'); }); it('should expose the context to nested conditional blocks', () => { @Component({ standalone: true, imports: [MultiplyPipe], template: ` @if (value | multiply:2; as root) { Root: {{value}}/{{root}} @if (value | multiply:3; as inner) { Inner: {{value}}/{{root}}/{{inner}} @if (value | multiply:4; as innermost) { Innermost: {{value}}/{{root}}/{{inner}}/{{innermost}} } } } `, }) class TestComponent { value = 1; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); let content = fixture.nativeElement.textContent; expect(content).toContain('Root: 1/2'); expect(content).toContain('Inner: 1/2/3'); expect(content).toContain('Innermost: 1/2/3/4'); fixture.componentInstance.value = 2; fixture.detectChanges(); content = fixture.nativeElement.textContent; expect(content).toContain('Root: 2/4'); expect(content).toContain('Inner: 2/4/6'); expect(content).toContain('Innermost: 2/4/6/8'); }); it('should expose the context to listeners inside nested conditional blocks', () => { let logs: any[] = []; @Component({ standalone: true, imports: [MultiplyPipe], template: ` @if (value | multiply:2; as root) { <button (click)="log(['Root', value, root])"></button> @if (value | multiply:3; as inner) { <button (click)="log(['Inner', value, root, inner])"></button> @if (value | multiply:4; as innermost) { <button (click)="log(['Innermost', value, root, inner, innermost])"></button> } } } `, }) class TestComponent { value = 1; log(value: any) { logs.push(value); } } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const buttons = Array.from<HTMLButtonElement>(fixture.nativeElement.querySelectorAll('button')); buttons.forEach((button) => button.click()); fixture.detectChanges(); expect(logs).toEqual([ ['Root', 1, 2], ['Inner', 1, 2, 3], ['Innermost', 1, 2, 3, 4], ]); logs = []; fixture.componentInstance.value = 2; fixture.detectChanges(); buttons.forEach((button) => button.click()); fixture.detectChanges(); expect(logs).toEqual([ ['Root', 2, 4], ['Inner', 2, 4, 6], ['Innermost', 2, 4, 6, 8], ]); }); it('should expose expression value passed through a pipe in context', () => { @Component({ standalone: true, template: '@if (value | multiply:2; as alias) {{{value}} aliased to {{alias}}}', imports: [MultiplyPipe], }) class TestComponent { value = 1; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1 aliased to 2'); fixture.componentInstance.value = 4; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('4 aliased to 8'); }); it('should destroy all views if there is nothing to display', () => { @Component({ standalone: true, template: '@if (show) {Something}', }) class TestComponent { show = true; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Something'); fixture.componentInstance.show = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe(''); }); it('should be able to use pipes in conditional expressions', () => { @Component({ standalone: true, imports: [MultiplyPipe], template: ` @if ((value | multiply:2) === 2) { one } @else if ((value | multiply:2) === 4) { two } @else { nothing } `, }) class TestComponent { value = 0; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('nothing'); fixture.componentInstance.value = 2; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('two'); fixture.componentInstance.value = 1; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('one'); }); it('should be able to use pipes injecting ChangeDetectorRef in if blocks', () => { @Pipe({name: 'test', standalone: true}) class TestPipe implements PipeTransform { changeDetectorRef = inject(ChangeDetectorRef); transform(value: any) { return value; } } @Component({ standalone: true, template: '@if (show | test) {Something}', imports: [TestPipe], }) class TestComponent { show = true; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Something'); }); it('should support a condition with the a typeof expression', () => { @Component({ standalone: true, template: ` @if (typeof value === 'string') { {{value.length}} } @else { {{value}} } `, }) class TestComponent { value: string | number = 'string'; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('6'); fixture.componentInstance.value = 42; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('42'); });
010041
/** * @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 {NgIf} from '@angular/common'; import { ChangeDetectorRef, Component, Directive, inject, Input, OnInit, Pipe, PipeTransform, TemplateRef, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; describe('control flow - for', () => { it('should create, remove and move views corresponding to items in a collection', () => { @Component({ template: '@for ((item of items); track item; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); fixture.componentInstance.items.pop(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|'); fixture.componentInstance.items.push(3); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); fixture.componentInstance.items[0] = 3; fixture.componentInstance.items[2] = 1; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('3(0)|2(1)|1(2)|'); }); it('should loop over iterators that can be iterated over only once', () => { @Component({ template: '@for ((item of items.keys()); track $index) {{{item}}|}', standalone: false, }) class TestComponent { items = new Map([ ['a', 1], ['b', 2], ['c', 3], ]); } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('a|b|c|'); }); it('should work correctly with trackBy index', () => { @Component({ template: '@for ((item of items); track idx; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); fixture.componentInstance.items.pop(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|'); fixture.componentInstance.items.push(3); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); fixture.componentInstance.items[0] = 3; fixture.componentInstance.items[2] = 1; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('3(0)|2(1)|1(2)|'); }); it('should support empty blocks', () => { @Component({ template: '@for ((item of items); track idx; let idx = $index) {|} @empty {Empty}', standalone: false, }) class TestComponent { items: number[] | null | undefined = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|||'); fixture.componentInstance.items = []; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Empty'); fixture.componentInstance.items = [0, 1]; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('||'); fixture.componentInstance.items = null; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Empty'); fixture.componentInstance.items = [0]; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|'); fixture.componentInstance.items = undefined; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Empty'); }); it('should be able to use pipes injecting ChangeDetectorRef in for loop blocks', () => { @Pipe({name: 'test', standalone: true}) class TestPipe implements PipeTransform { changeDetectorRef = inject(ChangeDetectorRef); transform(value: any) { return value; } } @Component({ template: '@for (item of items | test; track item;) {{{item}}|}', imports: [TestPipe], standalone: true, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1|2|3|'); }); it('should be able to access a directive property that is reassigned in a lifecycle hook', () => { @Directive({ selector: '[dir]', exportAs: 'dir', standalone: true, }) class Dir { data = [1]; ngDoCheck() { this.data = [2]; } } @Component({ selector: 'app-root', standalone: true, imports: [Dir], template: ` <div [dir] #dir="dir"></div> @for (x of dir.data; track $index) { {{x}} } `, }) class TestComponent {} const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('2'); }); it('should expose variables both under their real names and aliases', () => { @Component({ template: '@for ((item of items); track item; let idx = $index) {{{item}}({{$index}}/{{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0/0)|2(1/1)|3(2/2)|'); fixture.componentInstance.items.splice(1, 1); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0/0)|3(1/1)|'); });
010042
describe('trackBy', () => { it('should have access to the host context in the track function', () => { let offsetReads = 0; @Component({ template: '@for ((item of items); track $index + offset) {{{item}}}', standalone: false, }) class TestComponent { items = ['a', 'b', 'c']; get offset() { offsetReads++; return 0; } } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('abc'); expect(offsetReads).toBeGreaterThan(0); const prevReads = offsetReads; // explicitly modify the DOM text node to make sure that the list reconciliation algorithm // based on tracking indices overrides it. fixture.debugElement.childNodes[1].nativeNode.data = 'x'; fixture.componentInstance.items.shift(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('bc'); expect(offsetReads).toBeGreaterThan(prevReads); }); it('should be able to access component properties in the tracking function from a loop at the root of the template', () => { const calls = new Set(); @Component({ template: `@for ((item of items); track trackingFn(item, compProp)) {{{item}}}`, standalone: false, }) class TestComponent { items = ['a', 'b']; compProp = 'hello'; trackingFn(item: string, message: string) { calls.add(`${item}:${message}`); return item; } } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect([...calls].sort()).toEqual(['a:hello', 'b:hello']); }); it('should be able to access component properties in the tracking function from a nested template', () => { const calls = new Set(); @Component({ template: ` @if (true) { @if (true) { @if (true) { @for ((item of items); track trackingFn(item, compProp)) {{{item}}} } } } `, standalone: false, }) class TestComponent { items = ['a', 'b']; compProp = 'hello'; trackingFn(item: string, message: string) { calls.add(`${item}:${message}`); return item; } } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect([...calls].sort()).toEqual(['a:hello', 'b:hello']); }); it('should invoke method tracking function with the correct context', () => { let context = null as TestComponent | null; @Component({ template: `@for (item of items; track trackingFn($index, item)) {{{item}}}`, standalone: false, }) class TestComponent { items = ['a', 'b']; trackingFn(_index: number, item: string) { context = this; return item; } } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(context).toBe(fixture.componentInstance); }); it('should warn about duplicated keys when using arrays', () => { @Component({ template: `@for (item of items; track item) {{{item}}}`, standalone: false, }) class TestComponent { items = ['a', 'b', 'a', 'c', 'a']; } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('abaca'); expect(console.warn).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining( `NG0955: The provided track expression resulted in duplicated keys for a given collection.`, ), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining( `Adjust the tracking expression such that it uniquely identifies all the items in the collection. `, ), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining(`key "a" at index "0" and "2"`), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining(`key "a" at index "2" and "4"`), ); }); it('should warn about duplicated keys when using iterables', () => { @Component({ template: `@for (item of items.values(); track item) {{{item}}}`, standalone: false, }) class TestComponent { items = new Map([ [1, 'a'], [2, 'b'], [3, 'a'], [4, 'c'], [5, 'a'], ]); } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('abaca'); expect(console.warn).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining( `NG0955: The provided track expression resulted in duplicated keys for a given collection.`, ), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining( `Adjust the tracking expression such that it uniquely identifies all the items in the collection. `, ), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining(`key "a" at index "0" and "2"`), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining(`key "a" at index "2" and "4"`), ); }); it('should warn about duplicate keys when keys are expressed as symbols', () => { const value = Symbol('a'); @Component({ template: `@for (item of items.values(); track item) {}`, standalone: false, }) class TestComponent { items = new Map([ [1, value], [2, value], ]); } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining(`Symbol(a)" at index "0" and "1".`), ); }); it('should not warn about duplicate keys iterating over the new collection only', () => { @Component({ template: `@for (item of items; track item) {}`, standalone: false, }) class TestComponent { items = [1, 2, 3]; } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(console.warn).not.toHaveBeenCalled(); fixture.componentInstance.items = [4, 5, 6]; fixture.detectChanges(); expect(console.warn).not.toHaveBeenCalled(); }); it('should warn about collection re-creation due to identity tracking', () => { @Component({ template: `@for (item of items; track item) {(<span>{{item.value}}</span>)}`, standalone: false, }) class TestComponent { items = [{value: 0}, {value: 1}]; } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(0)(1)'); expect(console.warn).not.toHaveBeenCalled(); fixture.componentInstance.items = fixture.componentInstance.items.map((item) => ({ value: item.value + 1, })); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(1)(2)'); expect(console.warn).toHaveBeenCalled(); }); it('should NOT warn about collection re-creation when a view is not considered expensive', () => { @Component({ template: `@for (item of items; track item) {({{item.value}})}`, standalone: false, }) class TestComponent { items = [{value: 0}, {value: 1}]; } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(0)(1)'); expect(console.warn).not.toHaveBeenCalled(); fixture.componentInstance.items = fixture.componentInstance.items.map((item) => ({ value: item.value + 1, })); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(1)(2)'); expect(console.warn).not.toHaveBeenCalled(); }); it('should NOT warn about collection re-creation when a trackBy function is not identity', () => { @Component({ template: `@for (item of items; track item.value) {({{item.value}})}`, standalone: false, }) class TestComponent { items = [{value: 0}, {value: 1}]; } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(0)(1)'); expect(console.warn).not.toHaveBeenCalled(); fixture.componentInstance.items = fixture.componentInstance.items.map((item) => ({ value: item.value + 1, })); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(1)(2)'); expect(console.warn).not.toHaveBeenCalled(); }); });
010043
describe('list diffing and view operations', () => { it('should delete views in the middle', () => { @Component({ template: '@for (item of items; track item; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); // delete in the middle fixture.componentInstance.items.splice(1, 1); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|3(1)|'); }); it('should insert views in the middle', () => { @Component({ template: '@for (item of items; track item; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|3(1)|'); // add in the middle fixture.componentInstance.items.splice(1, 0, 2); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); }); it('should replace different items', () => { @Component({ template: '@for (item of items; track item; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); // an item in the middle stays the same, the rest gets replaced fixture.componentInstance.items = [5, 2, 7]; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('5(0)|2(1)|7(2)|'); }); it('should move and delete items', () => { @Component({ template: '@for (item of items; track item; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3, 4, 5, 6]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(false); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|4(3)|5(4)|6(5)|'); // move 5 and do some other delete other operations fixture.componentInstance.items = [5, 3, 7]; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('5(0)|3(1)|7(2)|'); }); it('should correctly attach and detach views with duplicated keys', () => { const BEFORE = [ {'name': 'Task 14', 'id': 14}, {'name': 'Task 14', 'id': 14}, {'name': 'Task 70', 'id': 70}, {'name': 'Task 34', 'id': 34}, ]; const AFTER = [ {'name': 'Task 70', 'id': 70}, {'name': 'Task 14', 'id': 14}, {'name': 'Task 28', 'id': 28}, ]; @Component({ standalone: true, template: ``, selector: 'child-cmp', }) class ChildCmp {} @Component({ standalone: true, imports: [ChildCmp], template: ` @for(task of tasks; track task.id) { <child-cmp/> } `, }) class TestComponent { tasks = BEFORE; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const cmp = fixture.componentInstance; const nativeElement = fixture.debugElement.nativeElement; cmp.tasks = AFTER; fixture.detectChanges(); expect(nativeElement.querySelectorAll('child-cmp').length).toBe(3); }); });
010045
it('should not project the root node across multiple layers of @for', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @for (item of items; track $index) { @for (item of items; track $index) { <span foo>{{item}}</span> } } After</test> `, }) class App { items = [1, 2]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before 1212 After Slot: '); }); it('should project an @for with a single root template node into the root node slot', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent, NgIf], template: `<test>Before @for (item of items; track $index) { <span *ngIf="true" foo>{{item}}</span> } After</test>`, }) class App { items = [1, 2]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 12'); fixture.componentInstance.items.push(3); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 123'); }); it('should invoke a projected attribute directive at the root of an @for once', () => { let directiveCount = 0; @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Directive({ selector: '[foo]', standalone: true, }) class FooDirective { constructor() { directiveCount++; } } @Component({ standalone: true, imports: [TestComponent, FooDirective], template: `<test>Before @for (item of items; track $index) { <span foo>{{item}}</span> } After</test> `, }) class App { items = [1]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(directiveCount).toBe(1); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 1'); }); it('should invoke a projected template directive at the root of an @for once', () => { let directiveCount = 0; @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Directive({ selector: '[templateDir]', standalone: true, }) class TemplateDirective implements OnInit { constructor( private viewContainerRef: ViewContainerRef, private templateRef: TemplateRef<any>, ) { directiveCount++; } ngOnInit(): void { const view = this.viewContainerRef.createEmbeddedView(this.templateRef); this.viewContainerRef.insert(view); } } @Component({ standalone: true, imports: [TestComponent, TemplateDirective], template: `<test>Before @for (item of items; track $index) { <span *templateDir foo>{{item}}</span> } After</test> `, }) class App { items = [1]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(directiveCount).toBe(1); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 1'); }); it('should invoke a directive on a projected ng-template at the root of an @for once', () => { let directiveCount = 0; @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Directive({ selector: '[templateDir]', standalone: true, }) class TemplateDirective implements OnInit { constructor( private viewContainerRef: ViewContainerRef, private templateRef: TemplateRef<any>, ) { directiveCount++; } ngOnInit(): void { const view = this.viewContainerRef.createEmbeddedView(this.templateRef); this.viewContainerRef.insert(view); } } @Component({ standalone: true, imports: [TestComponent, TemplateDirective], template: `<test>Before @for (item of items; track $index) { <ng-template templateDir foo>{{item}}</ng-template> } After</test> `, }) class App { items = [1]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(directiveCount).toBe(1); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 1'); }); }); });
010046
/** * @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 {CommonModule} from '@angular/common'; import { AfterViewInit, ChangeDetectorRef, Component, ContentChildren, Directive, DoCheck, Input, NgModule, OnChanges, QueryList, SimpleChange, SimpleChanges, TemplateRef, ViewChild, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; describe('onChanges', () => { it('should correctly support updating one Input among many', () => { let log: string[] = []; @Component({ selector: 'child-comp', template: 'child', standalone: false, }) class ChildComp implements OnChanges { @Input() a: number = 0; @Input() b: number = 0; @Input() c: number = 0; ngOnChanges(changes: SimpleChanges) { for (let key in changes) { const simpleChange = changes[key]; log.push(key + ': ' + simpleChange.previousValue + ' -> ' + simpleChange.currentValue); } } } @Component({ selector: 'app-comp', template: '<child-comp [a]="a" [b]="b" [c]="c"></child-comp>', standalone: false, }) class AppComp { a = 0; b = 0; c = 0; } TestBed.configureTestingModule({declarations: [AppComp, ChildComp]}); const fixture = TestBed.createComponent(AppComp); fixture.detectChanges(); const appComp = fixture.componentInstance; expect(log).toEqual(['a: undefined -> 0', 'b: undefined -> 0', 'c: undefined -> 0']); log.length = 0; appComp.a = 1; fixture.detectChanges(); expect(log).toEqual(['a: 0 -> 1']); log.length = 0; appComp.b = 2; fixture.detectChanges(); expect(log).toEqual(['b: 0 -> 2']); log.length = 0; appComp.c = 3; fixture.detectChanges(); expect(log).toEqual(['c: 0 -> 3']); }); it('should call onChanges method after inputs are set in creation and update mode', () => { const events: any[] = []; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() val1 = 'a'; @Input('publicVal2') val2 = 'b'; ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp', changes}); } } @Component({ template: `<comp [val1]="val1" [publicVal2]="val2"></comp>`, standalone: false, }) class App { val1 = 'a2'; val2 = 'b2'; } TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'comp', changes: { val1: new SimpleChange(undefined, 'a2', true), val2: new SimpleChange(undefined, 'b2', true), }, }, ]); events.length = 0; fixture.componentInstance.val1 = 'a3'; fixture.componentInstance.val2 = 'b3'; fixture.detectChanges(); expect(events).toEqual([ { name: 'comp', changes: { val1: new SimpleChange('a2', 'a3', false), val2: new SimpleChange('b2', 'b3', false), }, }, ]); }); it('should call parent onChanges before child onChanges', () => { const events: any[] = []; @Component({ selector: 'parent', template: `<child [val]="val"></child>`, standalone: false, }) class Parent { @Input() val = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'parent', changes}); } } @Component({ selector: 'child', template: `<p>test</p>`, standalone: false, }) class Child { @Input() val = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'child', changes}); } } @Component({ template: `<parent [val]="val"></parent>`, standalone: false, }) class App { val = 'foo'; } TestBed.configureTestingModule({ declarations: [App, Child, Parent], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'parent', changes: { val: new SimpleChange(undefined, 'foo', true), }, }, { name: 'child', changes: { val: new SimpleChange(undefined, 'foo', true), }, }, ]); events.length = 0; fixture.componentInstance.val = 'bar'; fixture.detectChanges(); expect(events).toEqual([ { name: 'parent', changes: { val: new SimpleChange('foo', 'bar', false), }, }, { name: 'child', changes: { val: new SimpleChange('foo', 'bar', false), }, }, ]); }); it('should call all parent onChanges across view before calling children onChanges', () => { const events: any[] = []; @Component({ selector: 'parent', template: `<child [name]="name" [val]="val"></child>`, standalone: false, }) class Parent { @Input() val = ''; @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'parent ' + this.name, changes}); } } @Component({ selector: 'child', template: `<p>test</p>`, standalone: false, }) class Child { @Input() val = ''; @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'child ' + this.name, changes}); } } @Component({ template: ` <parent name="1" [val]="val"></parent> <parent name="2" [val]="val"></parent> `, standalone: false, }) class App { val = 'foo'; } TestBed.configureTestingModule({ declarations: [App, Child, Parent], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'parent 1', changes: { name: new SimpleChange(undefined, '1', true), val: new SimpleChange(undefined, 'foo', true), }, }, { name: 'parent 2', changes: { name: new SimpleChange(undefined, '2', true), val: new SimpleChange(undefined, 'foo', true), }, }, { name: 'child 1', changes: { name: new SimpleChange(undefined, '1', true), val: new SimpleChange(undefined, 'foo', true), }, }, { name: 'child 2', changes: { name: new SimpleChange(undefined, '2', true), val: new SimpleChange(undefined, 'foo', true), }, }, ]); events.length = 0; fixture.componentInstance.val = 'bar'; fixture.detectChanges(); expect(events).toEqual([ { name: 'parent 1', changes: { val: new SimpleChange('foo', 'bar', false), }, }, { name: 'parent 2', changes: { val: new SimpleChange('foo', 'bar', false), }, }, { name: 'child 1', changes: { val: new SimpleChange('foo', 'bar', false), }, }, { name: 'child 2', changes: { val: new SimpleChange('foo', 'bar', false), }, }, ]); });
010049
it('should call onChanges properly in for loop with children', () => { const events: any[] = []; @Component({ selector: 'child', template: `<p>{{val}}</p>`, standalone: false, }) class Child { @Input() val = ''; @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'child of parent ' + this.name, changes}); } } @Component({ selector: 'parent', template: `<child [name]="name" [val]="val"></child>`, standalone: false, }) class Parent { @Input() val = ''; @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'parent ' + this.name, changes}); } } @Component({ template: ` <parent name="0" [val]="val"></parent> <parent *ngFor="let number of numbers" [name]="number" [val]="val"></parent> <parent name="1" [val]="val"></parent> `, standalone: false, }) class App { val = 'a'; numbers = ['2', '3', '4']; } TestBed.configureTestingModule({ declarations: [App, Child, Parent], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'parent 0', changes: { name: new SimpleChange(undefined, '0', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'parent 1', changes: { name: new SimpleChange(undefined, '1', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'parent 2', changes: { name: new SimpleChange(undefined, '2', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'child of parent 2', changes: { name: new SimpleChange(undefined, '2', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'parent 3', changes: { name: new SimpleChange(undefined, '3', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'child of parent 3', changes: { name: new SimpleChange(undefined, '3', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'parent 4', changes: { name: new SimpleChange(undefined, '4', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'child of parent 4', changes: { name: new SimpleChange(undefined, '4', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'child of parent 0', changes: { name: new SimpleChange(undefined, '0', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'child of parent 1', changes: { name: new SimpleChange(undefined, '1', true), val: new SimpleChange(undefined, 'a', true), }, }, ]); events.length = 0; fixture.componentInstance.val = 'b'; fixture.detectChanges(); expect(events).toEqual([ { name: 'parent 0', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'parent 1', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'parent 2', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'child of parent 2', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'parent 3', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'child of parent 3', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'parent 4', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'child of parent 4', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'child of parent 0', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'child of parent 1', changes: { val: new SimpleChange('a', 'b', false), }, }, ]); }); it('should not call onChanges if props are set directly', () => { const events: any[] = []; @Component({ template: `<p>{{value}}</p>`, standalone: false, }) class App { value = 'a'; ngOnChanges(changes: SimpleChanges) { events.push(changes); } } TestBed.configureTestingModule({ declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([]); fixture.componentInstance.value = 'b'; fixture.detectChanges(); expect(events).toEqual([]); }); });
010113
scribe('OnPush', () => { @Component({ selector: 'my-comp', changeDetection: ChangeDetectionStrategy.OnPush, template: `{{ doCheckCount }} - {{ name }} <button (click)="onClick()"></button>`, standalone: false, }) class MyComponent implements DoCheck { @Input() name = 'Nancy'; doCheckCount = 0; ngDoCheck(): void { this.doCheckCount++; } onClick() {} } @Component({ selector: 'my-app', template: '<my-comp [name]="name"></my-comp>', standalone: false, }) class MyApp { @ViewChild(MyComponent) comp!: MyComponent; name: string = 'Nancy'; } it('should check OnPush components on initialization', () => { TestBed.configureTestingModule({declarations: [MyComponent, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); }); it('should call doCheck even when OnPush components are not dirty', () => { TestBed.configureTestingModule({declarations: [MyComponent, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(2); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(3); }); it('should skip OnPush components in update mode when they are not dirty', () => { TestBed.configureTestingModule({declarations: [MyComponent, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); // doCheckCount is 2, but 1 should be rendered since it has not been marked dirty. expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); fixture.detectChanges(); // doCheckCount is 3, but 1 should be rendered since it has not been marked dirty. expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); }); it('should check OnPush components in update mode when inputs change', () => { TestBed.configureTestingModule({declarations: [MyComponent, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); fixture.componentInstance.name = 'Bess'; fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(2); // View should update, as changed input marks view dirty expect(fixture.nativeElement.textContent.trim()).toEqual('2 - Bess'); fixture.componentInstance.name = 'George'; fixture.detectChanges(); // View should update, as changed input marks view dirty expect(fixture.componentInstance.comp.doCheckCount).toEqual(3); expect(fixture.nativeElement.textContent.trim()).toEqual('3 - George'); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(4); // View should not be updated to "4", as inputs have not changed. expect(fixture.nativeElement.textContent.trim()).toEqual('3 - George'); }); it('should check OnPush components in update mode when component events occur', () => { TestBed.configureTestingModule({declarations: [MyComponent, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(1); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); const button = fixture.nativeElement.querySelector('button')!; button.click(); // No ticks should have been scheduled. expect(fixture.componentInstance.comp.doCheckCount).toEqual(1); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); fixture.detectChanges(); // Because the onPush comp should be dirty, it should update once CD runs expect(fixture.componentInstance.comp.doCheckCount).toEqual(2); expect(fixture.nativeElement.textContent.trim()).toEqual('2 - Nancy'); }); it('should not check OnPush components in update mode when parent events occur', () => { @Component({ selector: 'button-parent', template: '<my-comp></my-comp><button id="parent" (click)="noop()"></button>', standalone: false, }) class ButtonParent { @ViewChild(MyComponent) comp!: MyComponent; noop() {} } TestBed.configureTestingModule({declarations: [MyComponent, ButtonParent]}); const fixture = TestBed.createComponent(ButtonParent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button#parent'); button.click(); fixture.detectChanges(); // The comp should still be clean. So doCheck will run, but the view should display 1. expect(fixture.componentInstance.comp.doCheckCount).toEqual(2); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); }); it('should check parent OnPush components in update mode when child events occur', () => { @Component({ selector: 'button-parent', template: '{{ doCheckCount }} - <my-comp></my-comp>', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class ButtonParent implements DoCheck { @ViewChild(MyComponent) comp!: MyComponent; noop() {} doCheckCount = 0; ngDoCheck(): void { this.doCheckCount++; } } @Component({ selector: 'my-button-app', template: '<button-parent></button-parent>', standalone: false, }) class MyButtonApp { @ViewChild(ButtonParent) parent!: ButtonParent; } TestBed.configureTestingModule({declarations: [MyButtonApp, MyComponent, ButtonParent]}); const fixture = TestBed.createComponent(MyButtonApp); fixture.detectChanges(); const parent = fixture.componentInstance.parent; const comp = parent.comp; expect(parent.doCheckCount).toEqual(1); expect(comp.doCheckCount).toEqual(1); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - 1 - Nancy'); fixture.detectChanges(); expect(parent.doCheckCount).toEqual(2); // parent isn't checked, so child doCheck won't run expect(comp.doCheckCount).toEqual(1); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - 1 - Nancy'); const button = fixture.nativeElement.querySelector('button'); button.click(); // No ticks should have been scheduled. expect(parent.doCheckCount).toEqual(2); expect(comp.doCheckCount).toEqual(1); fixture.detectChanges(); expect(parent.doCheckCount).toEqual(3); expect(comp.doCheckCount).toEqual(2); expect(fixture.nativeElement.textContent.trim()).toEqual('3 - 2 - Nancy'); }); it('should check parent OnPush components when child directive on a template emits event', fakeAsync(() => { @Directive({ selector: '[emitter]', standalone: false, }) class Emitter { @Output() event = new EventEmitter<string>(); ngOnInit() { setTimeout(() => { this.event.emit('new message'); }); } } @Component({ selector: 'my-app', template: '{{message}} <ng-template emitter (event)="message = $event"></ng-template>', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class MyApp { message = 'initial message'; } const fixture = TestBed.configureTestingModule({ declarations: [MyApp, Emitter], }).createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toEqual('initial message'); tick(); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toEqual('new message'); })); });
010114
scribe('ChangeDetectorRef', () => { describe('detectChanges()', () => { @Component({ selector: 'my-comp', template: '{{ name }}', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class MyComp implements DoCheck { doCheckCount = 0; name = 'Nancy'; constructor(public cdr: ChangeDetectorRef) {} ngDoCheck() { this.doCheckCount++; } } @Component({ selector: 'parent-comp', template: `{{ doCheckCount}} - <my-comp></my-comp>`, standalone: false, }) class ParentComp implements DoCheck { @ViewChild(MyComp) myComp!: MyComp; doCheckCount = 0; constructor(public cdr: ChangeDetectorRef) {} ngDoCheck() { this.doCheckCount++; } } @Directive({ selector: '[dir]', standalone: false, }) class Dir { constructor(public cdr: ChangeDetectorRef) {} } it('should check the component view when called by component (even when OnPush && clean)', () => { TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Nancy'); fixture.componentInstance.name = 'Bess'; // as this is not an Input, the component stays clean fixture.componentInstance.cdr.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Bess'); }); it('should NOT call component doCheck when called by a component', () => { TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(1); // NOTE: in current Angular, detectChanges does not itself trigger doCheck, but you // may see doCheck called in some cases bc of the extra CD run triggered by zone.js. // It's important not to call doCheck to allow calls to detectChanges in that hook. fixture.componentInstance.cdr.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(1); }); it('should NOT check the component parent when called by a child component', () => { TestBed.configureTestingModule({declarations: [MyComp, ParentComp]}); const fixture = TestBed.createComponent(ParentComp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('1 - Nancy'); fixture.componentInstance.doCheckCount = 100; fixture.componentInstance.myComp.cdr.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(100); expect(fixture.nativeElement.textContent).toEqual('1 - Nancy'); }); it('should check component children when called by component if dirty or check-always', () => { TestBed.configureTestingModule({declarations: [MyComp, ParentComp]}); const fixture = TestBed.createComponent(ParentComp); fixture.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(1); fixture.componentInstance.myComp.name = 'Bess'; fixture.componentInstance.cdr.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(1); expect(fixture.componentInstance.myComp.doCheckCount).toEqual(2); // OnPush child is not dirty, so its change isn't rendered. expect(fixture.nativeElement.textContent).toEqual('1 - Nancy'); }); it('should not group detectChanges calls (call every time)', () => { TestBed.configureTestingModule({declarations: [MyComp, ParentComp]}); const fixture = TestBed.createComponent(ParentComp); fixture.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(1); fixture.componentInstance.cdr.detectChanges(); fixture.componentInstance.cdr.detectChanges(); expect(fixture.componentInstance.myComp.doCheckCount).toEqual(3); }); it('should check component view when called by directive on component node', () => { @Component({ template: '<my-comp dir></my-comp>', standalone: false, }) class MyApp { @ViewChild(MyComp) myComp!: MyComp; @ViewChild(Dir) dir!: Dir; } TestBed.configureTestingModule({declarations: [MyComp, Dir, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Nancy'); fixture.componentInstance.myComp.name = 'George'; fixture.componentInstance.dir.cdr.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('George'); }); it('should check host component when called by directive on element node', () => { @Component({ template: '{{ value }}<div dir></div>', standalone: false, }) class MyApp { @ViewChild(MyComp) myComp!: MyComp; @ViewChild(Dir) dir!: Dir; value = ''; } TestBed.configureTestingModule({declarations: [Dir, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); fixture.componentInstance.value = 'Frank'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Frank'); fixture.componentInstance.value = 'Joe'; fixture.componentInstance.dir.cdr.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Joe'); }); it('should check the host component when called from EmbeddedViewRef', () => { @Component({ template: '{{ name }}<div *ngIf="showing" dir></div>', standalone: false, }) class MyApp { @ViewChild(Dir) dir!: Dir; showing = true; name = 'Amelia'; } TestBed.configureTestingModule({declarations: [Dir, MyApp], imports: [CommonModule]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Amelia'); fixture.componentInstance.name = 'Emerson'; fixture.componentInstance.dir.cdr.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Emerson'); }); it('should support call in ngOnInit', () => { @Component({ template: '{{ value }}', standalone: false, }) class DetectChangesComp implements OnInit { value = 0; constructor(public cdr: ChangeDetectorRef) {} ngOnInit() { this.value++; this.cdr.detectChanges(); } } TestBed.configureTestingModule({declarations: [DetectChangesComp]}); const fixture = TestBed.createComponent(DetectChangesComp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('1'); }); ['OnInit', 'AfterContentInit', 'AfterViewInit', 'OnChanges'].forEach((hook) => { it(`should not go infinite loop when recursively called from children's ng${hook}`, () => { @Component({ template: '<child-comp [inp]="true"></child-comp>', standalone: false, }) class ParentComp { constructor(public cdr: ChangeDetectorRef) {} triggerChangeDetection() { this.cdr.detectChanges(); } } @Component({ template: '{{inp}}', selector: 'child-comp', standalone: false, }) class ChildComp { @Input() inp: any = ''; count = 0; constructor(public parentComp: ParentComp) {} ngOnInit() { this.check('OnInit'); } ngAfterContentInit() { this.check('AfterContentInit'); } ngAfterViewInit() { this.check('AfterViewInit'); } ngOnChanges() { this.check('OnChanges'); } check(h: string) { if (h === hook) { this.count++; if (this.count > 1) throw new Error(`ng${hook} should be called only once!`); this.parentComp.triggerChangeDetection(); } } } TestBed.configureTestingModule({declarations: [ParentComp, ChildComp]}); expect(() => { const fixture = TestBed.createComponent(ParentComp); fixture.detectChanges(); }).not.toThrow(); }); }); it('should support call in ngDoCheck', () => { @Component({ template: '{{doCheckCount}}', standalone: false, }) class DetectChangesComp { doCheckCount = 0; constructor(public cdr: ChangeDetectorRef) {} ngDoCheck() { this.doCheckCount++; this.cdr.detectChanges(); } } TestBed.configureTestingModule({declarations: [DetectChangesComp]}); const fixture = TestBed.createComponent(DetectChangesComp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('1'); });
010115
('should support change detection triggered as a result of View queries processing', () => { @Component({ selector: 'app', template: ` <div *ngIf="visible" #ref>Visible text</div> `, standalone: false, }) class App { @ViewChildren('ref') ref!: QueryList<any>; visible = false; constructor(public changeDetectorRef: ChangeDetectorRef) {} ngAfterViewInit() { this.ref.changes.subscribe((refs: QueryList<any>) => { this.visible = false; this.changeDetectorRef.detectChanges(); }); } } TestBed.configureTestingModule({ declarations: [App], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe(''); // even though we set "visible" to `true`, we do not expect any content to be displayed, // since the flag is overridden in `ngAfterViewInit` back to `false` fixture.componentInstance.visible = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe(''); }); describe('dynamic views', () => { @Component({ selector: 'structural-comp', template: '{{ value }}', standalone: false, }) class StructuralComp { @Input() tmp!: TemplateRef<any>; value = 'one'; constructor(public vcr: ViewContainerRef) {} create() { return this.vcr.createEmbeddedView(this.tmp, {ctx: this}); } } it('should support ViewRef.detectChanges()', () => { @Component({ template: '<ng-template #foo let-ctx="ctx">{{ ctx.value }}</ng-template><structural-comp [tmp]="foo"></structural-comp>', standalone: false, }) class App { @ViewChild(StructuralComp) structuralComp!: StructuralComp; } TestBed.configureTestingModule({declarations: [App, StructuralComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); const viewRef: EmbeddedViewRef<any> = fixture.componentInstance.structuralComp.create(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('oneone'); // check embedded view update fixture.componentInstance.structuralComp.value = 'two'; viewRef.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('onetwo'); // check root view update fixture.componentInstance.structuralComp.value = 'three'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('threethree'); }); it('should support ViewRef.detectChanges() directly after creation', () => { @Component({ template: '<ng-template #foo>Template text</ng-template><structural-comp [tmp]="foo">', standalone: false, }) class App { @ViewChild(StructuralComp) structuralComp!: StructuralComp; } TestBed.configureTestingModule({declarations: [App, StructuralComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); const viewRef: EmbeddedViewRef<any> = fixture.componentInstance.structuralComp.create(); viewRef.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('oneTemplate text'); }); }); }); describe('attach/detach', () => { @Component({ selector: 'detached-comp', template: '{{ value }}', standalone: false, }) class DetachedComp implements DoCheck { value = 'one'; doCheckCount = 0; constructor(public cdr: ChangeDetectorRef) {} ngDoCheck() { this.doCheckCount++; } } @Component({ template: '<detached-comp></detached-comp>', standalone: false, }) class MyApp { @ViewChild(DetachedComp) comp!: DetachedComp; constructor(public cdr: ChangeDetectorRef) {} } it('should not check detached components', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.comp.cdr.detach(); fixture.componentInstance.comp.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); }); it('should check re-attached components', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.comp.cdr.detach(); fixture.componentInstance.comp.value = 'two'; fixture.componentInstance.comp.cdr.reattach(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two'); }); it('should call lifecycle hooks on detached components', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(1); fixture.componentInstance.comp.cdr.detach(); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(2); }); it('should check detached component when detectChanges is called', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.comp.cdr.detach(); fixture.componentInstance.comp.value = 'two'; fixture.componentInstance.comp.cdr.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two'); }); it('should not check detached component when markDirty is called', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); const comp = fixture.componentInstance.comp; comp.cdr.detach(); comp.value = 'two'; comp.cdr.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); }); it('should detach any child components when parent is detached', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.cdr.detach(); fixture.componentInstance.comp.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.cdr.reattach(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two'); }); it('should detach OnPush components properly', () => { @Component({ selector: 'on-push-comp', template: '{{ value }}', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushComp { @Input() value!: string; constructor(public cdr: ChangeDetectorRef) {} } @Component({ template: '<on-push-comp [value]="value"></on-push-comp>', standalone: false, }) class OnPushApp { @ViewChild(OnPushComp) onPushComp!: OnPushComp; value = ''; } TestBed.configureTestingModule({declarations: [OnPushApp, OnPushComp]}); const fixture = TestBed.createComponent(OnPushApp); fixture.detectChanges(); fixture.componentInstance.value = 'one'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.onPushComp.cdr.detach(); fixture.componentInstance.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.onPushComp.cdr.reattach(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two'); }); });
010116
scribe('markForCheck()', () => { @Component({ selector: 'on-push-comp', template: '{{ value }}', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushComp implements DoCheck { value = 'one'; doCheckCount = 0; constructor(public cdr: ChangeDetectorRef) {} ngDoCheck() { this.doCheckCount++; } } @Component({ template: '{{ value }} - <on-push-comp></on-push-comp>', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushParent { @ViewChild(OnPushComp) comp!: OnPushComp; value = 'one'; } it('should ensure OnPush components are checked', () => { TestBed.configureTestingModule({declarations: [OnPushParent, OnPushComp]}); const fixture = TestBed.createComponent(OnPushParent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.comp.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.comp.cdr.markForCheck(); // Change detection should not have run yet, since markForCheck // does not itself schedule change detection. expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - two'); }); it('should never schedule change detection on its own', () => { TestBed.configureTestingModule({declarations: [OnPushParent, OnPushComp]}); const fixture = TestBed.createComponent(OnPushParent); fixture.detectChanges(); const comp = fixture.componentInstance.comp; expect(comp.doCheckCount).toEqual(1); comp.cdr.markForCheck(); comp.cdr.markForCheck(); expect(comp.doCheckCount).toEqual(1); }); it('should ensure ancestor OnPush components are checked', () => { TestBed.configureTestingModule({declarations: [OnPushParent, OnPushComp]}); const fixture = TestBed.createComponent(OnPushParent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.comp.cdr.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two - one'); }); it('should ensure OnPush components in embedded views are checked', () => { @Component({ template: '{{ value }} - <on-push-comp *ngIf="showing"></on-push-comp>', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class EmbeddedViewParent { @ViewChild(OnPushComp) comp!: OnPushComp; value = 'one'; showing = true; } TestBed.configureTestingModule({ declarations: [EmbeddedViewParent, OnPushComp], imports: [CommonModule], }); const fixture = TestBed.createComponent(EmbeddedViewParent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.comp.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.comp.cdr.markForCheck(); // markForCheck should not trigger change detection on its own. expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - two'); fixture.componentInstance.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - two'); fixture.componentInstance.comp.cdr.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two - two'); }); it('async pipe should trigger CD for embedded views where the declaration and insertion views are different', () => { @Component({ selector: 'insertion', changeDetection: ChangeDetectionStrategy.OnPush, template: ` <ng-container [ngTemplateOutlet]="template"> </ng-container> `, standalone: false, }) class Insertion { @Input() template!: TemplateRef<{}>; } // This component uses async pipe (which calls markForCheck) in a view that has different // insertion and declaration views. @Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: ` <insertion [template]="ref"></insertion> <ng-template #ref> <span>{{value | async}}</span> </ng-template> `, standalone: false, }) class Declaration { value = new BehaviorSubject('initial value'); } const fixture = TestBed.configureTestingModule({ declarations: [Insertion, Declaration], }).createComponent(Declaration); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.textContent).toContain('initial value'); fixture.componentInstance.value.next('new value'); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.textContent).toContain('new value'); }); // TODO(kara): add test for dynamic views once bug fix is in }); describe('checkNoChanges', () => { let comp: NoChangesComp; @Component({ selector: 'no-changes-comp', template: '{{ value }}', standalone: false, }) class NoChangesComp { value = 1; doCheckCount = 0; contentCheckCount = 0; viewCheckCount = 0; ngDoCheck() { this.doCheckCount++; } ngAfterContentChecked() { this.contentCheckCount++; } ngAfterViewChecked() { this.viewCheckCount++; } constructor(public cdr: ChangeDetectorRef) { comp = this; } } @Component({ template: '{{ value }} - <no-changes-comp></no-changes-comp>', standalone: false, }) class AppComp { value = 1; constructor(public cdr: ChangeDetectorRef) {} } // Custom error handler that just rethrows all the errors from the // view, rather than logging them out. Used to keep our logs clean. class RethrowErrorHandler extends ErrorHandler { override handleError(error: any) { throw error; } } it('should throw if bindings in current view have changed', () => { TestBed.configureTestingModule({ declarations: [NoChangesComp], providers: [{provide: ErrorHandler, useClass: RethrowErrorHandler}], }); const fixture = TestBed.createComponent(NoChangesComp); expect(() => { fixture.componentInstance.cdr.checkNoChanges(); }).toThrowError( /ExpressionChangedAfterItHasBeenCheckedError: .+ Previous value: '.*undefined'. Current value: '.*1'/gi, ); }); it('should throw if interpolations in current view have changed', () => { TestBed.configureTestingModule({ declarations: [AppComp, NoChangesComp], providers: [{provide: ErrorHandler, useClass: RethrowErrorHandler}], }); const fixture = TestBed.createComponent(AppComp); expect(() => fixture.componentInstance.cdr.checkNoChanges()).toThrowError( /ExpressionChangedAfterItHasBeenCheckedError: .+ Previous value: '.*undefined'. Current value: '.*1'/gi, ); }); it('should throw if bindings in embedded view have changed', () => { @Component({ template: '<span *ngIf="showing">{{ showing }}</span>', standalone: false, }) class EmbeddedViewApp { showing = true; constructor(public cdr: ChangeDetectorRef) {} } TestBed.configureTestingModule({ declarations: [EmbeddedViewApp], imports: [CommonModule], providers: [{provide: ErrorHandler, useClass: RethrowErrorHandler}], }); const fixture = TestBed.createComponent(EmbeddedViewApp); expect(() => fixture.componentInstance.cdr.checkNoChanges()).toThrowError( /ExpressionChangedAfterItHasBeenCheckedError: .+ Previous value: '.*undefined'. Current value: '.*true'/gi, ); }); it('should NOT call lifecycle hooks', () => { TestBed.configureTestingModule({ declarations: [AppComp, NoChangesComp], providers: [{provide: ErrorHandler, useClass: RethrowErrorHandler}], }); const fixture = TestBed.createComponent(AppComp); fixture.detectChanges(); expect(comp.doCheckCount).toEqual(1); expect(comp.contentCheckCount).toEqual(1); expect(comp.viewCheckCount).toEqual(1); comp.value = 2; expect(() => fixture.componentInstance.cdr.checkNoChanges()).toThrow(); expect(comp.doCheckCount).toEqual(1); expect(comp.contentCheckCount).toEqual(1); expect(comp.viewCheckCount).toEqual(1); });
010134
intersection observer once all deferred blocks have been loaded', fakeAsync(() => { @Component({ standalone: true, template: ` <button #triggerOne></button> @defer (on viewport(triggerOne)) { One } <button #triggerTwo></button> @defer (on viewport(triggerTwo)) { Two } `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(activeObservers.length).toBe(1); const buttons = Array.from<HTMLElement>(fixture.nativeElement.querySelectorAll('button')); const observer = activeObservers[0]; const disconnectSpy = spyOn(observer, 'disconnect').and.callThrough(); expect(Array.from(observer.observedElements)).toEqual(buttons); MockIntersectionObserver.invokeCallbacksForElement(buttons[0], true); fixture.detectChanges(); expect(disconnectSpy).not.toHaveBeenCalled(); expect(Array.from(observer.observedElements)).toEqual([buttons[1]]); MockIntersectionObserver.invokeCallbacksForElement(buttons[1], true); fixture.detectChanges(); expect(disconnectSpy).toHaveBeenCalled(); expect(observer.observedElements.size).toBe(0); })); it('should prefetch resources when the trigger comes into the viewport', fakeAsync(() => { @Component({ standalone: true, selector: 'root-app', template: ` @defer (when isLoaded; prefetch on viewport(trigger)) { Main content } <button #trigger></button> `, }) class MyCmp { // We need a `when` trigger here so that `on idle` doesn't get added automatically. readonly isLoaded = false; } let loadingFnInvokedTimes = 0; TestBed.configureTestingModule({ providers: [ { provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: { intercept: () => () => { loadingFnInvokedTimes++; return []; }, }, }, ], }); clearDirectiveDefs(MyCmp); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(loadingFnInvokedTimes).toBe(0); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); MockIntersectionObserver.invokeCallbacksForElement(button, true); fixture.detectChanges(); flush(); expect(loadingFnInvokedTimes).toBe(1); })); it('should prefetch resources when an implicit trigger comes into the viewport', fakeAsync(() => { @Component({ standalone: true, selector: 'root-app', template: ` @defer (when isLoaded; prefetch on viewport) { Main content } @placeholder { <button></button> } `, }) class MyCmp { // We need a `when` trigger here so that `on idle` doesn't get added automatically. readonly isLoaded = false; } let loadingFnInvokedTimes = 0; TestBed.configureTestingModule({ providers: [ { provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: { intercept: () => () => { loadingFnInvokedTimes++; return []; }, }, }, ], }); clearDirectiveDefs(MyCmp); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(loadingFnInvokedTimes).toBe(0); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); MockIntersectionObserver.invokeCallbacksForElement(button, true); fixture.detectChanges(); flush(); expect(loadingFnInvokedTimes).toBe(1); })); it('should load deferred content in a loop', fakeAsync(() => { @Component({ standalone: true, template: ` @for (item of items; track item) { @defer (on viewport) {d{{item}} } @placeholder {<button>p{{item}} </button>} } `, }) class MyCmp { items = [1, 2, 3, 4, 5, 6]; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const buttons = Array.from<Element>(fixture.nativeElement.querySelectorAll('button')); const items = fixture.componentInstance.items; // None of the blocks are loaded yet. expect(fixture.nativeElement.textContent.trim()).toBe('p1 p2 p3 p4 p5 p6'); // First half of the blocks is loaded. for (let i = 0; i < items.length / 2; i++) { MockIntersectionObserver.invokeCallbacksForElement(buttons[i], true); fixture.detectChanges(); flush(); } expect(fixture.nativeElement.textContent.trim()).toBe('d1 d2 d3 p4 p5 p6'); // Second half of the blocks is loaded. for (let i = items.length / 2; i < items.length; i++) { MockIntersectionObserver.invokeCallbacksForElement(buttons[i], true); fixture.detectChanges(); flush(); } expect(fixture.nativeElement.textContent.trim()).toBe('d1 d2 d3 d4 d5 d6'); })); }); describe('DOM-based events cleanup', () => { it('should unbind `interaction` trigger events when the deferred block is loaded', async () => { @Component({ standalone: true, template: ` @defer ( when isVisible; on interaction(trigger); prefetch on interaction(prefetchTrigger) ) { Main content } <button #trigger></button> <div #prefetchTrigger></div> `, }) class MyCmp { isVisible = false; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); const triggerSpy = spyOn(button, 'removeEventListener'); const div = fixture.nativeElement.querySelector('div'); const prefetchSpy = spyOn(div, 'removeEventListener'); fixture.componentInstance.isVisible = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify that trigger element is cleaned up. expect(triggerSpy).toHaveBeenCalledTimes(2); expect(triggerSpy).toHaveBeenCalledWith('click', jasmine.any(Function), jasmine.any(Object)); expect(triggerSpy).toHaveBeenCalledWith( 'keydown', jasmine.any(Function), jasmine.any(Object), ); // Verify that prefetch trigger element is cleaned up. expect(prefetchSpy).toHaveBeenCalledTimes(2); expect(prefetchSpy).toHaveBeenCalledWith('click', jasmine.any(Function), jasmine.any(Object)); expect(prefetchSpy).toHaveBeenCalledWith( 'keydown', jasmine.any(Function), jasmine.any(Object), ); }); it('should unbind `hover` trigger events when the deferred block is loaded', async () => { @Component({ standalone: true, template: ` @defer ( when isVisible; on hover(trigger); prefetch on hover(prefetchTrigger) ) { Main content } <button #trigger></button> <div #prefetchTrigger></div> `, }) class MyCmp { isVisible = false; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); const triggerSpy = spyOn(button, 'removeEventListener'); const div = fixture.nativeElement.querySelector('div'); const prefetchSpy = spyOn(div, 'removeEventListener'); fixture.componentInstance.isVisible = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify that trigger element is cleaned up. expect(triggerSpy).toHaveBeenCalledTimes(3); expect(triggerSpy).toHaveBeenCalledWith( 'mouseenter', jasmine.any(Function), jasmine.any(Object), ); expect(triggerSpy).toHaveBeenCalledWith( 'mouseover', jasmine.any(Function), jasmine.any(Object), ); expect(triggerSpy).toHaveBeenCalledWith( 'focusin', jasmine.any(Function), jasmine.any(Object), ); // Verify that prefetch trigger element is cleaned up. expect(prefetchSpy).toHaveBeenCalledTimes(3); expect(prefetchSpy).toHaveBeenCalledWith( 'mouseenter', jasmine.any(Function), jasmine.any(Object), ); expect(prefetchSpy).toHaveBeenCalledWith( 'mouseover', jasmine.any(Function), jasmine.any(Object), ); expect(prefetchSpy).toHaveBeenCalledWith( 'focusin', jasmine.any(Function), jasmine.any(Object), ); }); }); describe('DI', () => {
010145
('should create the root node in the correct namespace when previous node is SVG', () => { @Component({ template: ` <div>Some random content</div> <!-- Note that it's important for the test that the <svg> element is last. --> <svg></svg> `, standalone: false, }) class TestComp { constructor(public viewContainerRef: ViewContainerRef) {} } @Component({ selector: 'dynamic-comp', template: '', standalone: false, }) class DynamicComponent {} TestBed.configureTestingModule({declarations: [DynamicComponent]}); const fixture = TestBed.createComponent(TestComp); // Note: it's important that we **don't** call `fixture.detectChanges` between here and // the component being created, because running change detection will reset Ivy's // namespace state which will make the test pass. const componentRef = fixture.componentInstance.viewContainerRef.createComponent(DynamicComponent); const element = componentRef.location.nativeElement; expect((element.namespaceURI || '').toLowerCase()).not.toContain('svg'); componentRef.destroy(); }); it('should be compatible with componentRef generated via TestBed.createComponent in component factory', () => { @Component({ selector: 'child', template: `Child Component`, standalone: false, }) class Child {} @Component({ selector: 'comp', template: '<ng-template #ref></ng-template>', standalone: false, }) class Comp { @ViewChild('ref', {read: ViewContainerRef, static: true}) viewContainerRef!: ViewContainerRef; ngOnInit() { const makeComponentFactory = (componentType: any) => ({ create: () => TestBed.createComponent(componentType).componentRef, }); this.viewContainerRef.createComponent(makeComponentFactory(Child) as any); } } TestBed.configureTestingModule({declarations: [Comp, Child]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain('Child Component'); }); it('should return ComponentRef with ChangeDetectorRef attached to root view', () => { @Component({ selector: 'dynamic-cmp', template: ``, standalone: false, }) class DynamicCmp { doCheckCount = 0; ngDoCheck() { this.doCheckCount++; } } @Component({ template: ``, standalone: false, }) class TestCmp { constructor(public viewContainerRef: ViewContainerRef) {} } const fixture = TestBed.createComponent(TestCmp); const testCmpInstance = fixture.componentInstance; const dynamicCmpRef = testCmpInstance.viewContainerRef.createComponent(DynamicCmp); // change detection didn't run at all expect(dynamicCmpRef.instance.doCheckCount).toBe(0); // running change detection on the dynamicCmpRef level dynamicCmpRef.changeDetectorRef.detectChanges(); expect(dynamicCmpRef.instance.doCheckCount).toBe(1); // running change detection on the TestBed fixture level fixture.changeDetectorRef.detectChanges(); expect(dynamicCmpRef.instance.doCheckCount).toBe(2); // The injector should retrieve the change detector ref for DynamicComp. As such, // the doCheck hook for DynamicComp should NOT run upon ref.detectChanges(). const changeDetector = dynamicCmpRef.injector.get(ChangeDetectorRef); changeDetector.detectChanges(); expect(dynamicCmpRef.instance.doCheckCount).toBe(2); }); describe('createComponent using Type', () => { const TOKEN_A = new InjectionToken('A'); const TOKEN_B = new InjectionToken('B'); @Component({ selector: 'child-a', template: `[Child Component A]`, standalone: false, }) class ChildA {} @Component({ selector: 'child-b', template: ` [Child Component B] <ng-content></ng-content> {{ tokenA }} {{ tokenB }} `, standalone: false, }) class ChildB { constructor( private injector: Injector, public renderer: Renderer2, ) {} get tokenA() { return this.injector.get(TOKEN_A); } get tokenB() { return this.injector.get(TOKEN_B); } } @Component({ selector: 'app', template: '', providers: [{provide: TOKEN_B, useValue: '[TokenB - Value]'}], standalone: false, }) class App { constructor( public viewContainerRef: ViewContainerRef, public ngModuleRef: NgModuleRef<unknown>, public injector: Injector, ) {} } @NgModule({ declarations: [App, ChildA, ChildB], providers: [{provide: TOKEN_A, useValue: '[TokenA - Value]'}], }) class AppModule {} let fixture!: ComponentFixture<App>; beforeEach(() => { TestBed.configureTestingModule({imports: [AppModule]}); fixture = TestBed.createComponent(App); fixture.detectChanges(); }); it('should be able to create a component when Type is provided', () => { fixture.componentInstance.viewContainerRef.createComponent(ChildA); expect(fixture.nativeElement.parentNode.textContent).toContain('[Child Component A]'); }); it('should maintain connection with module injector when custom injector is provided', () => { const comp = fixture.componentInstance; const environmentInjector = createEnvironmentInjector( [{provide: TOKEN_B, useValue: '[TokenB - CustomValue]'}], TestBed.inject(EnvironmentInjector), ); // Use factory-less way of creating a component. comp.viewContainerRef.createComponent(ChildB, {injector: environmentInjector}); fixture.detectChanges(); // Custom injector provides only `TOKEN_B`, // so `TOKEN_A` should be retrieved from the module injector. expect(getElementText(fixture.nativeElement.parentNode)).toContain( '[TokenA - Value] [TokenB - CustomValue]', ); // Use factory-based API to compare the output with the factory-less one. const factoryBasedChildB = createComponent(ChildB, {environmentInjector}); fixture.detectChanges(); // Custom injector provides only `TOKEN_B`, // so `TOKEN_A` should be retrieved from the module injector expect(getElementText(fixture.nativeElement.parentNode)).toContain( '[TokenA - Value] [TokenB - CustomValue]', ); }); it('should throw if class without @Component decorator is used as Component type', () => { class MyClassWithoutComponentDecorator {} const createComponent = () => { fixture.componentInstance.viewContainerRef.createComponent( MyClassWithoutComponentDecorator, ); }; expect(createComponent).toThrowError( /Provided Component class doesn't contain Component definition./, ); }); describe('`options` argument handling', () => { it('should work correctly when an empty object is provided', () => { fixture.componentInstance.viewContainerRef.createComponent(ChildA, {}); expect(fixture.nativeElement.parentNode.textContent).toContain('[Child Component A]'); }); it('should take provided `options` arguments into account', () => { const {viewContainerRef, ngModuleRef, injector} = fixture.componentInstance; viewContainerRef.createComponent(ChildA); const projectableNode = document.createElement('div'); const textNode = document.createTextNode('[Projectable Node]'); projectableNode.appendChild(textNode); const projectableNodes = [[projectableNode]]; // Insert ChildB in front of ChildA (since index = 0) viewContainerRef.createComponent(ChildB, { index: 0, injector, ngModuleRef, projectableNodes, }); fixture.detectChanges(); expect(getElementText(fixture.nativeElement.parentNode)).toContain( '[Child Component B] ' + '[Projectable Node] ' + '[TokenA - Value] ' + '[TokenB - Value] ' + '[Child Component A]', ); }); }); }); });
010151
scribe('root view container ref', () => { let containerEl: HTMLElement | null = null; beforeEach(() => (containerEl = null)); /** * Creates a new test component renderer instance that wraps the root element * in another element. This allows us to test if elements have been inserted into * the parent element of the root component. */ function createTestComponentRenderer(document: any): TestComponentRenderer { return { insertRootElement(rootElementId: string) { const rootEl = document.createElement('div'); rootEl.id = rootElementId; containerEl = document.createElement('div'); document.body.appendChild(containerEl); containerEl!.appendChild(rootEl); }, removeAllRootElements() { containerEl?.remove(); }, }; } const TEST_COMPONENT_RENDERER = { provide: TestComponentRenderer, useFactory: createTestComponentRenderer, deps: [DOCUMENT], }; it('should check bindings for components dynamically created by root component', () => { @Component({ selector: 'dynamic-cmpt-with-bindings', template: `check count: {{checkCount}}`, standalone: false, }) class DynamicCompWithBindings implements DoCheck { checkCount = 0; ngDoCheck() { this.checkCount++; } } @Component({ template: ``, standalone: false, }) class TestComp { constructor(public vcRef: ViewContainerRef) {} } TestBed.configureTestingModule({ declarations: [TestComp, DynamicCompWithBindings], providers: [TEST_COMPONENT_RENDERER], }); const fixture = TestBed.createComponent(TestComp); const {vcRef} = fixture.componentInstance; fixture.detectChanges(); expect(containerEl!.childNodes.length).toBe(2); expect(containerEl!.childNodes[1].nodeType).toBe(Node.COMMENT_NODE); expect((containerEl!.childNodes[0] as Element).tagName).toBe('DIV'); vcRef.createComponent(DynamicCompWithBindings); fixture.detectChanges(); expect(containerEl!.childNodes.length).toBe(3); expect(containerEl!.childNodes[1].textContent).toBe('check count: 1'); fixture.detectChanges(); expect(containerEl!.childNodes.length).toBe(3); expect(containerEl!.childNodes[1].textContent).toBe('check count: 2'); }); it('should create deep DOM tree immediately for dynamically created components', () => { @Component({ template: ``, standalone: false, }) class TestComp { constructor(public vcRef: ViewContainerRef) {} } @Component({ selector: 'child', template: `<div>{{name}}</div>`, standalone: false, }) class Child { name = 'text'; } @Component({ selector: 'dynamic-cmpt-with-children', template: `<child></child>`, standalone: false, }) class DynamicCompWithChildren {} TestBed.configureTestingModule({ declarations: [TestComp, DynamicCompWithChildren, Child], providers: [TEST_COMPONENT_RENDERER], }); const fixture = TestBed.createComponent(TestComp); const {vcRef} = fixture.componentInstance; fixture.detectChanges(); expect(containerEl!.childNodes.length).toBe(2); expect(containerEl!.childNodes[1].nodeType).toBe(Node.COMMENT_NODE); expect((containerEl!.childNodes[0] as Element).tagName).toBe('DIV'); vcRef.createComponent(DynamicCompWithChildren); expect(containerEl!.childNodes.length).toBe(3); expect(getElementHtml(containerEl!.childNodes[1] as Element)).toBe( '<child><div></div></child>', ); fixture.detectChanges(); expect(containerEl!.childNodes.length).toBe(3); expect(getElementHtml(containerEl!.childNodes[1] as Element)).toBe( `<child><div>text</div></child>`, ); }); }); }); @Component({ template: ` <ng-template #tplRef let-name>{{name}}</ng-template> <p vcref [tplRef]="tplRef"></p> `, standalone: false, }) class EmbeddedViewInsertionComp {} @Directive({ selector: '[vcref]', standalone: false, }) class VCRefDirective { @Input() tplRef: TemplateRef<any> | undefined; @Input() name: string = ''; // Injecting the ViewContainerRef to create a dynamic container in which // embedded views will be created constructor( public vcref: ViewContainerRef, public elementRef: ElementRef, ) {} createView(s: string, index?: number): EmbeddedViewRef<any> { if (!this.tplRef) { throw new Error('No template reference passed to directive.'); } return this.vcref.createEmbeddedView(this.tplRef, {$implicit: s}, index); } } @Component({ selector: `embedded-cmp-with-ngcontent`, template: `<ng-content></ng-content><hr><ng-content></ng-content>`, standalone: false, }) class EmbeddedComponentWithNgContent {} @Component({ selector: 'view-container-ref-comp', template: ` <ng-template #ref0>0</ng-template> <ng-template #ref1>1</ng-template> <ng-template #ref2>2</ng-template> `, standalone: false, }) class ViewContainerRefComp { @ViewChildren(TemplateRef) templates!: QueryList<TemplateRef<any>>; constructor(public vcr: ViewContainerRef) {} } @Component({ selector: 'view-container-ref-app', template: ` <view-container-ref-comp></view-container-ref-comp> `, standalone: false, }) class ViewContainerRefApp { @ViewChild(ViewContainerRefComp) vcrComp!: ViewContainerRefComp; } @Directive({ selector: '[structDir]', standalone: false, }) export class StructDir { constructor( private vcref: ViewContainerRef, private tplRef: TemplateRef<any>, ) {} create() { this.vcref.createEmbeddedView(this.tplRef); } destroy() { this.vcref.clear(); } } @Component({ selector: 'destroy-cases', template: ` `, standalone: false, }) class DestroyCasesComp { @ViewChildren(StructDir) structDirs!: QueryList<StructDir>; } @Directive({ selector: '[constructorDir]', standalone: false, }) class ConstructorDir { constructor(vcref: ViewContainerRef, tplRef: TemplateRef<any>) { vcref.createEmbeddedView(tplRef); } } @Component({ selector: 'constructor-app', template: ` <div *constructorDir> <span *constructorDir #foo></span> </div> `, standalone: false, }) class ConstructorApp { @ViewChild('foo', {static: true}) foo!: ElementRef; } @Component({ selector: 'constructor-app-with-queries', template: ` <ng-template constructorDir #foo> <div #foo></div> </ng-template> `, standalone: false, }) class ConstructorAppWithQueries { @ViewChild('foo', {static: true}) foo!: TemplateRef<any>; }
010184
describe('afterNextRender', () => { it('should run with the correct timing', () => { @Component({ selector: 'dynamic-comp', standalone: false, }) class DynamicComp { afterRenderCount = 0; constructor() { afterNextRender(() => { this.afterRenderCount++; }); } } @Component({ selector: 'comp', standalone: false, }) class Comp { afterRenderCount = 0; changeDetectorRef = inject(ChangeDetectorRef); viewContainerRef = inject(ViewContainerRef); constructor() { afterNextRender(() => { this.afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); const component = createAndAttachComponent(Comp); const compInstance = component.instance; const viewContainerRef = compInstance.viewContainerRef; const dynamicCompRef = viewContainerRef.createComponent(DynamicComp); // It hasn't run at all expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(0); // Running change detection at the dynamicCompRef level dynamicCompRef.changeDetectorRef.detectChanges(); expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(0); // Running change detection at the compInstance level compInstance.changeDetectorRef.detectChanges(); expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(0); // Running change detection at the Application level TestBed.inject(ApplicationRef).tick(); expect(dynamicCompRef.instance.afterRenderCount).toBe(1); expect(compInstance.afterRenderCount).toBe(1); // Running change detection after removing view. viewContainerRef.remove(); TestBed.inject(ApplicationRef).tick(); expect(dynamicCompRef.instance.afterRenderCount).toBe(1); expect(compInstance.afterRenderCount).toBe(1); }); it('should not run until views have stabilized', async () => { // This test uses two components, a Reader and Writer, and arranges CD so that Reader // is checked, and then Writer makes Reader dirty again. An `afterNextRender` should not run // until Reader has been fully refreshed. TestBed.configureTestingModule(COMMON_CONFIGURATION); const appRef = TestBed.inject(ApplicationRef); const counter = signal(0); @Component({standalone: true, template: '{{counter()}}'}) class Reader { counter = counter; } @Component({standalone: true, template: ''}) class Writer { ngAfterViewInit(): void { counter.set(1); } } const ref = createAndAttachComponent(Reader); createAndAttachComponent(Writer); let textAtAfterRender: string = ''; afterNextRender( () => { // Reader should've been fully refreshed, so capture its template state at this moment. textAtAfterRender = ref.location.nativeElement.innerHTML; }, {injector: appRef.injector}, ); await appRef.whenStable(); expect(textAtAfterRender).toBe('1'); }); it('should run all hooks after outer change detection', () => { let log: string[] = []; @Component({ selector: 'child-comp', standalone: false, }) class ChildComp { constructor() { afterNextRender(() => { log.push('child-comp'); }); } } @Component({ selector: 'parent', template: `<child-comp></child-comp>`, standalone: false, }) class ParentComp { changeDetectorRef = inject(ChangeDetectorRef); constructor() { afterNextRender(() => { log.push('parent-comp'); }); } ngOnInit() { log.push('pre-cd'); this.changeDetectorRef.detectChanges(); log.push('post-cd'); } } TestBed.configureTestingModule({ declarations: [ChildComp, ParentComp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(ParentComp); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual(['pre-cd', 'post-cd', 'parent-comp', 'child-comp']); }); it('should unsubscribe when calling destroy', () => { let hookRef: AfterRenderRef | null = null; let afterRenderCount = 0; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { hookRef = afterNextRender(() => { afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); expect(afterRenderCount).toBe(0); hookRef!.destroy(); TestBed.inject(ApplicationRef).tick(); expect(afterRenderCount).toBe(0); }); it('should throw if called recursively', () => { class RethrowErrorHandler extends ErrorHandler { override handleError(error: any): void { throw error; } } @Component({ selector: 'comp', standalone: false, }) class Comp { appRef = inject(ApplicationRef); injector = inject(EnvironmentInjector); ngOnInit() { afterNextRender( () => { this.appRef.tick(); }, {injector: this.injector}, ); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, providers: [ {provide: ErrorHandler, useClass: RethrowErrorHandler}, ...COMMON_CONFIGURATION.providers, ], }); createAndAttachComponent(Comp); expect(() => TestBed.inject(ApplicationRef).tick()).toThrowError( /ApplicationRef.tick is called recursively/, ); }); it('should defer nested hooks to the next cycle', () => { let outerHookCount = 0; let innerHookCount = 0; @Component({ selector: 'comp', standalone: false, }) class Comp { injector = inject(Injector); constructor() { afterNextRender(() => { outerHookCount++; afterNextRender( () => { innerHookCount++; }, {injector: this.injector}, ); }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); // It hasn't run at all expect(outerHookCount).toBe(0); expect(innerHookCount).toBe(0); // Running change detection (first time) TestBed.inject(ApplicationRef).tick(); expect(outerHookCount).toBe(1); expect(innerHookCount).toBe(0); // Running change detection (second time) TestBed.inject(ApplicationRef).tick(); expect(outerHookCount).toBe(1); expect(innerHookCount).toBe(1); // Running change detection (third time) TestBed.inject(ApplicationRef).tick(); expect(outerHookCount).toBe(1); expect(innerHookCount).toBe(1); }); it('should run outside of the Angular zone', () => { const zoneLog: boolean[] = []; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { afterNextRender(() => { zoneLog.push(NgZone.isInAngularZone()); }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); expect(zoneLog).toEqual([]); TestBed.inject(NgZone).run(() => { TestBed.inject(ApplicationRef).tick(); expect(zoneLog).toEqual([false]); }); }); it('should propagate errors to the ErrorHandler', () => { const log: string[] = []; class FakeErrorHandler extends ErrorHandler { override handleError(error: any): void { log.push((error as Error).message); } } @Component({ template: '', standalone: false, }) class Comp { constructor() { afterNextRender(() => { log.push('pass 1'); }); afterNextRender(() => { throw new Error('fail 1'); }); afterNextRender(() => { log.push('pass 2'); }); afterNextRender(() => { throw new Error('fail 2'); }); } } TestBed.configureTestingModule({ declarations: [Comp], providers: [COMMON_PROVIDERS, {provide: ErrorHandler, useClass: FakeErrorHandler}], }); createAndAttachComponent(Comp); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual(['pass 1', 'fail 1', 'pass 2', 'fail 2']); });
010186
it('should destroy after the hook has run', () => { let hookRef: AfterRenderRef | null = null; let afterRenderCount = 0; @Component({selector: 'comp', standalone: false}) class Comp { constructor() { hookRef = afterNextRender(() => { afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); const appRef = TestBed.inject(ApplicationRef); const destroySpy = spyOn(hookRef!, 'destroy').and.callThrough(); expect(afterRenderCount).toBe(0); expect(destroySpy).not.toHaveBeenCalled(); // Run once and ensure that it was called and then cleaned up. appRef.tick(); expect(afterRenderCount).toBe(1); expect(destroySpy).toHaveBeenCalledTimes(1); // Make sure we're not retaining it. appRef.tick(); expect(afterRenderCount).toBe(1); expect(destroySpy).toHaveBeenCalledTimes(1); }); }); describe('server', () => { const COMMON_CONFIGURATION = { providers: [{provide: PLATFORM_ID, useValue: PLATFORM_SERVER_ID}], }; describe('afterRender', () => { it('should not run', () => { let afterRenderCount = 0; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { afterRender(() => { afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); TestBed.inject(ApplicationRef).tick(); expect(afterRenderCount).toBe(0); }); }); describe('afterNextRender', () => { it('should not run', () => { let afterRenderCount = 0; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { afterNextRender(() => { afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); TestBed.inject(ApplicationRef).tick(); expect(afterRenderCount).toBe(0); }); }); }); });
010195
() => { function getElementHtml(element: HTMLElement) { return element.innerHTML .replace(/<!--(\W|\w)*?-->/g, '') .replace(/\sng-reflect-\S*="[^"]*"/g, ''); } it('should project content', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: '<child>content</child>', standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe(`<child><div>content</div></child>`); }); it('should project content when <ng-content> is at a template root', () => { @Component({ selector: 'child', template: '<ng-content></ng-content>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: '<child>content</child>', standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe(`<child>content</child>`); }); it('should project content with siblings', () => { @Component({ selector: 'child', template: '<ng-content></ng-content>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child>before<div>content</div>after</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe(`<child>before<div>content</div>after</child>`); }); it('should be able to re-project content', () => { @Component({ selector: 'grand-child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class GrandChild {} @Component({ selector: 'child', template: `<grand-child><ng-content></ng-content></grand-child>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><b>Hello</b>World!</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child, GrandChild]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe( '<child><grand-child><div><b>Hello</b>World!</div></grand-child></child>', ); }); it('should project components', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'projected-comp', template: 'content', standalone: false, }) class ProjectedComp {} @Component({ selector: 'parent', template: `<child><projected-comp></projected-comp></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child, ProjectedComp]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe( '<child><div><projected-comp>content</projected-comp></div></child>', ); }); it('should project components that have their own projection', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'projected-comp', template: `<p><ng-content></ng-content></p>`, standalone: false, }) class ProjectedComp {} @Component({ selector: 'parent', template: ` <child> <projected-comp><div>Some content</div>Other content</projected-comp> </child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child, ProjectedComp]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe( `<child><div><projected-comp><p><div>Some content</div>Other content</p></projected-comp></div></child>`, ); }); it('should project with multiple instances of a component with projection', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'projected-comp', template: `Before<ng-content></ng-content>After`, standalone: false, }) class ProjectedComp {} @Component({ selector: 'parent', template: ` <child> <projected-comp><div>A</div><p>123</p></projected-comp> <projected-comp><div>B</div><p>456</p></projected-comp> </child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child, ProjectedComp]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe( '<child><div>' + '<projected-comp>Before<div>A</div><p>123</p>After</projected-comp>' + '<projected-comp>Before<div>B</div><p>456</p>After</projected-comp>' + '</div></child>', ); }); it('should re-project with multiple instances of a component with projection', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'projected-comp', template: `Before<ng-content></ng-content>After`, standalone: false, }) class ProjectedComp {} @Component({ selector: 'parent', template: ` <child> <projected-comp><div>A</div><ng-content></ng-content><p>123</p></projected-comp> <projected-comp><div>B</div><p>456</p></projected-comp> </child>`, standalone: false, }) class Parent {} @Component({ selector: 'app', template: ` <parent>**ABC**</parent> <parent>**DEF**</parent> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Parent, Child, ProjectedComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe( '<parent><child><div>' + '<projected-comp>Before<div>A</div>**ABC**<p>123</p>After</projected-comp>' + '<projected-comp>Before<div>B</div><p>456</p>After</projected-comp>' + '</div></child></parent>' + '<parent><child><div>' + '<projected-comp>Before<div>A</div>**DEF**<p>123</p>After</projected-comp>' + '<projected-comp>Before<div>B</div><p>456</p>After</projected-comp>' + '</div></child></parent>', ); }); it('should project into dynamic views (with createEmbeddedView)', () => { @Component({ selector: 'child', template: `Before-<ng-template [ngIf]="showing"><ng-content></ng-content></ng-template>-After`, standalone: false, }) class Child { showing = false; } @Component({ selector: 'parent', template: `<child><div>A</div>Some text</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child], imports: [CommonModule]}); const fixture = TestBed.createComponent(Parent); const childDebugEl = fixture.debugElement.query(By.directive(Child)); const childInstance = childDebugEl.injector.get(Child); const childElement = childDebugEl.nativeElement as HTMLElement; childInstance.showing = true; fixture.detectChanges(); expect(getElementHtml(childElement)).toBe(`Before-<div>A</div>Some text-After`); childInstance.showing = false; fixture.detectChanges(); expect(getElementHtml(childElement)).toBe(`Before--After`); childInstance.showing = true; fixture.detectChanges(); expect(getElementHtml(childElement)).toBe(`Before-<div>A</div>Some text-After`); });
010196
it('should project into dynamic views with specific selectors', () => { @Component({ selector: 'child', template: ` <ng-content></ng-content> Before- <ng-template [ngIf]="showing"> <ng-content select="div"></ng-content> </ng-template> -After`, standalone: false, }) class Child { showing = false; } @Component({ selector: 'parent', template: ` <child> <div>A</div> <span>B</span> </child> `, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child], imports: [CommonModule]}); const fixture = TestBed.createComponent(Parent); const childDebugEl = fixture.debugElement.query(By.directive(Child)); const childInstance = childDebugEl.injector.get(Child); childInstance.showing = true; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe( '<child><span>B</span> Before- <div>A</div> -After</child>', ); childInstance.showing = false; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe( '<child><span>B</span> Before- -After</child>', ); childInstance.showing = true; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe( '<child><span>B</span> Before- <div>A</div> -After</child>', ); }); it('should project if <ng-content> is in a template that has different declaration/insertion points', () => { @Component({ selector: 'comp', template: `<ng-template><ng-content></ng-content></ng-template>`, standalone: false, }) class Comp { @ViewChild(TemplateRef, {static: true}) template!: TemplateRef<any>; } @Directive({ selector: '[trigger]', standalone: false, }) class Trigger { @Input() trigger!: Comp; constructor(public vcr: ViewContainerRef) {} open() { this.vcr.createEmbeddedView(this.trigger.template); } } @Component({ selector: 'parent', template: ` <button [trigger]="comp"></button> <comp #comp>Some content</comp> `, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Trigger, Comp]}); const fixture = TestBed.createComponent(Parent); const trigger = fixture.debugElement.query(By.directive(Trigger)).injector.get(Trigger); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe(`<button></button><comp></comp>`); trigger.open(); expect(getElementHtml(fixture.nativeElement)).toBe( `<button></button>Some content<comp></comp>`, ); }); it('should project nodes into the last ng-content', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div> <span><ng-content></ng-content></span>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child>content</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child], imports: [CommonModule]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe( '<child><div></div><span>content</span></child>', ); }); // https://stackblitz.com/edit/angular-ceqmnw?file=src%2Fapp%2Fapp.component.ts it('should project nodes into the last ng-content unrolled by ngFor', () => { @Component({ selector: 'child', template: '<div *ngFor="let item of [1, 2]; let i = index">({{i}}):<ng-content></ng-content></div>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: '<child>content</child>', standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child], imports: [CommonModule]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe( '<child><div>(0):</div><div>(1):content</div></child>', ); }); it('should handle projected containers inside other containers', () => { @Component({ selector: 'nested-comp', template: `<div>Child content</div>`, standalone: false, }) class NestedComp {} @Component({ selector: 'root-comp', template: `<ng-content></ng-content>`, standalone: false, }) class RootComp {} @Component({ selector: 'my-app', template: ` <root-comp> <ng-container *ngFor="let item of items; last as last"> <nested-comp *ngIf="!last"></nested-comp> </ng-container> </root-comp> `, standalone: false, }) class MyApp { items = [1, 2]; } TestBed.configureTestingModule({ declarations: [MyApp, RootComp, NestedComp], imports: [CommonModule], }); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); // expecting # of divs to be (items.length - 1), since last element is filtered out by *ngIf, // this applies to all other assertions below expect(fixture.nativeElement.querySelectorAll('div').length).toBe(1); fixture.componentInstance.items = [3, 4, 5]; fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(2); fixture.componentInstance.items = [6, 7, 8, 9]; fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(3); }); it('should handle projection into element containers at the view root', () => { @Component({ selector: 'root-comp', template: ` <ng-template [ngIf]="show"> <ng-container> <ng-content></ng-content> </ng-container> </ng-template>`, standalone: false, }) class RootComp { @Input() show: boolean = true; } @Component({ selector: 'my-app', template: `<root-comp [show]="show"><div></div></root-comp> `, standalone: false, }) class MyApp { show = true; } TestBed.configureTestingModule({declarations: [MyApp, RootComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(1); fixture.componentInstance.show = false; fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(0); }); it('should handle projection of views with element containers at the root', () => { @Component({ selector: 'root-comp', template: `<ng-template [ngIf]="show"><ng-content></ng-content></ng-template>`, standalone: false, }) class RootComp { @Input() show: boolean = true; } @Component({ selector: 'my-app', template: `<root-comp [show]="show"><ng-container><div></div></ng-container></root-comp>`, standalone: false, }) class MyApp { show = true; } TestBed.configureTestingModule({declarations: [MyApp, RootComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(1); fixture.componentInstance.show = false; fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(0); }); it('should project ng-container at the content root', () => { @Component({ selector: 'child', template: `<ng-content></ng-content>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child> <ng-container> <ng-container>content</ng-container> </ng-container> </child> `, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe('<child>content</child>'); });
010198
describe('with selectors', () => { it('should project nodes using attribute selectors', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content select="span[title=toFirst]"></ng-content></div> <div id="second"><ng-content select="span[title=toSecond]"></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span title="toFirst">1</span><span title="toSecond">2</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span title="toFirst">1</span></div><div id="second"><span title="toSecond">2</span></div></child>', ); }); it('should project nodes using class selectors', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content select="span.toFirst"></ng-content></div> <div id="second"><ng-content select="span.toSecond"></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span class="toFirst">1</span><span class="toSecond">2</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span class="toFirst">1</span></div><div id="second"><span class="toSecond">2</span></div></child>', ); }); it('should project nodes using class selectors when element has multiple classes', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content select="span.toFirst"></ng-content></div> <div id="second"><ng-content select="span.toSecond"></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span class="other toFirst">1</span><span class="noise toSecond">2</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span class="other toFirst">1</span></div><div id="second"><span class="noise toSecond">2</span></div></child>', ); }); it('should project nodes into the first matching selector', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content select="span"></ng-content></div> <div id="second"><ng-content select="span.toSecond"></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span class="toFirst">1</span><span class="toSecond">2</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span class="toFirst">1</span><span class="toSecond">2</span></div><div id="second"></div></child>', ); }); it('should allow mixing ng-content with and without selectors', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content select="span.toFirst"></ng-content></div> <div id="second"><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span class="toFirst">1</span><span>remaining</span>more remaining</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span class="toFirst">1</span></div><div id="second"><span>remaining</span>more remaining</div></child>', ); }); it('should allow mixing ng-content with and without selectors - ng-content first', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content></ng-content></div> <div id="second"><ng-content select="span.toSecond"></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span>1</span><span class="toSecond">2</span>remaining</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span>1</span>remaining</div><div id="second"><span class="toSecond">2</span></div></child>', ); }); /** * Descending into projected content for selector-matching purposes is not supported * today: https://plnkr.co/edit/MYQcNfHSTKp9KvbzJWVQ?p=preview */ it('should not descend into re-projected content', () => { @Component({ selector: 'grand-child', template: `<ng-content select="span"></ng-content><hr><ng-content></ng-content>`, standalone: false, }) class GrandChild {} @Component({ selector: 'child', template: `<grand-child> <ng-content></ng-content> <span>in child template</span> </grand-child>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span>parent content</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [GrandChild, Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><grand-child><span>in child template</span><hr><span>parent content</span></grand-child></child>', ); }); it('should not descend into re-projected content', () => { @Component({ selector: 'card', template: `<ng-content select="[card-title]"></ng-content><hr><ng-content select="[card-content]"></ng-content>`, standalone: false, }) class Card {} @Component({ selector: 'card-with-title', template: `<card> <h1 card-title>Title</h1> <ng-content card-content></ng-content> </card>`, standalone: false, }) class CardWithTitle {} @Component({ selector: 'parent', template: `<card-with-title>content</card-with-title>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Card, CardWithTitle, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<card-with-title><card><h1 card-title="">Title</h1><hr>content</card></card-with-title>', ); }); it('should not match selectors against node having ngProjectAs attribute', () => { @Component({ selector: 'child', template: `<ng-content select="div"></ng-content>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><div ngProjectAs="span">should not project</div><div>should project</div></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div>should project</div></child>', ); }); // https://stackblitz.com/edit/angular-psokum?file=src%2Fapp%2Fapp.module.ts
010199
it('should project nodes where attribute selector matches a binding', () => { @Component({ selector: 'child', template: `<ng-content select="[title]"></ng-content>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span [title]="'Some title'">Has title</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><span title="Some title">Has title</span></child>', ); }); it('should match selectors against projected containers', () => { @Component({ selector: 'child', template: `<span><ng-content select="div"></ng-content></span>`, standalone: false, }) class Child {} @Component({ template: `<child><div *ngIf="value">content</div></child>`, standalone: false, }) class Parent { value = false; } TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.componentInstance.value = true; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><span><div>content</div></span></child>', ); }); }); it('should handle projected containers inside other containers', () => { @Component({ selector: 'child-comp', // template: '<ng-content></ng-content>', standalone: false, }) class ChildComp {} @Component({ selector: 'root-comp', // template: '<ng-content></ng-content>', standalone: false, }) class RootComp {} @Component({ selector: 'my-app', template: ` <root-comp> <ng-container *ngFor="let item of items; last as last"> <child-comp *ngIf="!last">{{ item }}|</child-comp> </ng-container> </root-comp> `, standalone: false, }) class MyApp { items: number[] = [1, 2, 3]; } TestBed.configureTestingModule({declarations: [ChildComp, RootComp, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); // expecting # of elements to be (items.length - 1), since last element is filtered out by // *ngIf, this applies to all other assertions below expect(fixture.nativeElement).toHaveText('1|2|'); fixture.componentInstance.items = [4, 5]; fixture.detectChanges(); expect(fixture.nativeElement).toHaveText('4|'); fixture.componentInstance.items = [6, 7, 8, 9]; fixture.detectChanges(); expect(fixture.nativeElement).toHaveText('6|7|8|'); }); it('should project content if the change detector has been detached', () => { @Component({ selector: 'my-comp', template: '<ng-content></ng-content>', standalone: false, }) class MyComp { constructor(changeDetectorRef: ChangeDetectorRef) { changeDetectorRef.detach(); } } @Component({ selector: 'my-app', template: ` <my-comp> <p>hello</p> </my-comp> `, standalone: false, }) class MyApp {} TestBed.configureTestingModule({declarations: [MyComp, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement).toHaveText('hello'); }); it('should support ngProjectAs with a various number of other bindings and attributes', () => { @Directive({ selector: '[color],[margin]', standalone: false, }) class ElDecorator { @Input() color?: string; @Input() margin?: number; } @Component({ selector: 'card', template: ` <ng-content select="[card-title]"></ng-content> --- <ng-content select="[card-subtitle]"></ng-content> --- <ng-content select="[card-content]"></ng-content> --- <ng-content select="[card-footer]"></ng-content> `, standalone: false, }) class Card {} @Component({ selector: 'card-with-title', template: ` <card> <h1 [color]="'red'" [margin]="10" ngProjectAs="[card-title]">Title</h1> <h2 xlink:href="google.com" ngProjectAs="[card-subtitle]">Subtitle</h2> <div style="font-color: blue;" ngProjectAs="[card-content]">content</div> <div [color]="'blue'" ngProjectAs="[card-footer]">footer</div> </card> `, standalone: false, }) class CardWithTitle {} TestBed.configureTestingModule({declarations: [Card, CardWithTitle, ElDecorator]}); const fixture = TestBed.createComponent(CardWithTitle); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Title --- Subtitle --- content --- footer'); }); it('should support ngProjectAs on elements (including <ng-content>)', () => { @Component({ selector: 'card', template: ` <ng-content select="[card-title]"></ng-content> --- <ng-content select="[card-content]"></ng-content> `, standalone: false, }) class Card {} @Component({ selector: 'card-with-title', template: ` <card> <h1 ngProjectAs="[card-title]">Title</h1> <ng-content ngProjectAs="[card-content]"></ng-content> </card> `, standalone: false, }) class CardWithTitle {} @Component({ selector: 'app', template: ` <card-with-title>content</card-with-title> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [Card, CardWithTitle, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Title --- content'); }); it('should not match multiple selectors in ngProjectAs', () => { @Component({ selector: 'card', template: ` <ng-content select="[card-title]"></ng-content> content `, standalone: false, }) class Card {} @Component({ template: ` <card> <h1 ngProjectAs="[non-existing-title-slot],[card-title]">Title</h1> </card> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [Card, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toEqual('Title content'); }); it('should preserve ngProjectAs and other attributes on projected element', () => { @Component({ selector: 'projector', template: `<ng-content select="projectMe"></ng-content>`, standalone: false, }) class Projector {} @Component({ template: ` <projector> <div ngProjectAs="projectMe" title="some title"></div> </projector> `, standalone: false, }) class Root {} TestBed.configureTestingModule({ declarations: [Root, Projector], }); const fixture = TestBed.createComponent(Root); fixture.detectChanges(); const projectedElement = fixture.debugElement.query(By.css('div')); const {ngProjectAs, title} = projectedElement.attributes; expect(ngProjectAs).toBe('projectMe'); expect(title).toBe('some title'); });
010203
it('should render the fallback content if content is not provided through projectableNodes', () => { @Component({ standalone: true, template: `<ng-content>One fallback</ng-content>|` + `<ng-content>Two fallback</ng-content>|<ng-content>Three fallback</ng-content>`, }) class Projection {} const hostElement = document.createElement('div'); const environmentInjector = TestBed.inject(EnvironmentInjector); const paragraph = document.createElement('p'); paragraph.textContent = 'override'; const projectableNodes = [[paragraph]]; const componentRef = createComponent(Projection, { hostElement, environmentInjector, projectableNodes, }); componentRef.changeDetectorRef.detectChanges(); expect(getElementHtml(hostElement)).toContain('<p>override</p>|Two fallback|Three fallback'); componentRef.destroy(); }); it('should render the content through projectableNodes along with fallback', () => { @Component({ standalone: true, template: `<ng-content>One fallback</ng-content>|` + `<ng-content>Two fallback</ng-content>|<ng-content>Three fallback</ng-content>`, }) class Projection {} const hostElement = document.createElement('div'); const environmentInjector = TestBed.inject(EnvironmentInjector); const paragraph = document.createElement('p'); paragraph.textContent = 'override'; const secondParagraph = document.createElement('p'); secondParagraph.textContent = 'override'; const projectableNodes = [[paragraph], [], [secondParagraph]]; const componentRef = createComponent(Projection, { hostElement, environmentInjector, projectableNodes, }); componentRef.changeDetectorRef.detectChanges(); expect(getElementHtml(hostElement)).toContain('<p>override</p>|Two fallback|<p>override</p>'); }); it('should render fallback content when ng-content is inside an ng-template', () => { @Component({ selector: 'projection', template: `<ng-container #ref/><ng-template #template><ng-content>Fallback</ng-content></ng-template>`, standalone: true, }) class Projection { @ViewChild('template') template!: TemplateRef<unknown>; @ViewChild('ref', {read: ViewContainerRef}) viewContainerRef!: ViewContainerRef; createContent() { this.viewContainerRef.createEmbeddedView(this.template); } } @Component({ standalone: true, imports: [Projection], template: `<projection/>`, }) class App { @ViewChild(Projection) projection!: Projection; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toContain(`<projection></projection>`); fixture.componentInstance.projection.createContent(); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toContain(`<projection>Fallback</projection>`); }); it('should render the fallback content when ng-content is re-projected', () => { @Component({ selector: 'inner-projection', template: ` <ng-content select="[inner-header]">Inner header fallback</ng-content> <ng-content select="[inner-footer]">Inner footer fallback</ng-content> `, standalone: true, }) class InnerProjection {} @Component({ selector: 'projection', template: ` <inner-projection> <ng-content select="[outer-header]" inner-header>Outer header fallback</ng-content> <ng-content select="[outer-footer]" inner-footer>Outer footer fallback</ng-content> </inner-projection> `, standalone: true, imports: [InnerProjection], }) class Projection {} @Component({ standalone: true, imports: [Projection], template: ` <projection> <span outer-header>Outer header override</span> </projection> `, }) class App {} const fixture = TestBed.createComponent(App); const content = getElementHtml(fixture.nativeElement); expect(content).toContain('Outer header override'); expect(content).toContain('Outer footer fallback'); }); it('should not instantiate directives inside the fallback content', () => { let creationCount = 0; @Component({ selector: 'fallback', standalone: true, template: 'Fallback', }) class Fallback { constructor() { creationCount++; } } @Component({ selector: 'projection', template: `<ng-content><fallback/></ng-content>`, standalone: true, imports: [Fallback], }) class Projection {} @Component({ standalone: true, imports: [Projection], template: `<projection>Hello</projection>`, }) class App {} const fixture = TestBed.createComponent(App); expect(creationCount).toBe(0); expect(getElementHtml(fixture.nativeElement)).toContain(`<projection>Hello</projection>`); }); it( 'should render the fallback content when an instance of a component that uses ' + 'fallback content is declared after one that does not', () => { @Component({ selector: 'projection', template: `<ng-content>Fallback</ng-content>`, standalone: true, }) class Projection {} @Component({ standalone: true, imports: [Projection], template: ` <projection>Content</projection> <projection/> `, }) class App {} const fixture = TestBed.createComponent(App); expect(getElementHtml(fixture.nativeElement)).toContain( '<projection>Content</projection><projection>Fallback</projection>', ); }, ); it( 'should render the fallback content when an instance of a component that uses ' + 'fallback content is declared before one that does not', () => { @Component({ selector: 'projection', template: `<ng-content>Fallback</ng-content>`, standalone: true, }) class Projection {} @Component({ standalone: true, imports: [Projection], template: ` <projection/> <projection>Content</projection> `, }) class App {} const fixture = TestBed.createComponent(App); expect(getElementHtml(fixture.nativeElement)).toContain( '<projection>Fallback</projection><projection>Content</projection>', ); }, ); }); });
010242
describe('OnPush components with signals', () => { it('marks view dirty', () => { @Component({ template: `{{value()}}{{incrementTemplateExecutions()}}`, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, }) class OnPushCmp { numTemplateExecutions = 0; value = signal('initial'); incrementTemplateExecutions() { this.numTemplateExecutions++; return ''; } } const fixture = TestBed.createComponent(OnPushCmp); const instance = fixture.componentInstance; fixture.detectChanges(); expect(instance.numTemplateExecutions).toBe(1); expect(fixture.nativeElement.textContent.trim()).toEqual('initial'); fixture.detectChanges(); // Should not be dirty, should not execute template expect(instance.numTemplateExecutions).toBe(1); instance.value.set('new'); fixture.detectChanges(); expect(instance.numTemplateExecutions).toBe(2); expect(instance.value()).toBe('new'); }); it("does not refresh a component when a signal notifies but isn't actually updated", () => { @Component({ template: `{{memo()}}{{incrementTemplateExecutions()}}`, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, }) class OnPushCmp { numTemplateExecutions = 0; value = signal({value: 'initial'}); memo = computed(() => this.value().value, {equal: Object.is}); incrementTemplateExecutions() { this.numTemplateExecutions++; return ''; } } const fixture = TestBed.createComponent(OnPushCmp); const instance = fixture.componentInstance; fixture.detectChanges(); expect(instance.numTemplateExecutions).toBe(1); expect(fixture.nativeElement.textContent.trim()).toEqual('initial'); instance.value.update((v) => ({...v})); fixture.detectChanges(); expect(instance.numTemplateExecutions).toBe(1); instance.value.update((v) => ({value: 'new'})); fixture.detectChanges(); expect(instance.numTemplateExecutions).toBe(2); expect(fixture.nativeElement.textContent.trim()).toEqual('new'); }); it('should not mark components as dirty when signal is read in a constructor of a child component', () => { const state = signal('initial'); @Component({ selector: 'child', template: `child`, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, }) class ChildReadingSignalCmp { constructor() { state(); } } @Component({ template: ` {{incrementTemplateExecutions()}} <!-- Template constructed to execute child component constructor in the update pass of a host component --> <ng-template [ngIf]="true"><child></child></ng-template> `, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [NgIf, ChildReadingSignalCmp], }) class OnPushCmp { numTemplateExecutions = 0; incrementTemplateExecutions() { this.numTemplateExecutions++; return ''; } } const fixture = TestBed.createComponent(OnPushCmp); const instance = fixture.componentInstance; fixture.detectChanges(); expect(instance.numTemplateExecutions).toBe(1); expect(fixture.nativeElement.textContent.trim()).toEqual('child'); // The "state" signal is not accesses in the template's update function anywhere so it // shouldn't mark components as dirty / impact change detection. state.set('new'); fixture.detectChanges(); expect(instance.numTemplateExecutions).toBe(1); }); it('should not mark components as dirty when signal is read in an input of a child component', () => { const state = signal('initial'); @Component({ selector: 'with-input-setter', standalone: true, template: '{{test}}', }) class WithInputSetter { test = ''; @Input() set testInput(newValue: string) { this.test = state() + ':' + newValue; } } @Component({ template: ` {{incrementTemplateExecutions()}} <!-- Template constructed to execute child component constructor in the update pass of a host component --> <ng-template [ngIf]="true"><with-input-setter [testInput]="'input'" /></ng-template> `, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [NgIf, WithInputSetter], }) class OnPushCmp { numTemplateExecutions = 0; incrementTemplateExecutions() { this.numTemplateExecutions++; return ''; } } const fixture = TestBed.createComponent(OnPushCmp); const instance = fixture.componentInstance; fixture.detectChanges(); expect(instance.numTemplateExecutions).toBe(1); expect(fixture.nativeElement.textContent.trim()).toEqual('initial:input'); // The "state" signal is not accesses in the template's update function anywhere so it // shouldn't mark components as dirty / impact change detection. state.set('new'); fixture.detectChanges(); expect(instance.numTemplateExecutions).toBe(1); expect(fixture.nativeElement.textContent.trim()).toEqual('initial:input'); }); it('should not mark components as dirty when signal is read in a query result setter', () => { const state = signal('initial'); @Component({ selector: 'with-query-setter', standalone: true, template: '<div #el>child</div>', }) class WithQuerySetter { el: unknown; @ViewChild('el', {static: true}) set elQuery(result: unknown) { // read a signal in a setter state(); this.el = result; } } @Component({ template: ` {{incrementTemplateExecutions()}} <!-- Template constructed to execute child component constructor in the update pass of a host component --> <ng-template [ngIf]="true"><with-query-setter /></ng-template> `, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [NgIf, WithQuerySetter], }) class OnPushCmp { numTemplateExecutions = 0; incrementTemplateExecutions() { this.numTemplateExecutions++; return ''; } } const fixture = TestBed.createComponent(OnPushCmp); const instance = fixture.componentInstance; fixture.detectChanges(); expect(instance.numTemplateExecutions).toBe(1); expect(fixture.nativeElement.textContent.trim()).toEqual('child'); // The "state" signal is not accesses in the template's update function anywhere so it // shouldn't mark components as dirty / impact change detection. state.set('new'); fixture.detectChanges(); expect(instance.numTemplateExecutions).toBe(1); }); it('can read a signal in a host binding in root view', () => { const useBlue = signal(false); @Component({ template: `{{incrementTemplateExecutions()}}`, selector: 'child', host: {'[class.blue]': 'useBlue()'}, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, }) class MyCmp { useBlue = useBlue; numTemplateExecutions = 0; incrementTemplateExecutions() { this.numTemplateExecutions++; return ''; } } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).not.toContain('blue'); expect(fixture.componentInstance.numTemplateExecutions).toBe(1); useBlue.set(true); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('blue'); expect(fixture.componentInstance.numTemplateExecutions).toBe(1); }); it('can read a signal in a host binding', () => { @Component({ template: `{{incrementTemplateExecutions()}}`, selector: 'child', host: {'[class.blue]': 'useBlue()'}, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, }) class ChildCmp { useBlue = signal(false); numTemplateExecutions = 0; incrementTemplateExecutions() { this.numTemplateExecutions++; return ''; } } @Component({ template: `<child />`, changeDetection: ChangeDetectionStrategy.OnPush, imports: [ChildCmp], standalone: true, }) class ParentCmp {} const fixture = TestBed.createComponent(ParentCmp); const child = fixture.debugElement.query((p) => p.componentInstance instanceof ChildCmp); const childInstance = child.componentInstance as ChildCmp; fixture.detectChanges(); expect(childInstance.numTemplateExecutions).toBe(1); expect(child.nativeElement.outerHTML).not.toContain('blue'); childInstance.useBlue.set(true); fixture.detectChanges(); // We should not re-execute the child template. It didn't change, the host bindings did. expect(childInstance.numTemplateExecutions).toBe(1); expect(child.nativeElement.outerHTML).toContain('blue'); });
010243
it('can have signals in both template and host bindings', () => { @Component({ template: ``, selector: 'child', host: {'[class.blue]': 'useBlue()'}, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, }) class ChildCmp { useBlue = signal(false); } @Component({ template: `<child /> {{parentSignalValue()}}`, changeDetection: ChangeDetectionStrategy.OnPush, imports: [ChildCmp], standalone: true, selector: 'parent', }) class ParentCmp { parentSignalValue = signal('initial'); } // Wrapper component so we can effectively test ParentCmp being marked dirty @Component({ template: `<parent />`, changeDetection: ChangeDetectionStrategy.OnPush, imports: [ParentCmp], standalone: true, }) class TestWrapper {} const fixture = TestBed.createComponent(TestWrapper); const parent = fixture.debugElement.query((p) => p.componentInstance instanceof ParentCmp) .componentInstance as ParentCmp; const child = fixture.debugElement.query((p) => p.componentInstance instanceof ChildCmp) .componentInstance as ChildCmp; fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('initial'); expect(fixture.nativeElement.outerHTML).not.toContain('blue'); child.useBlue.set(true); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('blue'); // Set the signal in the parent again and ensure it gets updated parent.parentSignalValue.set('new'); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('new'); // Set the signal in the child host binding again and ensure it is still updated child.useBlue.set(false); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).not.toContain('blue'); }); it('should be able to write to signals during change-detecting a given template, in advance()', () => { const counter = signal(0); @Directive({ standalone: true, selector: '[misunderstood]', }) class MisunderstoodDir { ngOnInit(): void { counter.update((c) => c + 1); } } @Component({ selector: 'test-component', standalone: true, imports: [MisunderstoodDir], template: ` {{counter()}}<div misunderstood></div>{{ 'force advance()' }} `, }) class TestCmp { counter = counter; } const fixture = TestBed.createComponent(TestCmp); // CheckNoChanges should not throw ExpressionChanged error // and signal value is updated to latest value with 1 `detectChanges` fixture.detectChanges(); expect(fixture.nativeElement.innerText).toContain('1'); expect(fixture.nativeElement.innerText).toContain('force advance()'); }); it('should allow writing to signals during change-detecting a given template, at the end', () => { const counter = signal(0); @Directive({ standalone: true, selector: '[misunderstood]', }) class MisunderstoodDir { ngOnInit(): void { counter.update((c) => c + 1); } } @Component({ selector: 'test-component', standalone: true, imports: [MisunderstoodDir], template: ` {{counter()}}<div misunderstood></div> `, }) class TestCmp { counter = counter; } const fixture = TestBed.createComponent(TestCmp); // CheckNoChanges should not throw ExpressionChanged error // and signal value is updated to latest value with 1 `detectChanges` fixture.detectChanges(); expect(fixture.nativeElement.innerText).toBe('1'); }); it('should allow writing to signals in afterViewInit', () => { @Component({ template: '{{loading()}}', standalone: true, }) class MyComp { loading = signal(true); // Classic example of what would have caused ExpressionChanged...Error ngAfterViewInit() { this.loading.set(false); } } const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.nativeElement.innerText).toBe('false'); }); it('does not refresh view if signal marked dirty but did not change', () => { const val = signal('initial', {equal: () => true}); @Component({ template: '{{val()}}{{incrementChecks()}}', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, }) class App { val = val; templateExecutions = 0; incrementChecks() { this.templateExecutions++; } } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.templateExecutions).toBe(1); expect(fixture.nativeElement.innerText).toContain('initial'); val.set('new'); fixture.detectChanges(); expect(fixture.componentInstance.templateExecutions).toBe(1); expect(fixture.nativeElement.innerText).toContain('initial'); });
010264
('attribute tokens', () => { it('should be able to provide an attribute token', () => { const TOKEN = new InjectionToken<string>('Some token'); function factory(token: string): string { return token + ' with factory'; } @Component({ selector: 'my-comp', template: '...', providers: [ { provide: TOKEN, deps: [[new Attribute('token')]], useFactory: factory, }, ], standalone: false, }) class MyComp { constructor(@Inject(TOKEN) readonly token: string) {} } @Component({ template: `<my-comp token='token'></my-comp>`, standalone: false, }) class WrapperComp { @ViewChild(MyComp) myComp!: MyComp; } TestBed.configureTestingModule({declarations: [MyComp, WrapperComp]}); const fixture = TestBed.createComponent(WrapperComp); fixture.detectChanges(); expect(fixture.componentInstance.myComp.token).toBe('token with factory'); }); }); describe('inject()', () => { it('should work in a directive constructor', () => { const TOKEN = new InjectionToken<string>('TOKEN'); @Component({ standalone: true, selector: 'test-cmp', template: '{{value}}', providers: [{provide: TOKEN, useValue: 'injected value'}], }) class TestCmp { value: string; constructor() { this.value = inject(TOKEN); } } const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('injected value'); }); it('should work in a service constructor when the service is provided on a directive', () => { const TOKEN = new InjectionToken<string>('TOKEN'); @Injectable() class Service { value: string; constructor() { this.value = inject(TOKEN); } } @Component({ standalone: true, selector: 'test-cmp', template: '{{service.value}}', providers: [Service, {provide: TOKEN, useValue: 'injected value'}], }) class TestCmp { constructor(readonly service: Service) {} } const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('injected value'); }); it('should be able to inject special tokens like ChangeDetectorRef', () => { const TOKEN = new InjectionToken<string>('TOKEN'); @Component({ standalone: true, selector: 'test-cmp', template: '{{value}}', }) class TestCmp { cdr = inject(ChangeDetectorRef); value = 'before'; } const fixture = TestBed.createComponent(TestCmp); fixture.componentInstance.value = 'after'; fixture.componentInstance.cdr.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('after'); }); it('should work in a service constructor', () => { const TOKEN = new InjectionToken<string>('TOKEN', { providedIn: 'root', factory: () => 'injected value', }); @Injectable({providedIn: 'root'}) class Service { value: string; constructor() { this.value = inject(TOKEN); } } const service = TestBed.inject(Service); expect(service.value).toEqual('injected value'); }); it('should work in a useFactory definition for a service', () => { const TOKEN = new InjectionToken<string>('TOKEN', { providedIn: 'root', factory: () => 'injected value', }); @Injectable({ providedIn: 'root', useFactory: () => new Service(inject(TOKEN)), }) class Service { constructor(readonly value: string) {} } expect(TestBed.inject(Service).value).toEqual('injected value'); }); it('should work for field injection', () => { const TOKEN = new InjectionToken<string>('TOKEN', { providedIn: 'root', factory: () => 'injected value', }); @Injectable({providedIn: 'root'}) class Service { value = inject(TOKEN); } const service = TestBed.inject(Service); expect(service.value).toEqual('injected value'); }); it('should not give non-node services access to the node context', () => { const TOKEN = new InjectionToken<string>('TOKEN'); @Injectable({providedIn: 'root'}) class Service { value: string; constructor() { this.value = inject(TOKEN, InjectFlags.Optional) ?? 'default value'; } } @Component({ standalone: true, selector: 'test-cmp', template: '{{service.value}}', providers: [{provide: TOKEN, useValue: 'injected value'}], }) class TestCmp { service: Service; constructor() { // `Service` is injected starting from the component context, where `inject` is // `ɵɵdirectiveInject` under the hood. However, this should reach the root injector which // should _not_ use `ɵɵdirectiveInject` to inject dependencies of `Service`, so `TOKEN` // should not be visible to `Service`. this.service = inject(Service); } } const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('default value'); }); describe('with an options object argument', () => { it('should be able to optionally inject a service', () => { const TOKEN = new InjectionToken<string>('TOKEN'); @Component({ standalone: true, template: '', }) class TestCmp { value = inject(TOKEN, {optional: true}); } expect(TestBed.createComponent(TestCmp).componentInstance.value).toBeNull(); }); it('should be able to use skipSelf injection', () => { const TOKEN = new InjectionToken<string>('TOKEN', { providedIn: 'root', factory: () => 'from root', }); @Component({ standalone: true, template: '', providers: [{provide: TOKEN, useValue: 'from component'}], }) class TestCmp { value = inject(TOKEN, {skipSelf: true}); } expect(TestBed.createComponent(TestCmp).componentInstance.value).toEqual('from root'); }); it('should be able to use self injection', () => { const TOKEN = new InjectionToken<string>('TOKEN', { providedIn: 'root', factory: () => 'from root', }); @Component({ standalone: true, template: '', }) class TestCmp { value = inject(TOKEN, {self: true, optional: true}); } expect(TestBed.createComponent(TestCmp).componentInstance.value).toBeNull(); }); it('should be able to use host injection', () => { const TOKEN = new InjectionToken<string>('TOKEN'); @Component({ standalone: true, selector: 'child', template: '{{value}}', }) class ChildCmp { value = inject(TOKEN, {host: true, optional: true}) ?? 'not found'; } @Component({ standalone: true, imports: [ChildCmp], template: '<child></child>', providers: [{provide: TOKEN, useValue: 'from parent'}], encapsulation: ViewEncapsulation.None, }) class ParentCmp {} const fixture = TestBed.createComponent(ParentCmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<child>not found</child>'); }); it('should not indicate it returns null when optional is explicitly false', () => { const TOKEN = new InjectionToken<string>('TOKEN', { providedIn: 'root', factory: () => 'from root', }); @Component({ standalone: true, template: '', }) class TestCmp { // TypeScript will check if this assignment is legal, which won't be the case if // inject() erroneously returns a `string|null` type here. value: string = inject(TOKEN, {optional: false}); } expect(TestBed.createComponent(TestCmp).componentInstance.value).toEqual('from root'); }); }); }); describe
010287
/*! * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Component, Directive, effect, ErrorHandler, EventEmitter, output, signal, } from '@angular/core'; import {outputFromObservable} from '@angular/core/rxjs-interop'; import {setUseMicrotaskEffectsByDefault} from '@angular/core/src/render3/reactivity/effect'; import {TestBed} from '@angular/core/testing'; import {BehaviorSubject, Observable, share, Subject} from 'rxjs'; describe('output() function', () => { let prev: boolean; beforeEach(() => { prev = setUseMicrotaskEffectsByDefault(false); }); afterEach(() => setUseMicrotaskEffectsByDefault(prev)); it('should support emitting values', () => { @Directive({ selector: '[dir]', standalone: true, }) class Dir { onBla = output<number>(); } @Component({ template: '<div dir (onBla)="values.push($event)"></div>', standalone: true, imports: [Dir], }) class App { values: number[] = []; } const fixture = TestBed.createComponent(App); const dir = fixture.debugElement.children[0].injector.get(Dir); fixture.detectChanges(); expect(fixture.componentInstance.values).toEqual([]); dir.onBla.emit(1); dir.onBla.emit(2); expect(fixture.componentInstance.values).toEqual([1, 2]); }); it('should support emitting void values', () => { @Directive({ selector: '[dir]', standalone: true, }) class Dir { onBla = output(); } @Component({ template: '<div dir (onBla)="count = count + 1"></div>', standalone: true, imports: [Dir], }) class App { count = 0; } const fixture = TestBed.createComponent(App); const dir = fixture.debugElement.children[0].injector.get(Dir); fixture.detectChanges(); expect(fixture.componentInstance.count).toEqual(0); dir.onBla.emit(); dir.onBla.emit(); expect(fixture.componentInstance.count).toEqual(2); }); it('should error when emitting to a destroyed output', () => { @Directive({ selector: '[dir]', standalone: true, }) class Dir { onBla = output<number>(); } @Component({ template: ` @if (show) { <div dir (onBla)="values.push($event)"></div> } `, standalone: true, imports: [Dir], }) class App { show = true; values: number[] = []; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dir = fixture.debugElement.children[0].injector.get(Dir); expect(fixture.componentInstance.values).toEqual([]); dir.onBla.emit(1); dir.onBla.emit(2); expect(fixture.componentInstance.values).toEqual([1, 2]); fixture.componentInstance.show = false; fixture.detectChanges(); expect(() => dir.onBla.emit(3)).toThrowError(/Unexpected emit for destroyed `OutputRef`/); }); it('should error when subscribing to a destroyed output', () => { @Directive({ selector: '[dir]', standalone: true, }) class Dir { onBla = output<number>(); } @Component({ template: ` @if (show) { <div dir (onBla)="values.push($event)"></div> } `, standalone: true, imports: [Dir], }) class App { show = true; values: number[] = []; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dir = fixture.debugElement.children[0].injector.get(Dir); expect(fixture.componentInstance.values).toEqual([]); dir.onBla.emit(1); dir.onBla.emit(2); expect(fixture.componentInstance.values).toEqual([1, 2]); fixture.componentInstance.show = false; fixture.detectChanges(); expect(() => dir.onBla.subscribe(() => {})).toThrowError( /Unexpected subscription to destroyed `OutputRef`/, ); }); it('should run listeners outside of `emit` reactive context', () => { @Directive({ selector: '[dir]', standalone: true, }) class Dir { onBla = output(); effectCount = 0; constructor() { effect(() => { this.onBla.emit(); this.effectCount++; }); } } @Component({ template: '<div dir (onBla)="fnUsingSomeSignal()"></div>', standalone: true, imports: [Dir], }) class App { signalUnrelatedToDir = signal(0); fnUsingSomeSignal() { // track this signal in this function. this.signalUnrelatedToDir(); } } const fixture = TestBed.createComponent(App); const dir = fixture.debugElement.children[0].injector.get(Dir); fixture.detectChanges(); expect(dir.effectCount).toEqual(1); fixture.componentInstance.signalUnrelatedToDir.update((v) => v + 1); fixture.detectChanges(); expect(dir.effectCount).toEqual(1); });
010288
describe('outputFromObservable()', () => { it('should support using a `Subject` as source', () => { @Directive({ selector: '[dir]', standalone: true, }) class Dir { onBla$ = new Subject<number>(); onBla = outputFromObservable(this.onBla$); } @Component({ template: '<div dir (onBla)="values.push($event)"></div>', standalone: true, imports: [Dir], }) class App { values: number[] = []; } const fixture = TestBed.createComponent(App); const dir = fixture.debugElement.children[0].injector.get(Dir); fixture.detectChanges(); expect(fixture.componentInstance.values).toEqual([]); dir.onBla$.next(1); dir.onBla$.next(2); expect(fixture.componentInstance.values).toEqual([1, 2]); }); it('should support using a `BehaviorSubject` as source', () => { @Directive({ selector: '[dir]', standalone: true, }) class Dir { onBla$ = new BehaviorSubject<number>(1); onBla = outputFromObservable(this.onBla$); } @Component({ template: '<div dir (onBla)="values.push($event)"></div>', standalone: true, imports: [Dir], }) class App { values: number[] = []; } const fixture = TestBed.createComponent(App); const dir = fixture.debugElement.children[0].injector.get(Dir); fixture.detectChanges(); expect(fixture.componentInstance.values).toEqual([1]); dir.onBla$.next(2); dir.onBla$.next(3); expect(fixture.componentInstance.values).toEqual([1, 2, 3]); }); it('should support using an `EventEmitter` as source', () => { @Directive({ selector: '[dir]', standalone: true, }) class Dir { onBla$ = new EventEmitter<number>(); onBla = outputFromObservable(this.onBla$); } @Component({ template: '<div dir (onBla)="values.push($event)"></div>', standalone: true, imports: [Dir], }) class App { values: number[] = []; } const fixture = TestBed.createComponent(App); const dir = fixture.debugElement.children[0].injector.get(Dir); fixture.detectChanges(); expect(fixture.componentInstance.values).toEqual([]); dir.onBla$.next(1); dir.onBla$.next(2); expect(fixture.componentInstance.values).toEqual([1, 2]); }); it('should support lazily creating an observer upon subscription', () => { @Directive({ selector: '[dir]', standalone: true, }) class Dir { streamStarted = false; onBla$ = new Observable((obs) => { this.streamStarted = true; obs.next(1); }).pipe(share()); onBla = outputFromObservable(this.onBla$); } @Component({ template: ` <div dir></div> <div dir (onBla)="true"></div> `, standalone: true, imports: [Dir], }) class App {} const fixture = TestBed.createComponent(App); const dir = fixture.debugElement.children[0].injector.get(Dir); const dir2 = fixture.debugElement.children[1].injector.get(Dir); fixture.detectChanges(); expect(dir.streamStarted).toBe(false); expect(dir2.streamStarted).toBe(true); }); it('should report subscription listener errors to `ErrorHandler` and continue', () => { @Directive({ selector: '[dir]', standalone: true, }) class Dir { onBla = output(); } @Component({ template: ` <div dir (onBla)="true"></div> `, standalone: true, imports: [Dir], }) class App {} let handledErrors: unknown[] = []; TestBed.configureTestingModule({ providers: [ { provide: ErrorHandler, useClass: class Handler extends ErrorHandler { override handleError(error: unknown): void { handledErrors.push(error); } }, }, ], }); const fixture = TestBed.createComponent(App); const dir = fixture.debugElement.children[0].injector.get(Dir); fixture.detectChanges(); let triggered = 0; dir.onBla.subscribe(() => { throw new Error('first programmatic listener failure'); }); dir.onBla.subscribe(() => { triggered++; }); dir.onBla.emit(); expect(handledErrors.length).toBe(1); expect((handledErrors[0] as Error).message).toBe('first programmatic listener failure'); expect(triggered).toBe(1); }); }); });
010316
describe('reactivity', () => { let prev: boolean; beforeEach(() => { prev = setUseMicrotaskEffectsByDefault(false); }); afterEach(() => setUseMicrotaskEffectsByDefault(prev)); describe('effects', () => { beforeEach(destroyPlatform); afterEach(destroyPlatform); it( 'should run effects in the zone in which they get created', withBody('<test-cmp></test-cmp>', async () => { const log: string[] = []; @Component({ selector: 'test-cmp', standalone: true, template: '', }) class Cmp { constructor(ngZone: NgZone) { effect(() => { log.push(Zone.current.name); }); ngZone.runOutsideAngular(() => { effect(() => { log.push(Zone.current.name); }); }); } } await bootstrapApplication(Cmp); expect(log).not.toEqual(['angular', 'angular']); }), ); it('should contribute to application stableness when an effect is pending', async () => { const someSignal = signal('initial'); const appRef = TestBed.inject(ApplicationRef); const isStable: boolean[] = []; const sub = appRef.isStable.subscribe((stable) => isStable.push(stable)); expect(isStable).toEqual([true]); TestBed.runInInjectionContext(() => effect(() => someSignal())); expect(isStable).toEqual([true, false]); appRef.tick(); expect(isStable).toEqual([true, false, true]); }); it('should propagate errors to the ErrorHandler', () => { TestBed.configureTestingModule({ providers: [{provide: ErrorHandler, useFactory: () => new FakeErrorHandler()}], rethrowApplicationErrors: false, }); let run = false; let lastError: any = null; class FakeErrorHandler extends ErrorHandler { override handleError(error: any): void { lastError = error; } } const appRef = TestBed.inject(ApplicationRef); effect( () => { run = true; throw new Error('fail!'); }, {injector: appRef.injector}, ); appRef.tick(); expect(run).toBeTrue(); expect(lastError.message).toBe('fail!'); }); // Disabled while we consider whether this actually makes sense. // This test _used_ to show that `effect()` was usable inside component error handlers, partly // because effect errors used to report to component error handlers. Now, effect errors are // always reported to the top-level error handler, which has never been able to use `effect()` // as `effect()` depends transitively on `ApplicationRef` which depends circularly on // `ErrorHandler`. xit('should be usable inside an ErrorHandler', async () => { const shouldError = signal(false); let lastError: any = null; class FakeErrorHandler extends ErrorHandler { constructor() { super(); effect(() => { if (shouldError()) { throw new Error('fail!'); } }); } override handleError(error: any): void { lastError = error; } } TestBed.configureTestingModule({ providers: [{provide: ErrorHandler, useClass: FakeErrorHandler}], rethrowApplicationErrors: false, }); const appRef = TestBed.inject(ApplicationRef); expect(() => appRef.tick()).not.toThrow(); shouldError.set(true); expect(() => appRef.tick()).not.toThrow(); expect(lastError?.message).toBe('fail!'); }); it('should run effect cleanup function on destroy', async () => { let counterLog: number[] = []; let cleanupCount = 0; @Component({ selector: 'test-cmp', standalone: true, template: '', }) class Cmp { counter = signal(0); effectRef = effect((onCleanup) => { counterLog.push(this.counter()); onCleanup(() => { cleanupCount++; }); }); } const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); await fixture.whenStable(); expect(counterLog).toEqual([0]); // initially an effect runs but the default cleanup function is noop expect(cleanupCount).toBe(0); fixture.componentInstance.counter.set(5); fixture.detectChanges(); await fixture.whenStable(); expect(counterLog).toEqual([0, 5]); expect(cleanupCount).toBe(1); fixture.destroy(); expect(counterLog).toEqual([0, 5]); expect(cleanupCount).toBe(2); }); it('should run effects created in ngAfterViewInit', () => { let didRun = false; @Component({ selector: 'test-cmp', standalone: true, template: '', }) class Cmp implements AfterViewInit { injector = inject(Injector); ngAfterViewInit(): void { effect( () => { didRun = true; }, {injector: this.injector}, ); } } const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(didRun).toBeTrue(); }); it('should create root effects when outside of a component, using injection context', () => { TestBed.configureTestingModule({}); const counter = signal(0); const log: number[] = []; TestBed.runInInjectionContext(() => effect(() => log.push(counter()))); TestBed.flushEffects(); expect(log).toEqual([0]); counter.set(1); TestBed.flushEffects(); expect(log).toEqual([0, 1]); }); it('should create root effects when outside of a component, using an injector', () => { TestBed.configureTestingModule({}); const counter = signal(0); const log: number[] = []; effect(() => log.push(counter()), {injector: TestBed.inject(Injector)}); TestBed.flushEffects(); expect(log).toEqual([0]); counter.set(1); TestBed.flushEffects(); expect(log).toEqual([0, 1]); }); it('should create root effects inside a component when specified', () => { TestBed.configureTestingModule({}); const counter = signal(0); const log: number[] = []; @Component({ standalone: true, template: '', }) class TestCmp { constructor() { effect(() => log.push(counter()), {forceRoot: true}); } } // Running this creates the effect. Note: we never CD this component. TestBed.createComponent(TestCmp); TestBed.flushEffects(); expect(log).toEqual([0]); counter.set(1); TestBed.flushEffects(); expect(log).toEqual([0, 1]); }); it('should check components made dirty from markForCheck() from an effect', async () => { TestBed.configureTestingModule({ providers: [provideExperimentalZonelessChangeDetection()], }); const source = signal(''); @Component({ standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: '{{ data }}', }) class TestCmp { cdr = inject(ChangeDetectorRef); data = ''; effectRef = effect(() => { if (this.data !== source()) { this.data = source(); this.cdr.markForCheck(); } }); } const fix = TestBed.createComponent(TestCmp); await fix.whenStable(); source.set('test'); await fix.whenStable(); expect(fix.nativeElement.innerHTML).toBe('test'); }); it('should check components made dirty from markForCheck() from an effect in a service', async () => { TestBed.configureTestingModule({ providers: [provideExperimentalZonelessChangeDetection()], }); const source = signal(''); @Injectable() class Service { data = ''; cdr = inject(ChangeDetectorRef); effectRef = effect(() => { if (this.data !== source()) { this.data = source(); this.cdr.markForCheck(); } }); } @Component({ standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, providers: [Service], template: '{{ service.data }}', }) class TestCmp { service = inject(Service); } const fix = TestBed.createComponent(TestCmp); await fix.whenStable(); source.set('test'); await fix.whenStable(); expect(fix.nativeElement.innerHTML).toBe('test'); });
010317
it('should check views made dirty from markForCheck() from an effect in a directive', async () => { TestBed.configureTestingModule({ providers: [provideExperimentalZonelessChangeDetection()], }); const source = signal(''); @Directive({ standalone: true, selector: '[dir]', }) class Dir { tpl = inject(TemplateRef); vcr = inject(ViewContainerRef); cdr = inject(ChangeDetectorRef); ctx = { $implicit: '', }; ref = this.vcr.createEmbeddedView(this.tpl, this.ctx); effectRef = effect(() => { if (this.ctx.$implicit !== source()) { this.ctx.$implicit = source(); this.cdr.markForCheck(); } }); } @Component({ standalone: true, imports: [Dir], template: `<ng-template dir let-data>{{data}}</ng-template>`, changeDetection: ChangeDetectionStrategy.OnPush, }) class TestCmp {} const fix = TestBed.createComponent(TestCmp); await fix.whenStable(); source.set('test'); await fix.whenStable(); expect(fix.nativeElement.innerHTML).toContain('test'); }); describe('destruction', () => { it('should still destroy root effects with the DestroyRef of the component', () => { TestBed.configureTestingModule({}); const counter = signal(0); const log: number[] = []; @Component({ standalone: true, template: '', }) class TestCmp { constructor() { effect(() => log.push(counter()), {forceRoot: true}); } } const fix = TestBed.createComponent(TestCmp); TestBed.flushEffects(); expect(log).toEqual([0]); // Destroy the effect. fix.destroy(); counter.set(1); TestBed.flushEffects(); expect(log).toEqual([0]); }); it('should destroy effects when the parent component is destroyed', () => { let destroyed = false; @Component({ standalone: true, }) class TestCmp { constructor() { effect((onCleanup) => onCleanup(() => (destroyed = true))); } } const fix = TestBed.createComponent(TestCmp); fix.detectChanges(); fix.destroy(); expect(destroyed).toBeTrue(); }); it('should destroy effects when their view is destroyed, separately from DestroyRef', () => { let destroyed = false; @Component({ standalone: true, }) class TestCmp { readonly injector = Injector.create({providers: [], parent: inject(Injector)}); constructor() { effect((onCleanup) => onCleanup(() => (destroyed = true)), {injector: this.injector}); } } const fix = TestBed.createComponent(TestCmp); fix.detectChanges(); fix.destroy(); expect(destroyed).toBeTrue(); }); it('should destroy effects when their DestroyRef is separately destroyed', () => { let destroyed = false; @Component({ standalone: true, }) class TestCmp { readonly injector = Injector.create({providers: [], parent: inject(Injector)}); constructor() { effect((onCleanup) => onCleanup(() => (destroyed = true)), {injector: this.injector}); } } const fix = TestBed.createComponent(TestCmp); fix.detectChanges(); (fix.componentInstance.injector as Injector & {destroy(): void}).destroy(); expect(destroyed).toBeTrue(); }); }); });
010318
describe('safeguards', () => { it('should allow writing to signals within effects', () => { const counter = signal(0); effect(() => counter.set(1), {injector: TestBed.inject(Injector)}); TestBed.flushEffects(); expect(counter()).toBe(1); }); it('should allow writing to signals in ngOnChanges', () => { @Component({ selector: 'with-input', standalone: true, template: '{{inSignal()}}', }) class WithInput implements OnChanges { inSignal = signal<string | undefined>(undefined); @Input() in: string | undefined; ngOnChanges(changes: SimpleChanges): void { if (changes['in']) { this.inSignal.set(changes['in'].currentValue); } } } @Component({ selector: 'test-cmp', standalone: true, imports: [WithInput], template: `<with-input [in]="'A'" />|<with-input [in]="'B'" />`, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('A|B'); }); it('should allow writing to signals in a constructor', () => { @Component({ selector: 'with-constructor', standalone: true, template: '{{state()}}', }) class WithConstructor { state = signal('property initializer'); constructor() { this.state.set('constructor'); } } @Component({ selector: 'test-cmp', standalone: true, imports: [WithConstructor], template: `<with-constructor />`, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('constructor'); }); it('should allow writing to signals in input setters', () => { @Component({ selector: 'with-input-setter', standalone: true, template: '{{state()}}', }) class WithInputSetter { state = signal('property initializer'); @Input() set testInput(newValue: string) { this.state.set(newValue); } } @Component({ selector: 'test-cmp', standalone: true, imports: [WithInputSetter], template: ` <with-input-setter [testInput]="'binding'" />|<with-input-setter testInput="static" /> `, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('binding|static'); }); it('should allow writing to signals in query result setters', () => { @Component({ selector: 'with-query', standalone: true, template: '{{items().length}}', }) class WithQuery { items = signal<unknown[]>([]); @ContentChildren('item') set itemsQuery(result: QueryList<unknown>) { this.items.set(result.toArray()); } } @Component({ selector: 'test-cmp', standalone: true, imports: [WithQuery], template: `<with-query><div #item></div></with-query>`, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1'); }); it('should not execute query setters in the reactive context', () => { const state = signal('initial'); @Component({ selector: 'with-query-setter', standalone: true, template: '<div #el></div>', }) class WithQuerySetter { el: unknown; @ViewChild('el', {static: true}) set elQuery(result: unknown) { // read a signal in a setter - I want to verify that framework executes this code outside of // the reactive context state(); this.el = result; } } @Component({ selector: 'test-cmp', standalone: true, template: ``, }) class Cmp { noOfCmpCreated = 0; constructor(environmentInjector: EnvironmentInjector) { // A slightly artificial setup where a component instance is created using imperative APIs. // We don't have control over the timing / reactive context of such API calls so need to // code defensively in the framework. // Here we want to specifically verify that an effect is _not_ re-run if a signal read // happens in a query setter of a dynamically created component. effect(() => { createComponent(WithQuerySetter, {environmentInjector}); this.noOfCmpCreated++; }); } } const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(fixture.componentInstance.noOfCmpCreated).toBe(1); state.set('changed'); fixture.detectChanges(); expect(fixture.componentInstance.noOfCmpCreated).toBe(1); }); it('should allow toObservable subscription in template (with async pipe)', () => { @Component({ selector: 'test-cmp', standalone: true, imports: [AsyncPipe], template: '{{counter$ | async}}', }) class Cmp { counter$ = toObservable(signal(0)); } const fixture = TestBed.createComponent(Cmp); expect(() => fixture.detectChanges(true)).not.toThrow(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('0'); }); it('should assign a debugName to the underlying node for an effect', async () => { @Component({ selector: 'test-cmp', standalone: true, template: '', }) class Cmp { effectRef = effect(() => {}, {debugName: 'TEST_DEBUG_NAME'}); } const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const component = fixture.componentInstance; const effectRef = component.effectRef as unknown as {[SIGNAL]: EffectNode}; expect(effectRef[SIGNAL].debugName).toBe('TEST_DEBUG_NAME'); });
010414
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ChangeDetectorRef, Component, Injectable, NgModule, ViewEncapsulation} from '@angular/core'; import {loadTranslations} from '@angular/localize'; import {BrowserModule, platformBrowser} from '@angular/platform-browser'; import {translations} from './translations'; class Todo { editing: boolean; get title() { return this._title; } set title(value: string) { this._title = value.trim(); } constructor( private _title: string, public completed: boolean = false, ) { this.editing = false; } } @Injectable({providedIn: 'root'}) class TodoStore { todos: Array<Todo> = [ new Todo($localize`Demonstrate Components`), new Todo($localize`Demonstrate Structural Directives`, true), // Using a placeholder new Todo($localize`Demonstrate ${'NgModules'}:value:`), new Todo($localize`Demonstrate zoneless change detection`), new Todo($localize`Demonstrate internationalization`), ]; private getWithCompleted(completed: boolean) { return this.todos.filter((todo: Todo) => todo.completed === completed); } allCompleted() { return this.todos.length === this.getCompleted().length; } setAllTo(completed: boolean) { this.todos.forEach((t: Todo) => (t.completed = completed)); } removeCompleted() { this.todos = this.getWithCompleted(false); } getRemaining() { return this.getWithCompleted(false); } getCompleted() { return this.getWithCompleted(true); } toggleCompletion(todo: Todo) { todo.completed = !todo.completed; } remove(todo: Todo) { this.todos.splice(this.todos.indexOf(todo), 1); } add(title: string) { this.todos.push(new Todo(title)); } } @Component({ selector: 'todo-app', // TODO(misko): make this work with `[(ngModel)]` encapsulation: ViewEncapsulation.None, template: ` <section class="todoapp"> <header class="header" i18n> <h1>todos</h1> <input class="new-todo" i18n-placeholder placeholder="What needs to be done?" autofocus="" [value]="newTodoText" (keyup)="$event.code == 'Enter' ? addTodo() : updateNewTodoValue($event.target.value)"> </header> <section *ngIf="todoStore.todos.length > 0" class="main"> <input *ngIf="todoStore.todos.length" #toggleall class="toggle-all" type="checkbox" [checked]="todoStore.allCompleted()" (click)="toggleAllTodos(toggleall.checked)"> <ul class="todo-list"> <li *ngFor="let todo of todoStore.todos" [class.completed]="todo.completed" [class.editing]="todo.editing"> <div class="view"> <input class="toggle" type="checkbox" (click)="toggleCompletion(todo)" [checked]="todo.completed"> <label (dblclick)="editTodo(todo)">{{todo.title}}</label> <button class="destroy" (click)="remove(todo)"></button> </div> <input *ngIf="todo.editing" class="edit" #editedtodo [value]="todo.title" (blur)="updateEditedTodoValue(todo, editedtodo.value)" (keyup)="updateEditedTodoValue(todo, $event.target.value)" (keyup)="$event.code == 'Enter' && updateEditedTodoValue(todo, editedtodo.value)" (keyup)="$event.code == 'Escape' && cancelEditingTodo(todo)"> </li> </ul> </section> <footer *ngIf="todoStore.todos.length > 0" class="footer"> <span class="todo-count" i18n> <strong>{{todoStore.getRemaining().length}}</strong> {todoStore.getRemaining().length, plural, =1 {item left} other {items left}} </span> <button *ngIf="todoStore.getCompleted().length > 0" class="clear-completed" (click)="removeCompleted()" i18n> Clear completed </button> </footer> </section> `, standalone: false, }) class ToDoAppComponent { newTodoText = ''; constructor( public todoStore: TodoStore, private readonly cdr: ChangeDetectorRef, ) { (window as any).todoAppComponent = this; } cancelEditingTodo(todo: Todo) { todo.editing = false; this.cdr.detectChanges(); } finishUpdatingTodo(todo: Todo, editedTitle: string) { editedTitle = editedTitle.trim(); if (editedTitle.length === 0) { this.remove(todo); } todo.title = editedTitle; this.cancelEditingTodo(todo); } editTodo(todo: Todo) { todo.editing = true; this.cdr.detectChanges(); } removeCompleted() { this.todoStore.removeCompleted(); this.cdr.detectChanges(); } toggleCompletion(todo: Todo) { this.todoStore.toggleCompletion(todo); this.cdr.detectChanges(); } remove(todo: Todo) { this.todoStore.remove(todo); this.cdr.detectChanges(); } addTodo() { if (this.newTodoText.trim().length) { this.todoStore.add(this.newTodoText); this.newTodoText = ''; } this.cdr.detectChanges(); } toggleAllTodos(checked: boolean) { this.todoStore.setAllTo(checked); this.cdr.detectChanges(); } updateEditedTodoValue(todo: Todo, value: string) { todo.title = value; this.cdr.detectChanges(); } updateNewTodoValue(value: string) { this.newTodoText = value; this.cdr.detectChanges(); } } @NgModule({ declarations: [ToDoAppComponent], imports: [BrowserModule], bootstrap: [ToDoAppComponent], }) class ToDoAppModule {} loadTranslations(translations); (window as any).appReady = platformBrowser().bootstrapModule(ToDoAppModule, {ngZone: 'noop'});
010443
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component, NgModule} from '@angular/core'; import { FormArray, FormBuilder, FormControl, FormGroup, ReactiveFormsModule, Validators, } from '@angular/forms'; import {BrowserModule, platformBrowser} from '@angular/platform-browser'; @Component({ selector: 'app-reactive-forms', template: ` <form [formGroup]="profileForm"> <div> First Name: <input type="text" formControlName="firstName" /> </div> <div> Last Name: <input type="text" formControlName="lastName" /> </div> <div> Subscribe: <input type="checkbox" formControlName="subscribed" /> </div> <div>Disabled: <input formControlName="disabledInput" /></div> <div formArrayName="addresses"> <div *ngFor="let item of itemControls; let i = index" [formGroupName]="i"> <div>City: <input formControlName="city" /></div> </div> </div> <button (click)="addCity()">Add City</button> </form> `, standalone: false, }) class ReactiveFormsComponent { profileForm!: FormGroup; addresses!: FormArray; get itemControls() { return (this.profileForm.get('addresses') as FormArray).controls; } constructor(private formBuilder: FormBuilder) { // We use this reference in our test (window as any).reactiveFormsComponent = this; } ngOnInit() { this.profileForm = new FormGroup({ firstName: new FormControl('', Validators.required), lastName: new FormControl(''), addresses: new FormArray([]), subscribed: new FormControl(), disabledInput: new FormControl({value: '', disabled: true}), }); this.addCity(); } createItem(): FormGroup { return this.formBuilder.group({ city: '', }); } addCity(): void { this.addresses = this.profileForm.get('addresses') as FormArray; this.addresses.push(this.createItem()); } } @Component({ selector: 'app-root', template: ` <app-reactive-forms></app-reactive-forms> `, standalone: false, }) class RootComponent {} @NgModule({ declarations: [RootComponent, ReactiveFormsComponent], imports: [BrowserModule, ReactiveFormsModule], }) class FormsExampleModule { ngDoBootstrap(app: any) { app.bootstrap(RootComponent); } } function bootstrapApp() { return platformBrowser().bootstrapModule(FormsExampleModule, {ngZone: 'noop'}); } (window as any).bootstrapApp = bootstrapApp;
010497
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component, NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {BrowserModule, platformBrowser} from '@angular/platform-browser'; @Component({ selector: 'app-template-forms', template: ` <form novalidate> <div ngModelGroup="profileForm"> <div> First Name: <input name="first" ngModel required /> </div> <div> Last Name: <input name="last" ngModel /> </div> <div> Subscribe: <input name="subscribed" type="checkbox" ngModel /> </div> <div>Disabled: <input name="foo" ngModel disabled /></div> <div *ngFor="let city of addresses; let i = index"> City <input [(ngModel)]="addresses[i].city" name="name" /> </div> <button (click)="addCity()">Add City</button> </div> </form> `, standalone: false, }) class TemplateFormsComponent { name = {first: 'Nancy', last: 'Drew', subscribed: true}; addresses = [{city: 'Toronto'}]; constructor() { // We use this reference in our test (window as any).templateFormsComponent = this; } addCity() { this.addresses.push({city: ''}); } } @Component({ selector: 'app-root', template: ` <app-template-forms></app-template-forms> `, standalone: false, }) class RootComponent {} @NgModule({ declarations: [RootComponent, TemplateFormsComponent], imports: [BrowserModule, FormsModule], }) class FormsExampleModule { ngDoBootstrap(app: any) { app.bootstrap(RootComponent); } } function bootstrapApp() { return platformBrowser().bootstrapModule(FormsExampleModule, {ngZone: 'noop'}); } (window as any).bootstrapApp = bootstrapApp;
010501
/** * @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 {animate, style, transition, trigger} from '@angular/animations'; import {Component, NgModule, ɵNgModuleFactory as NgModuleFactory} from '@angular/core'; import {bootstrapApplication, BrowserModule, platformBrowser} from '@angular/platform-browser'; import {BrowserAnimationsModule, provideAnimations} from '@angular/platform-browser/animations'; @Component({ selector: 'app-animations', template: ` <div [@myAnimation]="exp"></div> `, animations: [ trigger('myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])]), ], standalone: true, }) class AnimationsComponent { exp: any = false; } @Component({ selector: 'app-root', template: ` <app-animations></app-animations> `, standalone: true, imports: [AnimationsComponent], }) class RootComponent {} (window as any).waitForApp = bootstrapApplication(RootComponent, {providers: provideAnimations()});
010505
/** * @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 {animate, style, transition, trigger} from '@angular/animations'; import {Component, NgModule, ɵNgModuleFactory as NgModuleFactory} from '@angular/core'; import {BrowserModule, platformBrowser} from '@angular/platform-browser'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; @Component({ selector: 'app-animations', template: ` <div [@myAnimation]="exp"></div> `, animations: [ trigger('myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])]), ], standalone: false, }) class AnimationsComponent { exp: any = false; } @Component({ selector: 'app-root', template: ` <app-animations></app-animations> `, standalone: false, }) class RootComponent {} @NgModule({ declarations: [RootComponent, AnimationsComponent], imports: [BrowserModule, BrowserAnimationsModule], }) class AnimationsExampleModule { ngDoBootstrap(app: any) { app.bootstrap(RootComponent); } } (window as any).waitForApp = platformBrowser().bootstrapModule(AnimationsExampleModule, { ngZone: 'noop', });
010509
/** * @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 {APP_BASE_HREF} from '@angular/common'; import {Component, OnInit} from '@angular/core'; import {bootstrapApplication} from '@angular/platform-browser'; import { ActivatedRoute, provideRouter, Router, RouterLink, RouterLinkActive, RouterOutlet, Routes, } from '@angular/router'; @Component({ selector: 'app-list', template: ` <ul> <li><a routerLink="/item/1" routerLinkActive="active">List Item 1</a></li> <li><a routerLink="/item/2" routerLinkActive="active">List Item 2</a></li> <li><a routerLink="/item/3" routerLinkActive="active">List Item 3</a></li> </ul> `, standalone: true, imports: [RouterLink, RouterLinkActive], }) class ListComponent {} @Component({ selector: 'app-item', template: ` Item {{id}} <p><button (click)="viewList()">Back to List</button></p>`, standalone: true, }) class ItemComponent implements OnInit { id = -1; constructor( private activatedRoute: ActivatedRoute, private router: Router, ) {} ngOnInit() { this.activatedRoute.paramMap.subscribe((paramsMap) => { this.id = +paramsMap.get('id')!; }); } viewList() { this.router.navigate(['/list']); } } @Component({ selector: 'app-root', template: `<router-outlet></router-outlet>`, standalone: true, imports: [RouterOutlet], }) class RootComponent {} const ROUTES: Routes = [ {path: '', redirectTo: '/list', pathMatch: 'full'}, {path: 'list', component: ListComponent}, {path: 'item/:id', component: ItemComponent}, ]; (window as any).waitForApp = bootstrapApplication(RootComponent, { providers: [provideRouter(ROUTES), {provide: APP_BASE_HREF, useValue: ''}], });
010533
# Angular Signals Implementation This directory contains the code which powers Angular's reactive primitive, an implementation of the "signal" concept. A signal is a value which is "reactive", meaning it can notify interested consumers when it changes. There are many different implementations of this concept, with different designs for how these notifications are subscribed to and propagated, how cleanup/unsubscription works, how dependencies are tracked, etc. This document describes the algorithm behind our specific implementation of the signal pattern. ## Conceptual surface Angular Signals are zero-argument functions (`() => T`). When executed, they return the current value of the signal. Executing signals does not trigger side effects, though it may lazily recompute intermediate values (lazy memoization). Particular contexts (such as template expressions) can be _reactive_. In such contexts, executing a signal will return the value, but also register the signal as a dependency of the context in question. The context's owner will then be notified if any of its signal dependencies produces a new value (usually, this results in the re-execution of those expressions to consume the new values). This context and getter function mechanism allows for signal dependencies of a context to be tracked _automatically_ and _implicitly_. Users do not need to declare arrays of dependencies, nor does the set of dependencies of a particular context need to remain static across executions. ### Source signals ### Writable signals: `signal()` The `createSignal()` function produces a specific type of signal that tracks a stored value. In addition to providing a getter function, these signals can be wired up with additional APIs for changing the value of the signal (along with notifying any dependents of the change). These include the `.set` operation for replacing the signal value, and `.update` for deriving a new value. In Angular, these are exposed as functions on the signal getter itself. For example: ```typescript const counter = signal(0); counter.set(2); counter.update(count => count + 1); ``` #### Equality The signal creation function one can, optionally, specify an equality comparator function. The comparator is used to decide whether the new supplied value is the same, or different, as compared to the current signal’s value. If the equality function determines that 2 values are equal it will: * block update of signal’s value; * skip change propagation. ### Declarative derived values `createComputed()` creates a memoizing signal, which calculates its value from the values of some number of input signals. In Angular this is wrapped into the `computed` constructor: ```typescript const counter = signal(0); // Automatically updates when `counter` changes: const isEven = computed(() => counter() % 2 === 0); ``` Because the calculation function used to create the `computed` is executed in a reactive context, any signals read by that calculation will be tracked as dependencies, and the value of the computed signal recalculated whenever any of those dependencies changes. Similarly to signals, the `computed` can (optionally) specify an equality comparator function. ### Side effects: `createWatch()` The signals library provides an operation to watch a reactive function and receive notifications when the dependencies of that function change. This is used within Angular to build `effect()`. `effect()` schedules and runs a side-effectful function inside a reactive context. Signal dependencies of this function are captured, and the side effect is re-executed whenever any of its dependencies produces a new value. ```typescript const counter = signal(0); effect(() => console.log('The counter is:', counter())); // The counter is: 0 counter.set(1); // The counter is: 1 ``` Effects do not execute synchronously with the set (see the section on glitch-free execution below), but are scheduled and resolved by the framework. The exact timing of effects is unspecified. ## Producer and Consumer Internally, the signals implementation is defined in terms of two abstractions, producers and consumers. Producers represents values which can deliver change notifications, such as the various flavors of `Signal`s. Consumers represents a reactive context which may depend on some number of producers. In other words, producers produce reactivity, and consumers consume it. Implementers of either abstraction define a node object which implements the `ReactiveNode` interface, which models participation in the reactive graph. Any `ReactiveNode` can act in the role of a producer, a consumer, or both, by interacting with the appropriate subset of APIs. For example, `WritableSignal`s implement `ReactiveNode` but only operate against the producer APIs, since `WritableSignal`s don't consume other signal values. Some concepts are both producers _and_ consumers. For example, derived `computed` expressions consume other signals to produce new reactive values. Throughout the rest of this document, "producer" and "consumer" are used to describe `ReactiveNode`s acting in that capacity. ### The Dependency Graph `ReactiveNode`s are linked together through a dependency graph. This dependency graph is bidirectional, but there are differences in which dependencies are tracked in each direction. Consumers always keep track of the producers they depend on. Producers only track dependencies from consumers which are considered "live". A consumer is "live" when either: * It sets the `consumerIsAlwaysLive` property of its `ReactiveNode` to `true`, or * It's also a producer which is depended upon by a live consumer. In that sense, "liveness" is a transitive property of consumers. In practice, effects (including template pseudo-effects) are live consumers, which `computed`s are not inherently live. This means that any `computed` used in an `effect` will be treated as live, but a `computed` not read in any effects will not be. #### Liveness and memory management The concept of liveness allows for producer-to-consumer dependency tracking without risking memory leaks. Consider this contrived case of a `signal` and a `computed`: ```typescript const counter = signal(1); let double = computed(() => counter() * 2); console.log(double()); // 2 double = null; ``` If the dependency graph maintained a hard reference from `counter` to `double`, then `double` would be retained(not garbage collected) even though the user dropped their last reference to the actual signal. But because `double` is not live, the graph doesn't hold a reference from `counter` to `double`, and `double` can be freed when the user drops it. #### Non-live consumers and polling A consequence of not tracking an edge from `counter` to `double` is that when counter is changed: ```typescript counter.set(2); ``` No notification can propagate in the graph from `counter` to `double`, to let the `computed` know that it needs to throw away its memoized value (2) and recompute (producing 4). Instead, when `double()` is read, it polls its producers (which _are_ tracked in the graph) and checks whether any of them report having changed since the last time `double` was calculated. If not, it can safely use its memoized value. #### With a live consumer If an `effect` is created: ```typescript effect(() => console.log(double())); ``` Then `double` becomes a live consumer, as it's a dependency of a live consumer (the effect), and the graph will have a hard reference from `counter` to `double` to the effect consumer. There is no risk of memory leaks though, since the effect is referencing `double` directly anyway, and the effect cannot just be dropped and must be manually destroyed (which would cause `double` to no longer be live). That is, there is no way for a reference from a producer to a live consumer to exist in the graph _without_ the consumer also referencing the producer outside of the graph.` ## "
010534
Glitch Free" property Consider the following setup: ```typescript const counter = signal(0); const evenOrOdd = computed(() => counter() % 2 === 0 ? 'even' : 'odd'); effect(() => console.log(counter() + ' is ' + evenOrOdd())); counter.set(1); ``` When the effect is first created, it will print "0 is even", as expected, and record that both `counter` and `evenOrOdd` are dependencies of the logging effect. When `counter` is set to `1`, this invalidates both `evenOrOdd` and the logging effect. If `counter.set()` iterated through the dependencies of `counter` and triggered the logging effect first, before notifying `evenOrOdd` of the change, however, we might observe the inconsistent logging statement "1 is even". Eventually `evenOrOdd` would be notified, which would trigger the logging effect again, logging the correct statement "1 is odd". In this situation, the logging effect's observation of the inconsistent state "1 is even" is known as a _glitch_. A major goal of reactive system design is to prevent such intermediate states from ever being observed, and ensure _glitch-free execution_. ### Push/Pull Algorithm Angular Signals guarantees glitch-free execution by separating updates to the `ReactiveNode` graph into two phases. The first phase is performed eagerly when a producer value is changed. This change notification is propagated through the graph, notifying live consumers which depend on the producer of the potential update. Some of these consumers may be derived values and thus also producers, which invalidate their cached values and then continue the propagation of the change notification to their own live consumers, and so on. Ultimately this notification reaches effects, which schedule themselves for re-execution. Crucially, during this first phase, no side effects are run, and no recomputation of intermediate or derived values is performed, only invalidation of cached values. This allows the change notification to reach all affected nodes in the graph without the possibility of observing intermediate or glitchy states. Once this change propagation has completed (synchronously), the second phase can begin. In this second phase, signal values may be read by the application or framework, triggering recomputation of any needed derived values which were previously invalidated. We refer to this as the "push/pull" algorithm: "dirtiness" is eagerly _pushed_ through the graph when a source signal is changed, but recalculation is performed lazily, only when values are _pulled_ by reading their signals. ## Dynamic Dependency Tracking When a reactive context operation (for example, an `effect`'s side effect function) is executed, the signals that it reads are tracked as dependencies. However, this may not be the same set of signals from one execution to the next. For example, this computed signal: ```typescript const dynamic = computed(() => useA() ? dataA() : dataB()); ``` reads either `dataA` or `dataB` depending on the value of the `useA` signal. At any given point, it will have a dependency set of either `[useA, dataA]` or `[useA, dataB]`, and it can never depend on `dataA` and `dataB` at the same time. The potential dependencies of a reactive context are unbounded. Signals may be stored in variables or other data structures and swapped out with other signals from time to time. Thus, the signals implementation must deal with potential changes in the set of dependencies of a consumer on each execution. Dependencies of a computation are tracked in an array. When the computation is rerun, a pointer into that array is initialized to the index `0`, and each dependency read is compared against the dependency from the previous run at the pointer's current location. If there's a mismatch, then the dependencies have changed since the last run, and the old dependency can be dropped and replaced with the new one. At the end of the run, any remaining unmatched dependencies can be dropped. ## Equality Semantics Producers may lazily produce their value (such as a `computed` which only recalculates its value when pulled). However, a producer may also choose to apply an equality check to the values that it produces, and determine that the newly computed value is "equal" semantically to the previous. In this case, consumers which depend on that value should not be re-executed. For example, the following effect: ```typescript const counter = signal(0); const isEven = computed(() => counter() % 2 === 0); effect(() => console.log(isEven() ? 'even!' : 'odd!')); ``` should run if `counter` is updated to `1` as the value of `isEven` switches from `true` to `false`. But if `counter` is then set to `3`, `isEven` will recompute the same value: `false`. Therefore the logging effect should not run. This is a tricky property to guarantee in our implementation because values are not recomputed during the push phase of change propagation. `isEven` is invalidated when `counter` is changed, which causes the logging `effect` to also be invalidated and scheduled. Naively, `isEven` wouldn't be recomputed until the logging effect actually runs and attempts to read its value, which is too late to notice that it didn't need to run at all. ### Value Versioning To solve this problem, our implementation uses a similar technique to tracking dependency staleness. Producers track a monotonically increasing `version`, representing the semantic identity of their value. `version` is incremented when the producer produces a semantically new value. The current `version` of each dependency (producer) is saved as part of the tracked dependencies of a consumer. Before consumers trigger their reactive operations (e.g. the side effect function for `effect`s, or the recomputation for `computed`s), they poll their dependencies and ask for `version` to be refreshed if needed. For a `computed`, this will trigger recomputation of the value and the subsequent equality check, if the value is stale (which makes this polling a recursive process as the `computed` is also a consumer which will poll its own producers). If this recomputation produces a semantically changed value, `version` is incremented. The consumer can then compare the `version` of the new value with its last read version to determine if that particular dependency really did change. By doing this for all producers the consumer can determine that, if all `version`s match, that no _actual_ change to any dependency has occurred, and it can skip reacting to that change (e.g. skip running the side effect function). ## `Watch` primitive `Watch` is a primitive used to build different types of effects. `Watch`es are consumers that run side-effectful functions in their reactive context, but where the scheduling of the side effect is delegated to the implementor. The `Watch` will call this scheduling operation when it receives a notification that it's stale.
010539
/** * @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 */ /** * A comparison function which can determine if two values are equal. */ export type ValueEqualityFn<T> = (a: T, b: T) => boolean; /** * The default equality function used for `signal` and `computed`, which uses referential equality. */ export function defaultEquals<T>(a: T, b: T) { return Object.is(a, b); }
010544
/** * @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 {defaultEquals, ValueEqualityFn} from './equality'; import {throwInvalidWriteToSignalError} from './errors'; import { producerAccessed, producerIncrementEpoch, producerNotifyConsumers, producerUpdatesAllowed, REACTIVE_NODE, ReactiveNode, SIGNAL, } from './graph'; // Required as the signals library is in a separate package, so we need to explicitly ensure the // global `ngDevMode` type is defined. declare const ngDevMode: boolean | undefined; /** * If set, called after `WritableSignal`s are updated. * * This hook can be used to achieve various effects, such as running effects synchronously as part * of setting a signal. */ let postSignalSetFn: (() => void) | null = null; export interface SignalNode<T> extends ReactiveNode { value: T; equal: ValueEqualityFn<T>; } export type SignalBaseGetter<T> = (() => T) & {readonly [SIGNAL]: unknown}; // Note: Closure *requires* this to be an `interface` and not a type, which is why the // `SignalBaseGetter` type exists to provide the correct shape. export interface SignalGetter<T> extends SignalBaseGetter<T> { readonly [SIGNAL]: SignalNode<T>; } /** * Create a `Signal` that can be set or updated directly. */ export function createSignal<T>(initialValue: T): SignalGetter<T> { const node: SignalNode<T> = Object.create(SIGNAL_NODE); node.value = initialValue; const getter = (() => { producerAccessed(node); return node.value; }) as SignalGetter<T>; (getter as any)[SIGNAL] = node; return getter; } export function setPostSignalSetFn(fn: (() => void) | null): (() => void) | null { const prev = postSignalSetFn; postSignalSetFn = fn; return prev; } export function signalGetFn<T>(this: SignalNode<T>): T { producerAccessed(this); return this.value; } export function signalSetFn<T>(node: SignalNode<T>, newValue: T) { if (!producerUpdatesAllowed()) { throwInvalidWriteToSignalError(); } if (!node.equal(node.value, newValue)) { node.value = newValue; signalValueChanged(node); } } export function signalUpdateFn<T>(node: SignalNode<T>, updater: (value: T) => T): void { if (!producerUpdatesAllowed()) { throwInvalidWriteToSignalError(); } signalSetFn(node, updater(node.value)); } export function runPostSignalSetFn(): void { postSignalSetFn?.(); } // 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 SIGNAL_NODE: SignalNode<unknown> = /* @__PURE__ */ (() => { return { ...REACTIVE_NODE, equal: defaultEquals, value: undefined, }; })(); function signalValueChanged<T>(node: SignalNode<T>): void { node.version++; producerIncrementEpoch(); producerNotifyConsumers(node); postSignalSetFn?.(); }
010622
<T>(type: Type<T>): ComponentFixture<T> { const testComponentRenderer = this.inject(TestComponentRenderer); const rootElId = `root${_nextRootElementId++}`; testComponentRenderer.insertRootElement(rootElId); if (getAsyncClassMetadataFn(type)) { throw new Error( `Component '${type.name}' has unresolved metadata. ` + `Please call \`await TestBed.compileComponents()\` before running this test.`, ); } const componentDef = (type as any).ɵcmp; if (!componentDef) { throw new Error(`It looks like '${stringify(type)}' has not been compiled.`); } const componentFactory = new ComponentFactory(componentDef); const initComponent = () => { const componentRef = componentFactory.create( Injector.NULL, [], `#${rootElId}`, this.testModuleRef, ) as ComponentRef<T>; return this.runInInjectionContext(() => new ComponentFixture(componentRef)); }; const noNgZone = this.inject(ComponentFixtureNoNgZone, false); const ngZone = noNgZone ? null : this.inject(NgZone, null); const fixture = ngZone ? ngZone.run(initComponent) : initComponent(); this._activeFixtures.push(fixture); return fixture; } /** * @internal strip this from published d.ts files due to * https://github.com/microsoft/TypeScript/issues/36216 */ private get compiler(): TestBedCompiler { if (this._compiler === null) { throw new Error(`Need to call TestBed.initTestEnvironment() first`); } return this._compiler; } /** * @internal strip this from published d.ts files due to * https://github.com/microsoft/TypeScript/issues/36216 */ private get testModuleRef(): NgModuleRef<any> { if (this._testModuleRef === null) { this._testModuleRef = this.compiler.finalize(); } return this._testModuleRef; } private assertNotInstantiated(methodName: string, methodDescription: string) { if (this._testModuleRef !== null) { throw new Error( `Cannot ${methodDescription} when the test module has already been instantiated. ` + `Make sure you are not using \`inject\` before \`${methodName}\`.`, ); } } /** * Check whether the module scoping queue should be flushed, and flush it if needed. * * When the TestBed is reset, it clears the JIT module compilation queue, cancelling any * in-progress module compilation. This creates a potential hazard - the very first time the * TestBed is initialized (or if it's reset without being initialized), there may be pending * compilations of modules declared in global scope. These compilations should be finished. * * To ensure that globally declared modules have their components scoped properly, this function * is called whenever TestBed is initialized or reset. The _first_ time that this happens, prior * to any other operations, the scoping queue is flushed. */ private checkGlobalCompilationFinished(): void { // Checking _testNgModuleRef is null should not be necessary, but is left in as an additional // guard that compilations queued in tests (after instantiation) are never flushed accidentally. if (!this.globalCompilationChecked && this._testModuleRef === null) { flushModuleScopingQueueAsMuchAsPossible(); } this.globalCompilationChecked = true; } private destroyActiveFixtures(): void { let errorCount = 0; this._activeFixtures.forEach((fixture) => { try { fixture.destroy(); } catch (e) { errorCount++; console.error('Error during cleanup of component', { component: fixture.componentInstance, stacktrace: e, }); } }); this._activeFixtures = []; if (errorCount > 0 && this.shouldRethrowTeardownErrors()) { throw Error( `${errorCount} ${errorCount === 1 ? 'component' : 'components'} ` + `threw errors during cleanup`, ); } } shouldRethrowTeardownErrors(): boolean { const instanceOptions = this._instanceTeardownOptions; const environmentOptions = TestBedImpl._environmentTeardownOptions; // If the new teardown behavior hasn't been configured, preserve the old behavior. if (!instanceOptions && !environmentOptions) { return TEARDOWN_TESTING_MODULE_ON_DESTROY_DEFAULT; } // Otherwise use the configured behavior or default to rethrowing. return ( instanceOptions?.rethrowErrors ?? environmentOptions?.rethrowErrors ?? this.shouldTearDownTestingModule() ); } shouldThrowErrorOnUnknownElements(): boolean { // Check if a configuration has been provided to throw when an unknown element is found return ( this._instanceErrorOnUnknownElementsOption ?? TestBedImpl._environmentErrorOnUnknownElementsOption ?? THROW_ON_UNKNOWN_ELEMENTS_DEFAULT ); } shouldThrowErrorOnUnknownProperties(): boolean { // Check if a configuration has been provided to throw when an unknown property is found return ( this._instanceErrorOnUnknownPropertiesOption ?? TestBedImpl._environmentErrorOnUnknownPropertiesOption ?? THROW_ON_UNKNOWN_PROPERTIES_DEFAULT ); } shouldTearDownTestingModule(): boolean { return ( this._instanceTeardownOptions?.destroyAfterEach ?? TestBedImpl._environmentTeardownOptions?.destroyAfterEach ?? TEARDOWN_TESTING_MODULE_ON_DESTROY_DEFAULT ); } getDeferBlockBehavior(): DeferBlockBehavior { return this._instanceDeferBlockBehavior; } tearDownTestingModule() { // If the module ref has already been destroyed, we won't be able to get a test renderer. if (this._testModuleRef === null) { return; } // Resolve the renderer ahead of time, because we want to remove the root elements as the very // last step, but the injector will be destroyed as a part of the module ref destruction. const testRenderer = this.inject(TestComponentRenderer); try { this._testModuleRef.destroy(); } catch (e) { if (this.shouldRethrowTeardownErrors()) { throw e; } else { console.error('Error during cleanup of a testing module', { component: this._testModuleRef.instance, stacktrace: e, }); } } finally { testRenderer.removeAllRootElements?.(); } } /** * Execute any pending effects. * * @developerPreview */ flushEffects(): void { this.inject(MicrotaskEffectScheduler).flush(); this.inject(EffectScheduler).flush(); } } /** * @description * Configures and initializes environment for unit testing and provides methods for * creating components and services in unit tests. * * `TestBed` is the primary api for writing unit tests for Angular applications and libraries. * * @publicApi */ export const TestBed: TestBedStatic = TestBedImpl; /** * Allows injecting dependencies in `beforeEach()` and `it()`. Note: this function * (imported from the `@angular/core/testing` package) can **only** be used to inject dependencies * in tests. To inject dependencies in your application code, use the [`inject`](api/core/inject) * function from the `@angular/core` package instead. * * Example: * * ``` * beforeEach(inject([Dependency, AClass], (dep, object) => { * // some code that uses `dep` and `object` * // ... * })); * * it('...', inject([AClass], (object) => { * object.doSomething(); * expect(...); * }) * ``` * * @publicApi */ export function inject(tokens: any[], fn: Function): () => any { const testBed = TestBedImpl.INSTANCE; // Not using an arrow function to preserve context passed from call site return function (this: unknown) { return testBed.execute(tokens, fn, this); }; } /** * @publicApi */ export class InjectSetupWrapper { constructor(private _moduleDef: () => TestModuleMetadata) {} private _addModule() { const moduleDef = this._moduleDef(); if (moduleDef) { TestBedImpl.configureTestingModule(moduleDef); } } inject(tokens: any[], fn: Function): () => any { const self = this; // Not using an arrow function to preserve context passed from call site return function (this: unknown) { self._addModule(); return inject(tokens, fn).call(this); }; } } /** * @publicApi */ export function withModule(moduleDef: TestModuleMetadata): InjectSetupWrapper; export function withModule(moduleDef: TestModuleMetadata, fn: Function): () => any; export function
010636
describe('toSignal()', () => { it( 'should reflect the last emitted value of an Observable', test(() => { const counter$ = new BehaviorSubject(0); const counter = toSignal(counter$); expect(counter()).toBe(0); counter$.next(1); expect(counter()).toBe(1); counter$.next(3); expect(counter()).toBe(3); }), ); it( 'should notify when the last emitted value of an Observable changes', test(() => { let seenValue: number = 0; const counter$ = new BehaviorSubject(1); const counter = toSignal(counter$); expect(counter()).toBe(1); counter$.next(2); expect(counter()).toBe(2); }), ); it( 'should propagate an error returned by the Observable', test(() => { const counter$ = new BehaviorSubject(1); const counter = toSignal(counter$); expect(counter()).toBe(1); counter$.error('fail'); expect(counter).toThrow('fail'); }), ); it( 'should unsubscribe when the current context is destroyed', test(() => { const counter$ = new BehaviorSubject(0); const injector = Injector.create({providers: []}) as EnvironmentInjector; const counter = runInInjectionContext(injector, () => toSignal(counter$)); expect(counter()).toBe(0); counter$.next(1); expect(counter()).toBe(1); // Destroying the injector should unsubscribe the Observable. injector.destroy(); // The signal should have the last value observed. expect(counter()).toBe(1); // And this value should no longer be updating (unsubscribed). counter$.next(2); expect(counter()).toBe(1); }), ); it( 'should unsubscribe when an explicitly provided injector is destroyed', test(() => { const counter$ = new BehaviorSubject(0); const injector = Injector.create({providers: []}) as EnvironmentInjector; const counter = toSignal(counter$, {injector}); expect(counter()).toBe(0); counter$.next(1); expect(counter()).toBe(1); // Destroying the injector should unsubscribe the Observable. injector.destroy(); // The signal should have the last value observed. expect(counter()).toBe(1); // And this value should no longer be updating (unsubscribed). counter$.next(2); expect(counter()).toBe(1); }), ); it('should not require an injection context when manualCleanup is passed', () => { const counter$ = new BehaviorSubject(0); expect(() => toSignal(counter$, {manualCleanup: true})).not.toThrow(); counter$.complete(); }); it('should not unsubscribe when manualCleanup is passed', () => { const counter$ = new BehaviorSubject(0); const injector = Injector.create({providers: []}) as EnvironmentInjector; const counter = runInInjectionContext(injector, () => toSignal(counter$, {manualCleanup: true}), ); injector.destroy(); // Destroying the injector should not have unsubscribed the Observable. counter$.next(1); expect(counter()).toBe(1); counter$.complete(); // The signal should have the last value observed before the observable completed. expect(counter()).toBe(1); }); it('should not allow toSignal creation in a reactive context', () => { const counter$ = new BehaviorSubject(1); const doubleCounter = computed(() => { const counter = toSignal(counter$, {requireSync: true}); return counter() * 2; }); expect(() => doubleCounter()).toThrowError( /toSignal\(\) cannot be called from within a reactive context. Invoking `toSignal` causes new subscriptions every time./, ); }); it('should throw the error back to RxJS if rejectErrors is set', () => { let capturedObserver: Observer<number> = null!; const fake$ = { subscribe(observer: Observer<number>): Unsubscribable { capturedObserver = observer; return {unsubscribe(): void {}}; }, } as Subscribable<number>; const s = toSignal(fake$, {initialValue: 0, rejectErrors: true, manualCleanup: true}); expect(s()).toBe(0); if (capturedObserver === null) { return fail('Observer not captured as expected.'); } capturedObserver.next(1); expect(s()).toBe(1); expect(() => capturedObserver.error('test')).toThrow('test'); expect(s()).toBe(1); }); describe('with no initial value', () => { it( 'should return `undefined` if read before a value is emitted', test(() => { const counter$ = new Subject<number>(); const counter = toSignal(counter$); expect(counter()).toBeUndefined(); counter$.next(1); expect(counter()).toBe(1); }), ); it( 'should not throw if a value is emitted before called', test(() => { const counter$ = new Subject<number>(); const counter = toSignal(counter$); counter$.next(1); expect(() => counter()).not.toThrow(); }), ); }); describe('with requireSync', () => { it( 'should throw if created before a value is emitted', test(() => { const counter$ = new Subject<number>(); expect(() => toSignal(counter$, {requireSync: true})).toThrow(); }), ); it( 'should not throw if a value emits synchronously on creation', test(() => { const counter$ = new ReplaySubject<number>(1); counter$.next(1); const counter = toSignal(counter$); expect(counter()).toBe(1); }), ); }); describe('with an initial value', () => { it( 'should return the initial value if called before a value is emitted', test(() => { const counter$ = new Subject<number>(); const counter = toSignal(counter$, {initialValue: null}); expect(counter()).toBeNull(); counter$.next(1); expect(counter()).toBe(1); }), ); it( 'should not return the initial value if called after a value is emitted', test(() => { const counter$ = new Subject<number>(); const counter = toSignal(counter$, {initialValue: null}); counter$.next(1); expect(counter()).not.toBeNull(); }), ); }); describe('with an equality function', () => { it( 'should not update for values considered equal', test(() => { const counter$ = new Subject<{value: number}>(); const counter = toSignal(counter$, { initialValue: {value: 0}, equal: (a, b) => a.value === b.value, }); let updates = 0; const tracker = computed(() => { updates++; return counter(); }); expect(tracker()).toEqual({value: 0}); counter$.next({value: 1}); expect(tracker()).toEqual({value: 1}); expect(updates).toBe(2); counter$.next({value: 1}); // same value as before expect(tracker()).toEqual({value: 1}); expect(updates).toBe(2); // no downstream changes, since value was equal. counter$.next({value: 2}); expect(tracker()).toEqual({value: 2}); expect(updates).toBe(3); }), ); it( 'should update when values are reference equal but equality function says otherwise', test(() => { const numsSet = new Set<number>(); const nums$ = new BehaviorSubject<Set<number>>(numsSet); const nums = toSignal(nums$, { requireSync: true, equal: () => false, }); let updates = 0; const tracker = computed(() => { updates++; return Array.from(nums()!.values()); }); expect(tracker()).toEqual([]); numsSet.add(1); nums$.next(numsSet); // same value as before expect(tracker()).toEqual([1]); expect(updates).toBe(2); }), ); }); describe('in a @Component', () => { it('should support `toSignal` as a class member initializer', () => { @Component({ template: '{{counter()}}', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class TestCmp { // Component creation should not run inside the template effect/consumer, // hence using `toSignal` should be allowed/supported. counter$ = new Subject<number>(); counter = toSignal(this.counter$); } const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe(''); fixture.componentInstance.counter$.next(2); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('2'); }); });
010639
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Component, computed, createEnvironmentInjector, EnvironmentInjector, Injector, Signal, signal, } from '@angular/core'; import {toObservable} from '@angular/core/rxjs-interop'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {take, toArray} from 'rxjs/operators'; describe('toObservable()', () => { let fixture!: ComponentFixture<unknown>; let injector!: EnvironmentInjector; @Component({ template: '', standalone: true, }) class Cmp {} beforeEach(() => { fixture = TestBed.createComponent(Cmp); injector = TestBed.inject(EnvironmentInjector); }); function flushEffects(): void { fixture.detectChanges(); } it('should produce an observable that tracks a signal', async () => { const counter = signal(0); const counterValues = toObservable(counter, {injector}).pipe(take(3), toArray()).toPromise(); // Initial effect execution, emits 0. flushEffects(); counter.set(1); // Emits 1. flushEffects(); counter.set(2); counter.set(3); // Emits 3 (ignores 2 as it was batched by the effect). flushEffects(); expect(await counterValues).toEqual([0, 1, 3]); }); it('should propagate errors from the signal', () => { const source = signal(1); const counter = computed(() => { const value = source(); if (value === 2) { throw 'fail'; } else { return value; } }); const counter$ = toObservable(counter, {injector}); let currentValue: number = 0; let currentError: any = null; const sub = counter$.subscribe({ next: (value) => (currentValue = value), error: (err) => (currentError = err), }); flushEffects(); expect(currentValue).toBe(1); source.set(2); flushEffects(); expect(currentError).toBe('fail'); sub.unsubscribe(); }); it('monitors the signal even if the Observable is never subscribed', () => { let counterRead = false; const counter = computed(() => { counterRead = true; return 0; }); toObservable(counter, {injector}); // Simply creating the Observable shouldn't trigger a signal read. expect(counterRead).toBeFalse(); // The signal is read after effects have run. flushEffects(); expect(counterRead).toBeTrue(); }); it('should still monitor the signal if the Observable has no active subscribers', () => { const counter = signal(0); // Tracks how many reads of `counter()` there have been. let readCount = 0; const trackedCounter = computed(() => { readCount++; return counter(); }); const counter$ = toObservable(trackedCounter, {injector}); const sub = counter$.subscribe(); expect(readCount).toBe(0); flushEffects(); expect(readCount).toBe(1); // Sanity check of the read tracker - updating the counter should cause it to be read again // by the active effect. counter.set(1); flushEffects(); expect(readCount).toBe(2); // Tear down the only subscription. sub.unsubscribe(); // Now, setting the signal still triggers additional reads counter.set(2); flushEffects(); expect(readCount).toBe(3); }); it('stops monitoring the signal once injector is destroyed', () => { const counter = signal(0); // Tracks how many reads of `counter()` there have been. let readCount = 0; const trackedCounter = computed(() => { readCount++; return counter(); }); const childInjector = createEnvironmentInjector([], injector); toObservable(trackedCounter, {injector: childInjector}); expect(readCount).toBe(0); flushEffects(); expect(readCount).toBe(1); // Now, setting the signal shouldn't trigger any additional reads, as the Injector was destroyed childInjector.destroy(); counter.set(2); flushEffects(); expect(readCount).toBe(1); }); it('does not track downstream signal reads in the effect', () => { const counter = signal(0); const emits = signal(0); toObservable(counter, {injector}).subscribe(() => { // Read emits. If we are still tracked in the effect, this will cause an infinite loop by // triggering the effect again. emits(); emits.update((v) => v + 1); }); flushEffects(); expect(emits()).toBe(1); flushEffects(); expect(emits()).toBe(1); }); });
010647
/** * @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, DestroyRef, effect, inject, Injector, Signal, untracked, ɵmicrotaskEffect as microtaskEffect, } from '@angular/core'; import {Observable, ReplaySubject} from 'rxjs'; /** * Options for `toObservable`. * * @developerPreview */ export interface ToObservableOptions { /** * The `Injector` to use when creating the underlying `effect` which watches the signal. * * If this isn't specified, the current [injection context](guide/di/dependency-injection-context) * will be used. */ injector?: Injector; } /** * Exposes the value of an Angular `Signal` as an RxJS `Observable`. * * The signal's value will be propagated into the `Observable`'s subscribers using an `effect`. * * `toObservable` must be called in an injection context unless an injector is provided via options. * * @developerPreview */ export function toObservable<T>(source: Signal<T>, options?: ToObservableOptions): Observable<T> { !options?.injector && assertInInjectionContext(toObservable); const injector = options?.injector ?? inject(Injector); const subject = new ReplaySubject<T>(1); const watcher = effect( () => { let value: T; try { value = source(); } catch (err) { untracked(() => subject.error(err)); return; } untracked(() => subject.next(value)); }, {injector, manualCleanup: true}, ); injector.get(DestroyRef).onDestroy(() => { watcher.destroy(); subject.complete(); }); return subject.asObservable(); } export function toObservableMicrotask<T>( source: Signal<T>, options?: ToObservableOptions, ): Observable<T> { !options?.injector && assertInInjectionContext(toObservable); const injector = options?.injector ?? inject(Injector); const subject = new ReplaySubject<T>(1); const watcher = microtaskEffect( () => { let value: T; try { value = source(); } catch (err) { untracked(() => subject.error(err)); return; } untracked(() => subject.next(value)); }, {injector, manualCleanup: true}, ); injector.get(DestroyRef).onDestroy(() => { watcher.destroy(); subject.complete(); }); return subject.asObservable(); }
010648
/** * @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, assertNotInReactiveContext, computed, DestroyRef, inject, Injector, signal, Signal, WritableSignal, ɵRuntimeError, ɵRuntimeErrorCode, } from '@angular/core'; import {ValueEqualityFn} from '@angular/core/primitives/signals'; import {Observable, Subscribable} from 'rxjs'; /** * Options for `toSignal`. * * @publicApi */ export interface ToSignalOptions<T> { /** * Initial value for the signal produced by `toSignal`. * * This will be the value of the signal until the observable emits its first value. */ initialValue?: unknown; /** * Whether to require that the observable emits synchronously when `toSignal` subscribes. * * If this is `true`, `toSignal` will assert that the observable produces a value immediately upon * subscription. Setting this option removes the need to either deal with `undefined` in the * signal type or provide an `initialValue`, at the cost of a runtime error if this requirement is * not met. */ requireSync?: boolean; /** * `Injector` which will provide the `DestroyRef` used to clean up the Observable subscription. * * If this is not provided, a `DestroyRef` will be retrieved from the current [injection * context](guide/di/dependency-injection-context), unless manual cleanup is requested. */ injector?: Injector; /** * Whether the subscription should be automatically cleaned up (via `DestroyRef`) when * `toSignal`'s creation context is destroyed. * * If manual cleanup is enabled, then `DestroyRef` is not used, and the subscription will persist * until the `Observable` itself completes. */ manualCleanup?: boolean; /** * Whether `toSignal` should throw errors from the Observable error channel back to RxJS, where * they'll be processed as uncaught exceptions. * * In practice, this means that the signal returned by `toSignal` will keep returning the last * good value forever, as Observables which error produce no further values. This option emulates * the behavior of the `async` pipe. */ rejectErrors?: boolean; /** * A comparison function which defines equality for values emitted by the observable. * * Equality comparisons are executed against the initial value if one is provided. */ equal?: ValueEqualityFn<T>; } // Base case: no options -> `undefined` in the result type. export function toSignal<T>(source: Observable<T> | Subscribable<T>): Signal<T | undefined>; // Options with `undefined` initial value and no `requiredSync` -> `undefined`. export function toSignal<T>( source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T | undefined>> & { initialValue?: undefined; requireSync?: false; }, ): Signal<T | undefined>; // Options with `null` initial value -> `null`. export function toSignal<T>( source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T | null>> & {initialValue?: null; requireSync?: false}, ): Signal<T | null>; // Options with `undefined` initial value and `requiredSync` -> strict result type. export function toSignal<T>( source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T>> & {initialValue?: undefined; requireSync: true}, ): Signal<T>; // Options with a more specific initial value type. export function toSignal<T, const U extends T>( source: Observable<T> | Subscribable<T>, options: NoInfer<ToSignalOptions<T | U>> & {initialValue: U; requireSync?: false}, ): Signal<T | U>; /** * Get the current value of an `Observable` as a reactive `Signal`. * * `toSignal` returns a `Signal` which provides synchronous reactive access to values produced * by the given `Observable`, by subscribing to that `Observable`. The returned `Signal` will always * have the most recent value emitted by the subscription, and will throw an error if the * `Observable` errors. * * With `requireSync` set to `true`, `toSignal` will assert that the `Observable` produces a value * immediately upon subscription. No `initialValue` is needed in this case, and the returned signal * does not include an `undefined` type. * * By default, the subscription will be automatically cleaned up when the current [injection * context](guide/di/dependency-injection-context) is destroyed. For example, when `toSignal` is * called during the construction of a component, the subscription will be cleaned up when the * component is destroyed. If an injection context is not available, an explicit `Injector` can be * passed instead. * * If the subscription should persist until the `Observable` itself completes, the `manualCleanup` * option can be specified instead, which disables the automatic subscription teardown. No injection * context is needed in this configuration as well. * * @developerPreview */ e
010649
port function toSignal<T, U = undefined>( source: Observable<T> | Subscribable<T>, options?: ToSignalOptions<T | U> & {initialValue?: U}, ): Signal<T | U> { ngDevMode && assertNotInReactiveContext( toSignal, 'Invoking `toSignal` causes new subscriptions every time. ' + 'Consider moving `toSignal` outside of the reactive context and read the signal value where needed.', ); const requiresCleanup = !options?.manualCleanup; requiresCleanup && !options?.injector && assertInInjectionContext(toSignal); const cleanupRef = requiresCleanup ? (options?.injector?.get(DestroyRef) ?? inject(DestroyRef)) : null; const equal = makeToSignalEqual(options?.equal); // Note: T is the Observable value type, and U is the initial value type. They don't have to be // the same - the returned signal gives values of type `T`. let state: WritableSignal<State<T | U>>; if (options?.requireSync) { // Initially the signal is in a `NoValue` state. state = signal({kind: StateKind.NoValue}, {equal}); } else { // If an initial value was passed, use it. Otherwise, use `undefined` as the initial value. state = signal<State<T | U>>( {kind: StateKind.Value, value: options?.initialValue as U}, {equal}, ); } // Note: This code cannot run inside a reactive context (see assertion above). If we'd support // this, we would subscribe to the observable outside of the current reactive context, avoiding // that side-effect signal reads/writes are attribute to the current consumer. The current // consumer only needs to be notified when the `state` signal changes through the observable // subscription. Additional context (related to async pipe): // https://github.com/angular/angular/pull/50522. const sub = source.subscribe({ next: (value) => state.set({kind: StateKind.Value, value}), error: (error) => { if (options?.rejectErrors) { // Kick the error back to RxJS. It will be caught and rethrown in a macrotask, which causes // the error to end up as an uncaught exception. throw error; } state.set({kind: StateKind.Error, error}); }, // Completion of the Observable is meaningless to the signal. Signals don't have a concept of // "complete". }); if (options?.requireSync && state().kind === StateKind.NoValue) { throw new ɵRuntimeError( ɵRuntimeErrorCode.REQUIRE_SYNC_WITHOUT_SYNC_EMIT, (typeof ngDevMode === 'undefined' || ngDevMode) && '`toSignal()` called with `requireSync` but `Observable` did not emit synchronously.', ); } // Unsubscribe when the current context is destroyed, if requested. cleanupRef?.onDestroy(sub.unsubscribe.bind(sub)); // The actual returned signal is a `computed` of the `State` signal, which maps the various states // to either values or errors. return computed( () => { const current = state(); switch (current.kind) { case StateKind.Value: return current.value; case StateKind.Error: throw current.error; case StateKind.NoValue: // This shouldn't really happen because the error is thrown on creation. throw new ɵRuntimeError( ɵRuntimeErrorCode.REQUIRE_SYNC_WITHOUT_SYNC_EMIT, (typeof ngDevMode === 'undefined' || ngDevMode) && '`toSignal()` called with `requireSync` but `Observable` did not emit synchronously.', ); } }, {equal: options?.equal}, ); } function makeToSignalEqual<T>( userEquality: ValueEqualityFn<T> = Object.is, ): ValueEqualityFn<State<T>> { return (a, b) => a.kind === StateKind.Value && b.kind === StateKind.Value && userEquality(a.value, b.value); } const enum StateKind { NoValue, Value, Error, } interface NoValueState { kind: StateKind.NoValue; } interface ValueState<T> { kind: StateKind.Value; value: T; } interface ErrorState { kind: StateKind.Error; error: unknown; } type State<T> = NoValueState | ValueState<T> | ErrorState;
010697
/** * @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 */ // tslint:disable import {Component, Input} from '@angular/core'; @Component({ template: ` {{bla?.myInput}} `, }) class WithSafePropertyReads { @Input() myInput = 0; bla: this | undefined = this; }
010868
s imports to the `imports` in a test', async () => { writeFile( 'app.spec.ts', ` import {NgModule, Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {MatCardModule} from '@angular/material/card'; describe('bootstrapping an app', () => { it('should work', () => { TestBed.configureTestingModule({ declarations: [App], imports: [MatCardModule.forRoot({})] }); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.innerHTML).toBe('hello'); }); }); @Component({template: 'hello', standalone: false}) class App {} `, ); await runMigration('convert-to-standalone'); const content = stripWhitespace(tree.readContent('app.spec.ts')); expect(content).toContain( stripWhitespace(` @Component({template: 'hello'}) class App {} `), ); expect(content).toContain( stripWhitespace(` it('should work', () => { TestBed.configureTestingModule({ imports: [MatCardModule.forRoot({}), App] }); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.innerHTML).toBe('hello'); }); `), ); }); it('should not change testing objects with no declarations', async () => { const initialContent = ` import {NgModule, Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {ButtonModule} from './button.module'; import {MatCardModule} from '@angular/material/card'; describe('bootstrapping an app', () => { it('should work', () => { TestBed.configureTestingModule({ imports: [ButtonModule, MatCardModule] }); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>'); }); }); @Component({template: 'hello', standalone: false}) class App {} `; writeFile('app.spec.ts', initialContent); await runMigration('convert-to-standalone'); expect(tree.readContent('app.spec.ts')).toBe(initialContent); }); it('should migrate tests with a component declared through Catalyst', async () => { writeFile( 'app.spec.ts', ` import {NgModule, Component} from '@angular/core'; import {bootstrap, setupModule} from 'some_internal_path/angular/testing/catalyst'; import {ButtonModule} from './button.module'; import {MatCardModule} from '@angular/material/card'; describe('bootstrapping an app', () => { it('should work', () => { setupModule({ declarations: [App, Hello], imports: [ButtonModule, MatCardModule] }); const fixture = bootstrap(App); expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>'); }); it('should work in a different way', () => { setupModule({declarations: [App, Hello], imports: [MatCardModule]}); const fixture = bootstrap(App); expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>'); }); }); @Component({selector: 'hello', template: 'Hello', standalone: false}) class Hello {} @Component({template: '<hello></hello>', standalone: false}) class App {} `, ); await runMigration('convert-to-standalone'); const content = stripWhitespace(tree.readContent('app.spec.ts')); expect(content).toContain( stripWhitespace(` @Component({ selector: 'hello', template: 'Hello', imports: [ButtonModule, MatCardModule] }) class Hello {} `), ); expect(content).toContain( stripWhitespace(` @Component({ template: '<hello></hello>', imports: [ButtonModule, MatCardModule] }) class App {} `), ); expect(content).toContain( stripWhitespace(` it('should work', () => { setupModule({ imports: [ButtonModule, MatCardModule, App, Hello] }); const fixture = bootstrap(App); expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>'); }); `), ); expect(content).toContain( stripWhitespace(` it('should work in a different way', () => { setupModule({imports: [MatCardModule, App, Hello]}); const fixture = bootstrap(App); expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>'); }); `), ); }); it('should not copy over the NoopAnimationsModule into the imports of a test component', async () => { writeFile( 'app.spec.ts', ` import {NgModule, Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {MatCardModule} from '@angular/material/card'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; describe('bootstrapping an app', () => { it('should work', () => { TestBed.configureTestingModule({ imports: [MatCardModule, NoopAnimationsModule], declarations: [App] }); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>'); }); }); @Component({template: 'hello'}) class App {} `, ); await runMigration('convert-to-standalone'); const content = stripWhitespace(tree.readContent('app.spec.ts')); expect(content).toContain( stripWhitespace(` TestBed.configureTestingModule({ imports: [MatCardModule, NoopAnimationsModule, App] }); `), ); expect(content).toContain( stripWhitespace(` @Component({template: 'hello', imports: [MatCardModule]}) class App {} `), ); }); it('should not copy over the BrowserAnimationsModule into the imports of a test component', async () => { writeFile( 'app.spec.ts', ` import {NgModule, Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {MatCardModule} from '@angular/material/card'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; describe('bootstrapping an app', () => { it('should work', () => { TestBed.configureTestingModule({ imports: [MatCardModule, BrowserAnimationsModule], declarations: [App] }); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>'); }); }); @Component({template: 'hello', standalone: false}) class App {} `, ); await runMigration('convert-to-standalone'); const content = stripWhitespace(tree.readContent('app.spec.ts')); expect(content).toContain( stripWhitespace(` TestBed.configureTestingModule({ imports: [MatCardModule, BrowserAnimationsModule, App] }); `), ); expect(content).toContain( stripWhitespace(` @Component({template: 'hello', imports: [MatCardModule]}) class App {} `), ); }); it('should not move declarations that are not being migrated out of the declarations array', async () => { const appComponentContent = ` import {Component} from '@angular/core'; @Component({selector: 'app', template: '', standalone: false}) export class AppComponent {} `; const appModuleContent = ` import {NgModule} from '@angular/core'; import {AppComponent} from './app.component'; @NgModule({declarations: [AppComponent], bootstrap: [AppComponent]}) export class AppModule {} `; writeFile('app.component.ts', appComponentContent); writeFile('app.module.ts', appModuleContent); writeFile( 'app.spec.ts', ` import {Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {ButtonModule} from './button.module'; import {MatCardModule} from '@angular/material/card'; import {AppComponent} from './app.component'; describe('bootstrapping an app', () => { it('should work', () => { TestBed.configureTestingModule({ declarations: [AppComponent, TestComp], imports: [ButtonModule, MatCardModule] }); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.innerHTML).toBe(''); }); }); @Component({template: '', standalone: false}) class TestComp {} `, ); await runMigration('convert-to-standalone'); const testContent = stripWhitespace(tree.readContent('app.spec.ts')); expect(tree.readContent('app.module.ts')).toBe(appModuleContent); expect(tree.readContent('app.component.ts')).toBe(appComponentContent); expect(testContent).toContain( stripWhitespace(` it('should work', () => { TestBed.configureTestingModule({ declarations: [AppComponent], imports: [ButtonModule, MatCardModule, TestComp] }); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.innerHTML).toBe(''); }); `), ); expect(testContent).toContain( stripWhitespace(` @Component({ template: '', imports: [ButtonModule, MatCardModule] }) class TestComp {} `), ); }); it('should not migrate `configure
010874
.bootstrapModule call to bootstrapApplication', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({declarations: [AppComponent], bootstrap: [AppComponent]}) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; bootstrapApplication(AppComponent).catch(e => console.error(e)); `), ); expect(stripWhitespace(tree.readContent('./app/app.module.ts'))).toBe( stripWhitespace(` import {NgModule, Component} from '@angular/core'; @Component({template: 'hello'}) export class AppComponent {} `), ); }); it('should switch a platformBrowserDynamic().bootstrapModule call to bootstrapApplication', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; platformBrowserDynamic().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({declarations: [AppComponent], bootstrap: [AppComponent]}) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {bootstrapApplication} from '@angular/platform-browser'; bootstrapApplication(AppComponent).catch(e => console.error(e)); `), ); expect(stripWhitespace(tree.readContent('./app/app.module.ts'))).toBe( stripWhitespace(` import {NgModule, Component} from '@angular/core'; @Component({template: 'hello'}) export class AppComponent {} `), ); }); it('should switch a PlatformRef.bootstrapModule call to bootstrapApplication', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {PlatformRef} from '@angular/core'; const foo: PlatformRef = null!; foo.bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({declarations: [AppComponent], bootstrap: [AppComponent]}) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {PlatformRef} from '@angular/core'; import {bootstrapApplication} from '@angular/platform-browser'; const foo: PlatformRef = null!; bootstrapApplication(AppComponent).catch(e => console.error(e)); `), ); expect(stripWhitespace(tree.readContent('./app/app.module.ts'))).toBe( stripWhitespace(` import {NgModule, Component} from '@angular/core'; @Component({template: 'hello'}) export class AppComponent {} `), ); }); it('should convert the root module declarations to standalone', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.component.ts', ` import {Component} from '@angular/core'; @Component({template: '<div *ngIf="show" dir>hello</div>', standalone: false}) export class AppComponent { show = true; } `, ); writeFile( './app/dir.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[dir]', standalone: false}) export class Dir {} `, ); writeFile( './app/app.module.ts', ` import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {AppComponent} from './app.component'; import {Dir} from './dir'; @NgModule({ imports: [CommonModule], declarations: [AppComponent, Dir], bootstrap: [AppComponent] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(tree.exists('./app/app.module.ts')).toBe(false); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {CommonModule} from '@angular/common'; import {AppComponent} from './app/app.component'; import {importProvidersFrom} from '@angular/core'; bootstrapApplication(AppComponent, { providers: [importProvidersFrom(CommonModule)] }).catch(e => console.error(e)); `), ); expect(stripWhitespace(tree.readContent('./app/app.component.ts'))).toBe( stripWhitespace(` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; import {Dir} from './dir'; @Component({ template: '<div *ngIf="show" dir>hello</div>', imports: [NgIf, Dir] }) export class AppComponent { show = true; } `), ); expect(stripWhitespace(tree.readContent('./app/dir.ts'))).toBe( stripWhitespace(` import {Directive} from '@angular/core'; @Directive({selector: '[dir]'}) export class Dir {} `), ); }); it('should migrate the root component tests when converting to standalone', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.component.ts', ` import {Component} from '@angular/core'; @Component({template: 'hello', standalone: false}) export class AppComponent {} `, ); writeFile( './app/app.component.spec.ts', ` import {TestBed} from '@angular/core/testing'; import {AppComponent} from './app.component'; describe('bootstrapping an app', () => { it('should work', () => { TestBed.configureTestingModule({declarations: [AppComponent]}); const fixture = TestBed.createComponent(AppComponent); expect(fixture.nativeElement.innerHTML).toBe('hello'); }); }); `, ); writeFile( './app/app.module.ts', ` import {NgModule} from '@angular/core'; import {AppComponent} from './app.component'; @NgModule({declarations: [AppComponent], bootstrap: [AppComponent]}) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('./app/app.component.ts'))).toBe( stripWhitespace(` import {Component} from '@angular/core'; @Component({template: 'hello'}) export class AppComponent {} `), ); expect(stripWhitespace(tree.readContent('./app/app.component.spec.ts'))).toBe( stripWhitespace(` import {TestBed} from '@angular/core/testing'; import {AppComponent} from './app.component'; describe('bootstrapping an app', () => { it('should work', () => { TestBed.configureTestingModule({imports: [AppComponent]}); const fixture = TestBed.createComponent(AppComponent); expect(fixture.nativeElement.innerHTML).toBe('hello'); }); }); `), ); }); it('should copy providers and the
010876
orts` array to the `providers` and wrap them in `importProvidersFrom`', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( 'token.ts', ` import {InjectionToken} from '@angular/core'; export const token = new InjectionToken<string>('token'); `, ); writeFile( './modules/internal.module.ts', ` import {NgModule} from '@angular/core'; import {token} from '../token'; @NgModule({providers: [{provide: token, useValue: 'InternalModule'}]}) export class InternalModule {} `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {CommonModule} from '@angular/common'; import {InternalModule} from '../modules/internal.module'; import {token} from '../token'; @Component({template: 'hello', standalone: true}) export class AppComponent {} @NgModule({providers: [{provide: token, useValue: 'SameFileModule'}]}) export class SameFileModule {} @NgModule({ imports: [CommonModule, InternalModule, SameFileModule], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {SameFileModule, AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {CommonModule} from '@angular/common'; import {InternalModule} from './modules/internal.module'; import {NgModule, importProvidersFrom} from '@angular/core'; import {token} from './token'; bootstrapApplication(AppComponent, { providers: [importProvidersFrom(CommonModule, InternalModule, SameFileModule)] }).catch(e => console.error(e)); `), ); }); it('should switch RouterModule.forRoot calls with one argument to provideRouter', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [ RouterModule.forRoot([ {path: 'internal-comp', loadComponent: () => import("./routes/internal-comp").then(c => c.InternalComp) }, {path: 'external-comp', loadComponent: () => import('@external/external-comp').then(c => c.ExternalComp) } ]) ] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {provideRouter} from '@angular/router'; bootstrapApplication(AppComponent, { providers: [provideRouter([ {path: 'internal-comp', loadComponent: () => import("./app/routes/internal-comp").then(c => c.InternalComp)}, {path: 'external-comp', loadComponent: () => import('@external/external-comp').then(c => c.ExternalComp)} ])] }).catch(e => console.error(e)); `), ); }); it('should migrate a RouterModule.forRoot call with an empty config', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; import {APP_ROUTES} from './routes'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [RouterModule.forRoot(APP_ROUTES, {})] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {provideRouter} from '@angular/router'; import {APP_ROUTES} from './app/routes'; bootstrapApplication(AppComponent, { providers: [provideRouter(APP_ROUTES)] }).catch(e => console.error(e)); `), ); }); it('should migrate a router config with a preloadingStrategy to withPreloading', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; import {of} from 'rxjs'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [RouterModule.forRoot([], { preloadingStrategy: () => of(true) })] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {withPreloading, provideRouter} from '@angular/router'; import {of} from 'rxjs'; bootstrapApplication(AppComponent, { providers: [provideRouter([], withPreloading(() => of(true)))] }).catch(e => console.error(e)); `), ); }); it('should migrate a router config with enableTracing to withDebugTracing', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [RouterModule.forRoot([], { enableTracing: true })] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {withDebugTracing, provideRouter} from '@angular/router'; bootstrapApplication(AppComponent, { providers: [provideRouter([], withDebugTracing())] }).catch(e => console.error(e)); `), ); }); it('should migrate a router confi
010877
th `initialNavigation: "enabledBlocking"` to withEnabledBlockingInitialNavigation', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [RouterModule.forRoot([], { initialNavigation: 'enabledBlocking' })] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {withEnabledBlockingInitialNavigation, provideRouter} from '@angular/router'; bootstrapApplication(AppComponent, { providers: [provideRouter([], withEnabledBlockingInitialNavigation())] }).catch(e => console.error(e)); `), ); }); it('should migrate a router config with `initialNavigation: "enabled"` to withEnabledBlockingInitialNavigation', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [RouterModule.forRoot([], { initialNavigation: 'enabled' })] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {withEnabledBlockingInitialNavigation, provideRouter} from '@angular/router'; bootstrapApplication(AppComponent, { providers: [provideRouter([], withEnabledBlockingInitialNavigation())] }).catch(e => console.error(e)); `), ); }); it('should migrate a router config with `initialNavigation: "disabled"` to withDisabledInitialNavigation', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [RouterModule.forRoot([], { initialNavigation: 'disabled' })] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {withDisabledInitialNavigation, provideRouter} from '@angular/router'; bootstrapApplication(AppComponent, { providers: [provideRouter([], withDisabledInitialNavigation())] }).catch(e => console.error(e)); `), ); }); it('should migrate a router config with useHash to withHashLocation', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [RouterModule.forRoot([], { useHash: true })] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {withHashLocation, provideRouter} from '@angular/router'; bootstrapApplication(AppComponent, { providers: [provideRouter([], withHashLocation())] }).catch(e => console.error(e)); `), ); }); it('should migrate a router config with errorHandler to withNavigationErrorHandler', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [RouterModule.forRoot([], { errorHandler: () => {} })] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {withNavigationErrorHandler, provideRouter} from '@angular/router'; bootstrapApplication(AppComponent, { providers: [provideRouter([], withNavigationErrorHandler(() => {}))] }).catch(e => console.error(e)); `), ); }); it('should combine the anchorScrolling and scrollPositionRestoration of a router config into withInMemoryScrolling', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; @Component({template: 'hello', standalone: false}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [RouterModule.forRoot([], { anchorScrolling: 'enabled', scrollPositionRestoration: 'top' })] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {withInMemoryScrolling, provideRouter} from '@angular/router'; bootstrapApplication(AppComponent, { providers: [provideRouter([], withInMemoryScrolling({ anchorScrolling: 'enabled', scrollPositionRestoration: 'top' }))] }).catch(e => console.error(e)); `), ); }); it('should copy properties that d
010878
t map to a feature into withRouterConfig', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; @Component({template: 'hello'}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [RouterModule.forRoot([], { canceledNavigationResolution: 'replace', useHash: true, paramsInheritanceStrategy: 'always' })] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {withHashLocation, withRouterConfig, provideRouter} from '@angular/router'; bootstrapApplication(AppComponent, { providers: [provideRouter([], withHashLocation(), withRouterConfig({ canceledNavigationResolution: 'replace', paramsInheritanceStrategy: 'always' }))] }).catch(e => console.error(e)); `), ); }); it('should preserve a RouterModule.forRoot where the config cannot be statically analyzed', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {RouterModule} from '@angular/router'; @Component({template: 'hello'}) export class AppComponent {} const extraOptions = {useHash: true}; @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [RouterModule.forRoot([], { enableTracing: true, ...extraOptions })] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {RouterModule} from '@angular/router'; import {importProvidersFrom} from '@angular/core'; const extraOptions = {useHash: true}; bootstrapApplication(AppComponent, { providers: [importProvidersFrom(RouterModule.forRoot([], { enableTracing: true, ...extraOptions }))] }).catch(e => console.error(e)); `), ); }); it('should convert BrowserAnimationsModule references to provideAnimations', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; @Component({template: 'hello'}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [BrowserAnimationsModule] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {provideAnimations} from '@angular/platform-browser/animations'; bootstrapApplication(AppComponent, { providers: [provideAnimations()] }).catch(e => console.error(e)); `), ); }); it('should preserve BrowserAnimationsModule.withConfig calls', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; @Component({template: 'hello'}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [BrowserAnimationsModule.withConfig({disableAnimations: true})] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {importProvidersFrom} from '@angular/core'; bootstrapApplication(AppComponent, { providers: [importProvidersFrom(BrowserAnimationsModule.withConfig({disableAnimations: true}))] }).catch(e => console.error(e)); `), ); }); it('should convert NoopAnimationsModule references to provideNoopAnimations', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; @Component({template: 'hello'}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [NoopAnimationsModule] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {provideNoopAnimations} from '@angular/platform-browser/animations'; bootstrapApplication(AppComponent, { providers: [provideNoopAnimations()] }).catch(e => console.error(e)); `), ); }); it('should convert HttpClientModule references to provideHttpClient(withInterceptorsFromDi())', async () => { writeFile( 'main.ts', ` import {AppModule} from './app/app.module'; import {platformBrowser} from '@angular/platform-browser'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); `, ); writeFile( './app/app.module.ts', ` import {NgModule, Component} from '@angular/core'; import {HttpClientModule} from '@angular/common/http'; @Component({template: 'hello'}) export class AppComponent {} @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [HttpClientModule] }) export class AppModule {} `, ); await runMigration('standalone-bootstrap'); expect(stripWhitespace(tree.readContent('main.ts'))).toBe( stripWhitespace(` import {AppComponent} from './app/app.module'; import {platformBrowser, bootstrapApplication} from '@angular/platform-browser'; import {withInterceptorsFromDi, provideHttpClient} from '@angular/common/http'; bootstrapApplication(AppComponent, { providers: [provideHttpClient(withInterceptorsFromDi())] }).catch(e => console.error(e)); `), ); }); it('should omit standalone direct
010884
it('should migrate nested children components', async () => { writeFile( 'app.module.ts', ` import {NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import {routes} from './routes'; @NgModule({ imports: [RouterModule.forRoot(routes] }) export class AppModule {} `, ); writeFile( 'routes.ts', ` import {Routes} from '@angular/router'; import {TestComponent} from './test'; import {Test1Component} from './cmp1'; export const routes: Routes = [ {path: 'test', component: TestComponent}, {path: 'test1', component: Test1Component}, { path:'nested', children: [ { path: 'test', component: TestComponent, children: [ {path: 'test', component: TestComponent}, {path: 'test1', component: Test1Component}, { path: 'nested1', children: [ {path: 'test', component: TestComponent}, ], }, ], }, {path: 'test', component: TestComponent}, ] }, ]; `, ); writeFile( 'test.ts', ` import {Component} from '@angular/core'; @Component({template: 'hello', standalone: true}) export class TestComponent {} `, ); writeFile( 'cmp1.ts', ` import {Component} from '@angular/core'; @Component({template: 'hello', standalone: true}) export class Test1Component {} `, ); await runMigration('route-lazy-loading'); expect(stripWhitespace(tree.readContent('routes.ts'))).toContain( stripWhitespace(` import {Routes} from '@angular/router'; export const routes: Routes = [ {path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}, {path: 'test1', loadComponent: () => import('./cmp1').then(m => m.Test1Component)}, { path:'nested', children: [ { path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent), children: [ {path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}, {path: 'test1', loadComponent: () => import('./cmp1').then(m => m.Test1Component)}, { path: 'nested1', children: [ {path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}, ], }, ], }, {path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}, ] }, ]; `), ); }); it('should migrate routes if the routes file in is another file with type', async () => { writeFile( 'app.module.ts', ` import {NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import {routes} from './routes'; @NgModule({ imports: [RouterModule.forRoot(routes], }) export class AppModule {} `, ); writeFile( 'routes.ts', ` import {Routes, Route} from '@angular/router'; import {TestComponent} from './test'; import {Test2 as Test2Alias} from './test2'; export const routes: Routes = [{path: 'test', component: TestComponent}]; export const routes1: Route[] = [{path: 'test', component: Test2Alias}]; `, ); writeFile( 'test.ts', ` import {Component} from '@angular/core'; @Component({template: 'hello', standalone: true}) export class TestComponent {} `, ); writeFile( 'test2.ts', ` import {Component} from '@angular/core'; @Component({template: 'hello', standalone: true}) export class Test2 {} `, ); await runMigration('route-lazy-loading'); expect(stripWhitespace(tree.readContent('routes.ts'))).toContain( stripWhitespace(` import {Routes, Route} from '@angular/router'; export const routes: Routes = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}]; export const routes1: Route[] = [{path: 'test', loadComponent: () => import('./test2').then(m => m.Test2)}]; `), ); }); it('should migrate routes array if the Routes type is aliased', async () => { writeFile( 'routes.ts', ` import {Routes as Routes1, Route as Route1} from '@angular/router'; import {TestComponent} from './test'; export const routes: Routes1 = [{path: 'test', component: TestComponent}]; export const routes1: Route1[] = [{path: 'test', component: TestComponent}]; `, ); writeFile( 'test.ts', ` import {Component} from '@angular/core'; @Component({template: 'hello', standalone: true}) export class TestComponent {} `, ); await runMigration('route-lazy-loading'); expect(stripWhitespace(tree.readContent('routes.ts'))).toContain( stripWhitespace(` import {Routes as Routes1, Route as Route1} from '@angular/router'; export const routes: Routes1 = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}]; export const routes1: Route1[] = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}]; `), ); }); it('should not migrate routes if the routes array doesnt have type and is not referenced', async () => { writeFile( 'routes.ts', ` import {TestComponent} from './test'; export const routes = [{path: 'test', component: TestComponent}]; `, ); writeFile( 'test.ts', ` import {Component} from '@angular/core'; @Component({template: 'hello', standalone: true}) export class TestComponent {} `, ); let error: string | null = null; try { await runMigration('route-lazy-loading'); } catch (e: any) { error = e.message; } expect(error).toMatch(/Could not find any files to migrate under the path/); }); xit('should migrate routes if the routes file in is another file without type', async () => { writeFile( 'app.module.ts', ` import {NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import {routes} from './routes'; @NgModule({ imports: [RouterModule.forRoot(routes], }) export class AppModule {} `, ); writeFile( 'routes.ts', ` import {TestComponent} from './test'; export const routes = [{path: 'test', component: TestComponent}]; `, ); writeFile( 'test.ts', ` import {Component} from '@angular/core'; @Component({template: 'hello', standalone: true}) export class TestComponent {} `, ); await runMigration('route-lazy-loading'); expect(stripWhitespace(tree.readContent('routes.ts'))).toContain( stripWhitespace(` export const routes = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}]; `), ); }); // TODO: support multiple imports of components // ex import * as Components from './components'; // export const MenuRoutes: Routes = [ // { // path: 'menu', // component: Components.MenuListComponent // }, // ]; });
010887
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {getSystemPath, normalize, virtualFs} from '@angular-devkit/core'; import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing'; import {HostTree} from '@angular-devkit/schematics'; import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import {runfiles} from '@bazel/runfiles'; import shx from 'shelljs'; describe('Provide initializer migration', () => { it('should transform APP_INITIALIZER + useValue into provideAppInitializer', async () => { const content = await migrateCode(` import { APP_INITIALIZER } from '@angular/core'; const providers = [{ provide: APP_INITIALIZER, useValue: () => { console.log('hello'); }, multi: true, }]; `); expect(content).toContain(`import { provideAppInitializer } from '@angular/core';`); expect(content).toContain( `const providers = [provideAppInitializer(() => { console.log('hello'); })]`, ); expect(content).not.toContain('APP_INITIALIZER'); }); it('should not remove other imported symbols by mistake', async () => { const content = await migrateCode(` import { APP_INITIALIZER, input } from '@angular/core'; const providers = [{ provide: APP_INITIALIZER, useValue: () => { console.log('hello'); }, multi: true, }]; `); expect(content).toContain(`import { input, provideAppInitializer } from '@angular/core';`); }); it('should reuse provideAppInitializer if already imported', async () => { const content = await migrateCode(` import { APP_INITIALIZER, input, provideAppInitializer } from '@angular/core'; const providers = [{ provide: APP_INITIALIZER, useValue: () => { console.log('hello'); }, multi: true, }]; `); expect(content).toContain(`import { input, provideAppInitializer } from '@angular/core';`); }); it('should transform APP_INITIALIZER + useValue async function into provideAppInitializer', async () => { const content = await migrateCode(` import { APP_INITIALIZER } from '@angular/core'; const providers = [{ provide: APP_INITIALIZER, useValue: async () => { await Promise.resolve(); return 42; }, multi: true, }]; `); expect(content).toContain( `const providers = [provideAppInitializer(async () => { await Promise.resolve(); return 42; })]`, ); }); it('should transform APP_INITIALIZER + useValue symbol into provideAppInitializer', async () => { const content = await migrateCode(` import { APP_INITIALIZER } from '@angular/core'; function initializerFn() {} const providers = [{ provide: APP_INITIALIZER, useValue: initializerFn, multi: true, }]; `); expect(content).toContain(`const providers = [provideAppInitializer(initializerFn)];`); }); it('should transform APP_INITIALIZER + useFactory into provideAppInitializer', async () => { const content = await migrateCode(` import { APP_INITIALIZER } from '@angular/core'; const providers = [{ provide: APP_INITIALIZER, useFactory: () => { const service = inject(Service); return () => service.init(); }, multi: true, }]; `); expect(content).toContain(`const providers = [provideAppInitializer(() => { return (() => { const service = inject(Service); return () => service.init(); })(); })];`); }); it('should transform APP_INITIALIZER + useExisting into provideAppInitializer', async () => { const content = await migrateCode(` import { APP_INITIALIZER } from '@angular/core'; const providers = [{ provide: APP_INITIALIZER, useExisting: MY_INITIALIZER, multi: true, }]; `); expect(content).toContain(`import { inject, provideAppInitializer } from '@angular/core';`); expect(content).toContain( `const providers = [provideAppInitializer(() => inject(MY_INITIALIZER)())]`, ); }); it('should transform APP_INITIALIZER + deps into provideAppInitializer', async () => { const content = await migrateCode(` import { APP_INITIALIZER } from '@angular/core'; const providers = [{ provide: APP_INITIALIZER, useFactory: (a: ServiceA, b: ServiceB) => { return () => a.init(); }, deps: [ServiceA, ServiceB], multi: true, }]; `); expect(content).toContain(`import { inject, provideAppInitializer } from '@angular/core';`); expect(content).toContain( `const providers = [provideAppInitializer(() => { return ((a: ServiceA, b: ServiceB) => { return () => a.init(); })(inject(ServiceA), inject(ServiceB)); })];`, ); }); it('should not transform APP_INITIALIZER if multi is not set to true', async () => { const content = await migrateCode(` import { APP_INITIALIZER } from '@angular/core'; const providers = [{ provide: APP_INITIALIZER, useValue: [initializer], }]; `); expect(content).toBe(` import { APP_INITIALIZER } from '@angular/core'; const providers = [{ provide: APP_INITIALIZER, useValue: [initializer], }]; `); }); it('should not transform APP_INITIALIZER if it is not imported from @angular/core', async () => { const content = await migrateCode(` import { APP_INITIALIZER } from '@not-angular/core'; const providers = [{ provide: APP_INITIALIZER, useValue: () => { console.log('hello'); }, multi: true, }]; `); expect(content).toBe(` import { APP_INITIALIZER } from '@not-angular/core'; const providers = [{ provide: APP_INITIALIZER, useValue: () => { console.log('hello'); }, multi: true, }]; `); }); it('should transform ENVIRONMENT_INITIALIZER + useValue into provideEnvironmentInitializer', async () => { const content = await migrateCode(` import { ENVIRONMENT_INITIALIZER } from '@angular/core'; const providers = [{ provide: ENVIRONMENT_INITIALIZER, useValue: () => { console.log('hello'); }, multi: true, }]; `); expect(content).toContain(`import { provideEnvironmentInitializer } from '@angular/core';`); expect(content).toContain( `const providers = [provideEnvironmentInitializer(() => { console.log('hello'); })]`, ); expect(content).not.toContain('ENVIRONMENT_INITIALIZER'); }); it('should transform PLATFORM_INITIALIZER + useValue into providePlatformInitializer', async () => { const content = await migrateCode(` import { PLATFORM_INITIALIZER } from '@angular/core'; const providers = [{ provide: PLATFORM_INITIALIZER, useValue: () => { console.log('hello'); }, multi: true, }]; `); expect(content).toContain(`import { providePlatformInitializer } from '@angular/core';`); expect(content).toContain( `const providers = [providePlatformInitializer(() => { console.log('hello'); })]`, ); expect(content).not.toContain('PLATFORM_INITIALIZER'); }); }); async function migrateCode(content: string) { const {readFile, writeFile, runMigration} = setUpMigration(); writeFile('/index.ts', content); await runMigration(); return readFile('/index.ts'); } function setUpMigration() { const host = new TempScopedNodeJsSyncHost(); const tree = new UnitTestTree(new HostTree(host)); const runner = new SchematicTestRunner( 'test', runfiles.resolvePackageRelative('../migrations.json'), ); function writeFile(filePath: string, content: string) { host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(content)); } writeFile( '/tsconfig.json', JSON.stringify({ compilerOptions: { lib: ['es2015'], strictNullChecks: true, }, }), ); writeFile( '/angular.json', JSON.stringify({ version: 1, projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}}, }), ); const previousWorkingDir = shx.pwd(); const tmpDirPath = getSystemPath(host.root); // Switch into the temporary directory path. This allows us to run // the schematic against our custom unit test tree. shx.cd(tmpDirPath); // Get back to current directory after test. cleanupFns.push(() => shx.cd(previousWorkingDir)); return { readFile(filePath: string) { return tree.readContent(filePath); }, writeFile, async runMigration() { return await runner.runSchematic('provide-initializer', {}, tree); }, }; } let cleanupFns: Array<() => void> = []; afterEach(() => { for (const cleanupFn of cleanupFns) { cleanupFn(); } cleanupFns = []; });
010888
/** * @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 {getSystemPath, logging, normalize, virtualFs} from '@angular-devkit/core'; import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing'; import {HostTree} from '@angular-devkit/schematics'; import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import {runfiles} from '@bazel/runfiles'; import shx from 'shelljs'; describe('control flow migration', () => { let runner: SchematicTestRunner; let host: TempScopedNodeJsSyncHost; let tree: UnitTestTree; let tmpDirPath: string; let previousWorkingDir: string; let errorOutput: string[] = []; let warnOutput: string[] = []; function writeFile(filePath: string, contents: string) { host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents)); } function runMigration(path: string | undefined = undefined, format: boolean = true) { return runner.runSchematic('control-flow-migration', {path, format}, tree); } beforeEach(() => { runner = new SchematicTestRunner('test', runfiles.resolvePackageRelative('../collection.json')); host = new TempScopedNodeJsSyncHost(); tree = new UnitTestTree(new HostTree(host)); errorOutput = []; warnOutput = []; runner.logger.subscribe((e: logging.LogEntry) => { if (e.level === 'error') { errorOutput.push(e.message); } else if (e.level === 'warn') { warnOutput.push(e.message); } }); writeFile('/tsconfig.json', '{}'); writeFile( '/angular.json', JSON.stringify({ version: 1, projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}}, }), ); previousWorkingDir = shx.pwd(); tmpDirPath = getSystemPath(host.root); // Switch into the temporary directory path. This allows us to run // the schematic against our custom unit test tree. shx.cd(tmpDirPath); }); afterEach(() => { shx.cd(previousWorkingDir); shx.rm('-r', tmpDirPath); }); describe('path', () => { it('should throw an error if no files match the passed-in path', async () => { let error: string | null = null; writeFile( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[dir]'}) export class MyDir {} `, ); try { await runMigration('./foo'); } catch (e: any) { error = e.message; } expect(error).toMatch( /Could not find any files to migrate under the path .*\/foo\. Cannot run the control flow migration/, ); }); it('should throw an error if a path outside of the project is passed in', async () => { let error: string | null = null; writeFile( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[dir]'}) export class MyDir {} `, ); try { await runMigration('../foo'); } catch (e: any) { error = e.message; } expect(error).toBe('Cannot run control flow migration outside of the current project.'); }); it('should only migrate the paths that were passed in', async () => { writeFile( 'comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgIf, NgFor,NgSwitch,NgSwitchCase ,NgSwitchDefault], template: \`<div><span *ngIf="toggle">This should be hidden</span></div>\` }) class Comp { toggle = false; } `, ); writeFile( 'skip.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgIf], template: \`<div *ngIf="show">Show me</div>\` }) class Comp { show = false; } `, ); await runMigration('./comp.ts'); const migratedContent = tree.readContent('/comp.ts'); const skippedContent = tree.readContent('/skip.ts'); expect(migratedContent).toContain( 'template: `<div>@if (toggle) {<span>This should be hidden</span>}</div>`', ); expect(migratedContent).toContain('imports: []'); expect(migratedContent).not.toContain(`import {NgIf} from '@angular/common';`); expect(skippedContent).toContain('template: `<div *ngIf="show">Show me</div>`'); expect(skippedContent).toContain('imports: [NgIf]'); expect(skippedContent).toContain(`import {NgIf} from '@angular/common';`); }); });
010889
describe('ngIf', () => { it('should migrate an inline template', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgIf], template: \`<div><span *ngIf="toggle">This should be hidden</span></div>\` }) class Comp { toggle = false; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `<div>@if (toggle) {<span>This should be hidden</span>}</div>`', ); }); it('should migrate an empty case', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {ngSwitch, ngSwitchCase} from '@angular/common'; @Component({ template: \`<div [ngSwitch]="testOpts">` + `<p *ngSwitchCase="">Option 1</p>` + `<p *ngSwitchCase="2">Option 2</p>` + `</div>\` }) class Comp { testOpts = "1"; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( `template: \`<div>@switch (testOpts) { @case ('') { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>`, ); }); it('should migrate multiple inline templates in the same file', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgIf], template: \`<div><span *ngIf="toggle">This should be hidden</span></div>\` }) class Comp { toggle = false; } @Component({ template: \`<article *ngIf="show === 5">An Article</article>\` }) class OtherComp { show = 5 } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `<div>@if (toggle) {<span>This should be hidden</span>}</div>`', ); expect(content).toContain('template: `@if (show === 5) {<article>An Article</article>}`'); }); it('should migrate an external template', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [`<div>`, `<span *ngIf="show">Content here</span>`, `</div>`].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [`<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` }`, `</div>`].join('\n'), ); }); it('should migrate a template referenced by multiple components', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp {} `, ); writeFile( '/other-comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class OtherComp {} `, ); writeFile( '/comp.html', [`<div>`, `<span *ngIf="show">Content here</span>`, `</div>`].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [`<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` }`, `</div>`].join('\n'), ); }); it('should migrate an if case with no star', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [`<div>`, `<span ngIf="show">Content here</span>`, `</div>`].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [`<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` }`, `</div>`].join('\n'), ); }); it('should migrate an if case as a binding', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [`<div>`, `<span [ngIf]="show">Content here</span>`, `</div>`].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [`<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` }`, `</div>`].join('\n'), ); }); it('should migrate an if case as a binding with let variables', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-template [ngIf]="data$ | async" let-data="ngIf">`, ` {{ data }}`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe([`@if (data$ | async; as data) {`, ` {{ data }}`, `}`].join('\n')); }); it('should migrate an if case as a binding with let variable with no value', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-template [ngIf]="viewModel$ | async" let-vm>`, ` {{vm | json}}`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [`@if (viewModel$ | async; as vm) {`, ` {{vm | json}}`, `}`].join('\n'), ); }); it('should migrate an if else case as bindings', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf,NgIfElse} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<ng-template [ngIf]="show" [ngIfElse]="tmplName"><span>Content here</span></ng-template>`, `</div>`, `<ng-template #tmplName><p>Stuff</p></ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` } @else {`, ` <p>Stuff</p>`, ` }`, `</div>\n`, ].join('\n'), ); });
010890
it('should migrate an if then else case as bindings', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf,NgIfElse} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<ng-template [ngIf]="show" [ngIfElse]="elseTmpl" [ngIfThenElse]="thenTmpl">Ignore Me</ng-template>`, `</div>`, `<ng-template #elseTmpl><p>Stuff</p></ng-template>`, `<ng-template #thenTmpl><span>Content here</span></ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` } @else {`, ` <p>Stuff</p>`, ` }`, `</div>\n`, ].join('\n'), ); }); it('should migrate an if else case with condition that has `then` in the string', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf,NgIfElse} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [`<div *ngIf="!(isAuthenticated$ | async) && !reauthRequired">`, ` Hello!`, `</div>`].join( '\n', ), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (!(isAuthenticated$ | async) && !reauthRequired) {`, ` <div>`, ` Hello!`, ` </div>`, `}`, ].join('\n'), ); }); it('should migrate an if case on a container', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<ng-container *ngIf="show"><span>Content here</span></ng-container>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [`<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` }`, `</div>`].join('\n'), ); }); it('should migrate an if case on an empty container', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-container`, ` *ngIf="true; then template"`, `></ng-container>`, `<ng-template #template>`, ` Hello!`, `</ng-template> `, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe([`@if (true) {`, ` Hello!`, `}\n`].join('\n')); }); it('should migrate an if case with an ng-template with i18n', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<ng-template *ngIf="show" i18n="@@something"><span>Content here</span></ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <ng-container i18n="@@something"><span>Content here</span></ng-container>`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate an if case with an ng-template with empty i18n', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<ng-template *ngIf="show" i18n><span>Content here</span></ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <ng-container i18n><span>Content here</span></ng-container>`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate an if case with an ng-container with i18n', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<ng-container *ngIf="show" i18n="@@something"><span>Content here</span></ng-container>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <ng-container i18n="@@something"><span>Content here</span></ng-container>`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate a bound if case on an ng-template with i18n', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-template`, ` [ngIf]="data$ | async"`, ` let-data="ngIf"`, ` i18n="@@i18n-label">`, ` {{ data }}`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (data$ | async; as data) {`, ` <ng-container i18n="@@i18n-label">`, ` {{ data }}`, `</ng-container>`, `}`, ].join('\n'), ); });
010891
it('should migrate an if case with an ng-container with empty i18n', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<ng-container *ngIf="show" i18n><span>Content here</span></ng-container>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <ng-container i18n><span>Content here</span></ng-container>`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate a bound NgIfElse case with ng-templates and remove all unnecessary attributes', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-template`, ` [ngIf]="fooTemplate"`, ` [ngIfElse]="barTemplate"`, ` [ngTemplateOutlet]="fooTemplate"`, `></ng-template>`, `<ng-template #fooTemplate>Foo</ng-template>`, `<ng-template #barTemplate>Bar</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (fooTemplate) {`, ` <ng-template`, ` [ngTemplateOutlet]="fooTemplate"`, ` ></ng-template>`, `} @else {`, ` Bar`, `}`, `<ng-template #fooTemplate>Foo</ng-template>\n`, ].join('\n'), ); }); it('should migrate a bound NgIfThenElse case with ng-templates with i18n', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<ng-template [ngIf]="show" [ngIfThenElse]="thenTmpl" [ngIfElse]="elseTmpl">ignored</ng-template>`, `</div>`, `<ng-template #thenTmpl i18n="@@something"><span>Content here</span></ng-template>`, `<ng-template #elseTmpl i18n="@@somethingElse"><p>other</p></ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <ng-container i18n="@@something"><span>Content here</span></ng-container>`, ` } @else {`, ` <ng-container i18n="@@somethingElse"><p>other</p></ng-container>`, ` }`, `</div>\n`, ].join('\n'), ); }); it('should migrate a bound NgIfElse case with ng-templates with i18n', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<ng-template [ngIf]="show" [ngIfElse]="elseTmpl" i18n="@@something"><span>Content here</span></ng-template>`, `</div>`, `<ng-template #elseTmpl i18n="@@somethingElse"><p>other</p></ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <ng-container i18n="@@something"><span>Content here</span></ng-container>`, ` } @else {`, ` <ng-container i18n="@@somethingElse"><p>other</p></ng-container>`, ` }`, `</div>\n`, ].join('\n'), ); }); it('should migrate an NgIfElse case with ng-templates with multiple i18n attributes', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-template *ngIf="false; else barTempl" i18n="@@foo">`, ` Foo`, `</ng-template>`, `<ng-template i18n="@@bar" #barTempl> Bar </ng-template>`, `<a *ngIf="true" i18n="@@bam">Bam</a>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (false) {`, ` <ng-container i18n="@@foo">`, ` Foo`, `</ng-container>`, `} @else {`, ` <ng-container i18n="@@bar"> Bar </ng-container>`, `}`, `@if (true) {`, ` <a i18n="@@bam">Bam</a>`, `}`, ].join('\n'), ); }); it('should migrate an if else case', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<span *ngIf="show; else elseBlock">Content here</span>`, `<ng-template #elseBlock>Else Content</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` } @else {`, ` Else Content`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate an if else case with no semicolon before else', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<span *ngIf="show else elseBlock">Content here</span>`, `<ng-template #elseBlock>Else Content</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` } @else {`, ` Else Content`, ` }`, `</div>`, ].join('\n'), ); });
010892
it('should migrate an if then else case with no semicolons', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<span *ngIf="show then thenTmpl else elseTmpl"></span>`, `<ng-template #thenTmpl><span>Content here</span></ng-template>`, `<ng-template #elseTmpl>Else Content</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` } @else {`, ` Else Content`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate an if else case with a colon after else', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<span *ngIf="show; else: elseTmpl">Content here</span>`, `<ng-template #elseTmpl>Else Content</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` } @else {`, ` Else Content`, ` }`, `</div>`, ].join('\n'); expect(actual).toBe(expected); }); it('should migrate an if else case with no space after ;', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<span *ngIf="show;else elseBlock">Content here</span>`, `<ng-template #elseBlock>Else Content</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` } @else {`, ` Else Content`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate an if then else case with no spaces before ;', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<span *ngIf="show;then thenBlock;else elseBlock">Ignored</span>`, `<ng-template #thenBlock><div>THEN Stuff</div></ng-template>`, `<ng-template #elseBlock>Else Content</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <div>THEN Stuff</div>`, ` } @else {`, ` Else Content`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate an if else case when the template is above the block', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<ng-template #elseBlock>Else Content</ng-template>`, `<span *ngIf="show; else elseBlock">Content here</span>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` } @else {`, ` Else Content`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate an if then else case', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<span *ngIf="show; then thenBlock; else elseBlock">Ignored</span>`, `<ng-template #thenBlock><div>THEN Stuff</div></ng-template>`, `<ng-template #elseBlock>Else Content</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <div>THEN Stuff</div>`, ` } @else {`, ` Else Content`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate an if then else case with templates in odd places', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<ng-template #elseBlock>Else Content</ng-template>`, `<span *ngIf="show; then thenBlock; else elseBlock">Ignored</span>`, `<ng-template #thenBlock><div>THEN Stuff</div></ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <div>THEN Stuff</div>`, ` } @else {`, ` Else Content`, ` }`, `</div>`, ].join('\n'), ); });
010893
it('should migrate a complex if then else case on ng-containers', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-container>`, ` <ng-container`, ` *ngIf="loading; then loadingTmpl; else showTmpl"`, ` >`, ` </ng-container>`, `<ng-template #showTmpl>`, ` <ng-container`, ` *ngIf="selected; else emptyTmpl"`, ` >`, ` <div></div>`, ` </ng-container>`, `</ng-template>`, `<ng-template #emptyTmpl>`, ` Empty`, `</ng-template>`, `</ng-container>`, `<ng-template #loadingTmpl>`, ` <p>Loading</p>`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<ng-container>`, ` @if (loading) {`, ` <p>Loading</p>`, ` } @else {`, ` @if (selected) {`, ` <div></div>`, ` } @else {`, ` Empty`, ` }`, ` }`, `</ng-container>\n`, ].join('\n'), ); }); it('should migrate but not remove ng-templates when referenced elsewhere', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<span *ngIf="show; then thenBlock; else elseBlock">Ignored</span>`, `<ng-template #thenBlock><div>THEN Stuff</div></ng-template>`, `<ng-template #elseBlock>Else Content</ng-template>`, `</div>`, `<ng-container *ngTemplateOutlet="elseBlock"></ng-container>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (show) {`, ` <div>THEN Stuff</div>`, ` } @else {`, ` Else Content`, ` }`, ` <ng-template #elseBlock>Else Content</ng-template>`, `</div>`, `<ng-container *ngTemplateOutlet="elseBlock"></ng-container>`, ].join('\n'), ); }); it('should not remove ng-templates used by other directives', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-template #blockUsedElsewhere><div>Block</div></ng-template>`, `<ng-container *ngTemplateOutlet="blockUsedElsewhere"></ng-container>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<ng-template #blockUsedElsewhere><div>Block</div></ng-template>`, `<ng-container *ngTemplateOutlet="blockUsedElsewhere"></ng-container>`, ].join('\n'), ); }); it('should migrate if with alias', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { user$ = of({ name: 'Jane' }}) } `, ); writeFile('/comp.html', `<div *ngIf="user$ | async as user">{{ user.name }}</div>`); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe(`@if (user$ | async; as user) {<div>{{ user.name }}</div>}`); }); it('should migrate if/else with alias', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { user$ = of({ name: 'Jane' }}) } `, ); writeFile( '/comp.html', [ `<div>`, `<div *ngIf="user$ | async as user; else noUserBlock">{{ user.name }}</div>`, `<ng-template #noUserBlock>No user</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (user$ | async; as user) {`, ` <div>{{ user.name }}</div>`, ` } @else {`, ` No user`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate if/else with semicolon at end', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { user$ = of({ name: 'Jane' }}) } `, ); writeFile( '/comp.html', [ `<div>`, `<div *ngIf="user$ | async as user; else noUserBlock;">{{ user.name }}</div>`, `<ng-template #noUserBlock>No user</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (user$ | async; as user) {`, ` <div>{{ user.name }}</div>`, ` } @else {`, ` No user`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate if/else with let variable', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { user$ = of({ name: 'Jane' }}) } `, ); writeFile( '/comp.html', [ `<div>`, `<div *ngIf="user of users; else noUserBlock; let tooltipContent;">{{ user.name }}</div>`, `<ng-template #noUserBlock>No user</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @if (user of users; as tooltipContent) {`, ` <div>{{ user.name }}</div>`, ` } @else {`, ` No user`, ` }`, `</div>`, ].join('\n'), ); });