_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_323720_326106
`, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('i0.ɵɵdefineInjector({ imports: [StandaloneCmp] })'); }); it('should filter directives & pipes out of NgModule.imports', () => { env.write( 'test.ts', ` import {Directive, ModuleWithProviders, NgModule, Pipe} from '@angular/core'; @Directive({standalone: true}) export class StandaloneDir {} @NgModule({}) export class SubModule {}; declare function SubModuleWithProviders(): ModuleWithProviders<SubModule>; @Pipe({standalone: true, name: 'st'}) export class StandalonePipe {} export const LOCAL_ARRAY = [StandaloneDir, StandalonePipe, SubModule]; export const ARRAY_WITH_MWP = [StandalonePipe, SubModuleWithProviders()]; @NgModule({ imports: [ StandaloneDir, ...LOCAL_ARRAY, SubModule, SubModuleWithProviders(), ARRAY_WITH_MWP, ], }) export class Module {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const expectedImports = 'SubModule, SubModule, SubModuleWithProviders(), ARRAY_WITH_MWP'; expect(jsContents.replace(/\s/g, '')).toContain( `Module.ɵinj=/*@__PURE__*/i0.ɵɵdefineInjector({imports:[${expectedImports.replace( /\s/g, '', )}]});`, ); }); }); describe('input transforms', () => { it('should compile a directive input with a transform function', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; function toNumber(value: boolean | string) { return 1; } @Directive({standalone: true}) export class Dir { @Input({transform: toNumber}) value!: number; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('inputs: { value: [2, "value", "value", toNumber] }'); expect(jsContents).toContain('features: [i0.ɵɵInputTransformsFeature]'); expect
{ "end_byte": 326106, "start_byte": 323720, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_326112_334379
ntents).toContain('static ngAcceptInputType_value: boolean | string;'); }); it('should compile a component input with a transform function', () => { env.write( '/test.ts', ` import {Component, Input} from '@angular/core'; function toNumber(value: boolean | string) { return 1; } @Component({standalone: true, template: 'hello'}) export class Dir { @Input({transform: toNumber}) value!: number; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('inputs: { value: [2, "value", "value", toNumber] }'); expect(jsContents).toContain('features: [i0.ɵɵInputTransformsFeature]'); expect(dtsContents).toContain('static ngAcceptInputType_value: boolean | string;'); }); it('should compile an input with a transform function that contains a generic parameter', () => { env.write( '/types.ts', ` export interface GenericWrapper<T> { value: T; } `, ); env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; import {GenericWrapper} from './types'; function toNumber(value: boolean | string | GenericWrapper<string>) { return 1; } @Directive({standalone: true}) export class Dir { @Input({transform: toNumber}) value!: number; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('inputs: { value: [2, "value", "value", toNumber] }'); expect(jsContents).toContain('features: [i0.ɵɵInputTransformsFeature]'); expect(dtsContents).toContain('import * as i1 from "./types"'); expect(dtsContents).toContain( 'static ngAcceptInputType_value: boolean | string | i1.GenericWrapper<string>;', ); }); it('should compile an input with a transform function that contains nested generic parameters', () => { env.write( '/types.ts', ` export interface GenericWrapper<T> { value: T; } `, ); env.write( '/other-types.ts', ` export class GenericClass<T> { foo: T; } `, ); env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; import {GenericWrapper} from './types'; import {GenericClass} from './other-types'; function toNumber(value: boolean | string | GenericWrapper<GenericClass<string>>) { return 1; } @Directive({standalone: true}) export class Dir { @Input({transform: toNumber}) value!: number; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('inputs: { value: [2, "value", "value", toNumber] }'); expect(jsContents).toContain('features: [i0.ɵɵInputTransformsFeature]'); expect(dtsContents).toContain('import * as i1 from "./types"'); expect(dtsContents).toContain('import * as i2 from "./other-types"'); expect(dtsContents).toContain( 'static ngAcceptInputType_value: boolean | string | i1.GenericWrapper<i2.GenericClass<string>>;', ); }); it('should compile an input with an external transform function', () => { env.write( 'node_modules/external/index.d.ts', ` export interface ExternalObj { foo: boolean; } export type ExternalToNumberType = string | boolean | ExternalObj; export declare function externalToNumber(val: ExternalToNumberType): number; `, ); env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; import {externalToNumber} from 'external'; @Directive({standalone: true}) export class Dir { @Input({transform: externalToNumber}) value!: number; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain(`import { externalToNumber } from 'external';`); expect(jsContents).toContain('inputs: { value: [2, "value", "value", externalToNumber] }'); expect(jsContents).toContain('features: [i0.ɵɵInputTransformsFeature]'); expect(dtsContents).toContain('import * as i1 from "external";'); expect(dtsContents).toContain('static ngAcceptInputType_value: i1.ExternalToNumberType;'); }); it('should compile an input with an inline transform function', () => { env.write( 'node_modules/external/index.d.ts', ` export interface ExternalObj { foo: boolean; } export type ExternalToNumberType = string | boolean | ExternalObj; `, ); env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; import {ExternalToNumberType} from 'external'; @Directive({standalone: true}) export class Dir { @Input({transform: (value: ExternalToNumberType) => value ? 1 : 0}) value!: number; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain( 'inputs: { value: [2, "value", "value", (value) => value ? 1 : 0] }', ); expect(jsContents).toContain('features: [i0.ɵɵInputTransformsFeature]'); expect(dtsContents).toContain('import * as i1 from "external";'); expect(dtsContents).toContain('static ngAcceptInputType_value: i1.ExternalToNumberType;'); }); it('should compile an input referencing an imported function with literal types', () => { env.write( '/transforms.ts', ` export function toBoolean(value: boolean | '' | 'true' | 'false'): boolean { return !!value; } `, ); env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; import {toBoolean} from './transforms'; @Directive({standalone: true}) export class Dir { @Input({transform: toBoolean}) value!: number; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('inputs: { value: [2, "value", "value", toBoolean] }'); expect(jsContents).toContain('features: [i0.ɵɵInputTransformsFeature]'); expect(dtsContents).toContain( `static ngAcceptInputType_value: boolean | "" | "true" | "false";`, ); }); it('should compile a directive input with a transform function with a `this` typing', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; function toNumber(this: Dir, value: boolean | string) { return 1; } @Directive({standalone: true}) export class Dir { @Input({transform: toNumber}) value!: number; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('inputs: { value: [2, "value", "value", toNumber] }'); expect(jsContents).toContain('features: [i0.ɵɵInputTransformsFeature]'); expect(dtsContents).toContain
{ "end_byte": 334379, "start_byte": 326112, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_334387_342795
ngAcceptInputType_value: boolean | string;'); }); it('should treat an input transform function only with a `this` parameter as unknown', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; function toNumber(this: Dir) { return 1; } @Directive({standalone: true}) export class Dir { @Input({transform: toNumber}) value!: number; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('inputs: { value: [2, "value", "value", toNumber] }'); expect(jsContents).toContain('features: [i0.ɵɵInputTransformsFeature]'); expect(dtsContents).toContain('static ngAcceptInputType_value: unknown;'); }); it('should insert the InputTransformsFeature before the InheritDefinitionFeature', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; function toNumber(value: boolean | string) { return 1; } @Directive() export class ParentDir {} @Directive() export class Dir extends ParentDir { @Input({transform: toNumber}) value!: number; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('inputs: { value: [2, "value", "value", toNumber] }'); expect(jsContents).toContain( 'features: [i0.ɵɵInputTransformsFeature, i0.ɵɵInheritDefinitionFeature]', ); expect(dtsContents).toContain('static ngAcceptInputType_value: boolean | string;'); }); it('should compile an input with using an ambient type in the transform function', () => { env.write( 'node_modules/external/index.d.ts', ` import {ElementRef} from '@angular/core'; export declare function coerceElement(value: HTMLElement | ElementRef<HTMLElement>): HTMLElement; `, ); env.write( '/test.ts', ` import {Directive, Input, Component} from '@angular/core'; import {coerceElement} from 'external'; @Directive({standalone: true}) export class Dir { @Input({transform: coerceElement}) element!: HTMLElement; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain( 'inputs: { element: [2, "element", "element", coerceElement] }', ); expect(jsContents).toContain('features: [i0.ɵɵInputTransformsFeature]'); expect(dtsContents).toContain( 'static ngAcceptInputType_element: HTMLElement | i0.ElementRef<HTMLElement>;', ); }); }); describe('debug info', () => { it('should set forbidOrphanRendering debug info for component when the option forbidOrphanComponents is set', () => { env.write( 'tsconfig.json', JSON.stringify({ extends: './tsconfig-base.json', angularCompilerOptions: { forbidOrphanComponents: true, }, }), ); env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ template: '...', }) export class Comp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch('forbidOrphanRendering: true'); }); it('should set forbidOrphanRendering debug info for standalone components when the option forbidOrphanComponents is set', () => { env.write( 'tsconfig.json', JSON.stringify({ extends: './tsconfig-base.json', angularCompilerOptions: { forbidOrphanComponents: true, }, }), ); env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ standalone: true, template: '...', }) export class Comp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch('forbidOrphanRendering: true'); }); it('should not set forbidOrphanRendering debug info when the option forbidOrphanComponents is not set', () => { env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ template: '...', }) export class Comp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toMatch('forbidOrphanRendering:'); }); }); describe('tsickle compatibility', () => { it('should preserve fileoverview comments', () => { env.write( 'test.ts', ` // type-only import that will be elided. import {SimpleChanges} from '@angular/core'; export class X { p: SimpleChanges = null!; } `, ); const options: CompilerOptions = { strict: true, strictTemplates: true, target: ts.ScriptTarget.Latest, module: ts.ModuleKind.ESNext, annotateForClosureCompiler: true, }; const program = new NgtscProgram(['/test.ts'], options, createCompilerHost({options})); const transformers = program.compiler.prepareEmit().transformers; // Add a "fake tsickle" transform before Angular's transform. transformers.before!.unshift((ctx) => (sf: ts.SourceFile) => { const tsickleFileOverview = ctx.factory.createNotEmittedStatement(sf); ts.setSyntheticLeadingComments(tsickleFileOverview, [ { kind: ts.SyntaxKind.MultiLineCommentTrivia, text: `* * @fileoverview Closure comment * @suppress bla1 * @suppress bla2 `, pos: -1, end: -1, hasTrailingNewLine: true, }, ]); return ctx.factory.updateSourceFile( sf, [tsickleFileOverview, ...sf.statements], sf.isDeclarationFile, sf.referencedFiles, sf.typeReferenceDirectives, sf.hasNoDefaultLib, sf.libReferenceDirectives, ); }); const {diagnostics, emitSkipped} = program .getTsProgram() .emit(undefined, undefined, undefined, undefined, transformers); expect(diagnostics.length).toBe(0); expect(emitSkipped).toBe(false); expect(env.getContents('/test.js')).toContain(`* @fileoverview Closure comment`); }); }); }); function expectTokenAtPosition<T extends ts.Node>( sf: ts.SourceFile, pos: number, guard: (node: ts.Node) => node is T, ): T { // getTokenAtPosition is part of TypeScript's private API. const node = (ts as any).getTokenAtPosition(sf, pos) as ts.Node; expect(guard(node)).toBe(true); return node as T; } });
{ "end_byte": 342795, "start_byte": 334387, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_0_428
/** * @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 {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles();
{ "end_byte": 428, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_430_9543
runInEachFileSystem(() => { describe('ngtsc incremental compilation (semantic changes)', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.enableMultipleCompilations(); env.tsconfig(); }); function expectToHaveWritten(files: string[]): void { const set = env.getFilesWrittenSinceLastFlush(); const expectedSet = new Set<string>(); for (const file of files) { expectedSet.add(file); expectedSet.add(file.replace(/\.js$/, '.d.ts')); } expect(set).toEqual(expectedSet); // Reset for the next compilation. env.flushWrittenFileTracking(); } describe('changes to public api', () => { it('should not recompile dependent components when public api is unchanged', () => { // Testing setup: ADep is a component with an input and an output, and is consumed by two // other components - ACmp within its same NgModule, and BCmp which depends on ADep via an // NgModule import. // // ADep is changed during the test without affecting its public API, and the test asserts // that both ACmp and BCmp which consume ADep are not re-emitted. env.write( 'a/dep.ts', ` import {Component, Input, Output, EventEmitter} from '@angular/core'; @Component({ selector: 'a-dep', template: 'a-dep', standalone: false, }) export class ADep { @Input() input!: string; @Output() output = new EventEmitter<string>(); } `, ); env.write( 'a/cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'a-cmp', template: '<a-dep></a-dep>', standalone: false, }) export class ACmp {} `, ); env.write( 'a/mod.ts', ` import {NgModule} from '@angular/core'; import {ADep} from './dep'; import {ACmp} from './cmp'; @NgModule({ declarations: [ADep, ACmp], exports: [ADep], }) export class AMod {} `, ); env.write( 'b/cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'b-cmp', template: '<a-dep></a-dep>', standalone: false, }) export class BCmp {} `, ); env.write( 'b/mod.ts', ` import {NgModule} from '@angular/core'; import {BCmp} from './cmp'; import {AMod} from '../a/mod'; @NgModule({ declarations: [BCmp], imports: [AMod], }) export class BMod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); // Change ADep without affecting its public API. env.write( 'a/dep.ts', ` import {Component, Input, Output, EventEmitter} from '@angular/core'; @Component({ selector: 'a-dep', template: 'a-dep', standalone: false, }) export class ADep { @Input() input!: string; @Output() output = new EventEmitter<number>(); // changed from string to number } `, ); env.driveMain(); expectToHaveWritten([ // ADep is written because it was updated. '/a/dep.js', // AMod is written because it has a direct dependency on ADep. '/a/mod.js', // Nothing else is written because the public API of AppCmpB was not affected ]); }); it('should not recompile components that do not use a changed directive', () => { // Testing setup: ADep is a directive with an input and output, which is visible to two // components which do not use ADep in their templates - ACmp within the same NgModule, and // BCmp which has visibility of ADep via an NgModule import. // // During the test, ADep's public API is changed, and the test verifies that neither ACmp // nor BCmp are re-emitted. env.write( 'a/dep.ts', ` import {Directive, Input, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[a-dep]', standalone: false, }) export class ADep { @Input() input!: string; @Output() output = new EventEmitter<string>(); } `, ); env.write( 'a/cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'a-cmp', template: 'Does not use a-dep.', standalone: false, }) export class ACmp {} `, ); env.write( 'a/mod.ts', ` import {NgModule} from '@angular/core'; import {ADep} from './dep'; import {ACmp} from './cmp'; @NgModule({ declarations: [ADep, ACmp], exports: [ADep], }) export class AMod {} `, ); env.write( 'b/cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'b-cmp', template: 'Does not use a-dep.', standalone: false, }) export class BCmp {} `, ); env.write( 'b/mod.ts', ` import {NgModule} from '@angular/core'; import {BCmp} from './cmp'; import {AMod} from '../a/mod'; @NgModule({ declarations: [BCmp], imports: [AMod], }) export class BMod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); // Update ADep and change its public API. env.write( 'a/dep.ts', ` import {Directive, Input, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[a-dep]', standalone: false, }) export class ADep { @Input() input!: string; @Output('output-renamed') // public binding name of the @Output is changed. output = new EventEmitter<string>(); } `, ); env.driveMain(); expectToHaveWritten([ // ADep is written because it was updated. '/a/dep.js', // AMod is written because it has a direct dependency on ADep. '/a/mod.js', // Nothing else is written because neither ACmp nor BCmp depend on ADep. ]); }); it('should recompile components for which a directive usage is introduced', () => { // Testing setup: Cmp is a component with a template that would match a directive with the // selector '[dep]' if one existed. Dep is a directive with a different selector initially. // // During the test, Dep's selector is updated to '[dep]', causing it to begin matching the // template of Cmp. The test verifies that Cmp is re-emitted after this change. env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[does-not-match]', standalone: false, }) export class Dep {} `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', // selector changed to now match inside Cmp's template standalone: false, }) export class Dep {} `, ); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because the directives matched in its template have changed. '/cmp.js', ]); });
{ "end_byte": 9543, "start_byte": 430, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_9551_17566
it('should recompile components for which a directive usage is removed', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, Dep's selector is changed, causing it to no longer match the template of // Cmp. The test verifies that Cmp is re-emitted after this change. env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep {} `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[does-not-match]', // selector changed to no longer match Cmp's template standalone: false, }) export class Dep {} `, ); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because the directives matched in its template have changed. '/cmp.js', ]); }); it('should recompile dependent components when an input is added', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an input is added to Dep, and the test verifies that Cmp is re-emitted. env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep {} `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'dep.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { @Input() input!: string; // adding this changes Dep's public API } `, ); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile dependent components when an input is renamed', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an input of Dep is renamed, and the test verifies that Cmp is // re-emitted. env.write( 'dep.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { @Input() input!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'dep.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { @Input('renamed') input!: string; // renaming this changes Dep's public API } `, ); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile dependent components when an input is removed', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an input of Dep is removed, and the test verifies that Cmp is // re-emitted. env.write( 'dep.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { @Input() input!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { // Dep's input has been removed, which changes its public API } `, ); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); });
{ "end_byte": 17566, "start_byte": 9551, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_17574_25759
it('should recompile dependent components when an output is added', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an output of Dep is added, and the test verifies that Cmp is re-emitted. env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep {} `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'dep.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { @Output() output = new EventEmitter<string>(); // added, which changes Dep's public API } `, ); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile dependent components when an output is renamed', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an output of Dep is renamed, and the test verifies that Cmp is // re-emitted. env.write( 'dep.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { @Output() output = new EventEmitter<string>(); } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'dep.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { @Output('renamed') output = new EventEmitter<string>(); // public API changed } `, ); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile dependent components when an output is removed', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an output of Dep is removed, and the test verifies that Cmp is // re-emitted. env.write( 'dep.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { @Output() output = new EventEmitter<string>(); } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { // Dep's output has been removed, which changes its public API } `, ); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); }); it('should recompile dependent components when exportAs clause changes', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]' and an exportAs clause. // // During the test, the exportAs clause of Dep is changed, and the test verifies that Cmp is // re-emitted. env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', exportAs: 'depExport1', standalone: false, }) export class Dep {} `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', exportAs: 'depExport2', // changing this changes Dep's public API standalone: false, }) export class Dep {} `, ); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Cmp is written because it depends on Dep, which has changed in its public API. '/cmp.js', ]); });
{ "end_byte": 25759, "start_byte": 17574, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_25767_30672
it('should recompile components when a pipe is newly matched because it was renamed', () => { // Testing setup: Cmp uses two pipes (PipeA and PipeB) in its template. // // During the test, the selectors of these pipes are swapped. This ensures that Cmp's // template is still valid, since both pipe names continue to be valid within it. However, // as the identity of each pipe is now different, the effective public API of those pipe // usages has changed. The test then verifies that Cmp is re-emitted. env.write( 'pipes.ts', ` import {Pipe} from '@angular/core'; @Pipe({ name: 'pipeA', standalone: false, }) export class PipeA { transform(value: any): any { return value; } } @Pipe({ name: 'pipeB', standalone: false, }) export class PipeB { transform(value: any): any { return value; } } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '{{ value | pipeA }} {{ value | pipeB }}', standalone: false, }) export class Cmp { value!: string; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {PipeA, PipeB} from './pipes'; import {Cmp} from './cmp'; @NgModule({ declarations: [Cmp, PipeA, PipeB], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'pipes.ts', ` import {Pipe} from '@angular/core'; @Pipe({ name: 'pipeB', // swapped with PipeB's selector standalone: false, }) export class PipeA { transform(value: any): any { return value; } } @Pipe({ name: 'pipeA', // swapped with PipeA's selector standalone: false, }) export class PipeB { transform(value: any): any { return value; } } `, ); env.driveMain(); expectToHaveWritten([ // PipeA and PipeB have directly changed. '/pipes.js', // Mod depends directly on PipeA and PipeB. '/mod.js', // Cmp depends on the public APIs of PipeA and PipeB, which have changed (as they've // swapped). '/cmp.js', ]); }); it('should recompile dependent components when an input becomes required', () => { // Testing setup: Cmp is a component with a template that matches a directive Dep with the // initial selector '[dep]'. // // During the test, an input of Dep becomes required, and the test verifies that Cmp is // re-emitted. env.write( 'dep.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { @Input() input!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<div dep input="hello"></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'dep.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep { @Input({required: true}) input!: string; // making this required changes the public API } `, ); env.driveMain(); expectToHaveWritten([ // Dep is written because it was directly updated. '/dep.js', // Dep is written because it was directly updated. '/dep.d.ts', // Mod is written because it has a direct dependency on Dep. '/mod.js', // Mod is written because it depends on Dep, which has changed in its public API. '/mod.d.ts', ]); }); });
{ "end_byte": 30672, "start_byte": 25767, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_30678_35909
describe('external declarations', () => { it('should not recompile components that use external declarations that are not changed', () => { // Testing setup: Two components (MyCmpA and MyCmpB) both depend on an external directive // which matches their templates, via an NgModule import. // // During the test, MyCmpA is invalidated, and the test verifies that only MyCmpA and not // MyCmpB is re-emitted. env.write( 'node_modules/external/index.d.ts', ` import * as ng from '@angular/core'; export declare class ExternalDir { static ɵdir: ng.ɵɵDirectiveDefWithMeta<ExternalDir, "[external]", never, {}, {}, never>; } export declare class ExternalMod { static ɵmod: ng.ɵɵNgModuleDefWithMeta<ExternalMod, [typeof ExternalDir], never, [typeof ExternalDir]>; } `, ); env.write( 'cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div external></div>', standalone: false, }) export class MyCmpA {} `, ); env.write( 'cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div external></div>', standalone: false, }) export class MyCmpB {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {ExternalMod} from 'external'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; @NgModule({ declarations: [MyCmpA, MyCmpB], imports: [ExternalMod], }) export class MyMod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); // Invalidate MyCmpA, causing it to be re-emitted. env.invalidateCachedFile('cmp-a.ts'); env.driveMain(); expectToHaveWritten([ // MyMod is written because it has a direct reference to MyCmpA, which was invalidated. '/mod.js', // MyCmpA is written because it was invalidated. '/cmp-a.js', // MyCmpB should not be written because it is unaffected. ]); }); it('should recompile components once an external declaration is changed', () => { // Testing setup: Two components (MyCmpA and MyCmpB) both depend on an external directive // which matches their templates, via an NgModule import. // // During the test, the external directive is invalidated, and the test verifies that both // components are re-emitted as a result. env.write( 'node_modules/external/index.d.ts', ` import * as ng from '@angular/core'; export declare class ExternalDir { static ɵdir: ng.ɵɵDirectiveDefWithMeta<ExternalDir, "[external]", never, {}, {}, never>; } export declare class ExternalMod { static ɵmod: ng.ɵɵNgModuleDefWithMeta<ExternalMod, [typeof ExternalDir], never, [typeof ExternalDir]>; } `, ); env.write( 'cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div external></div>', standalone: false, }) export class MyCmpA {} `, ); env.write( 'cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div external></div>', standalone: false, }) export class MyCmpB {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {ExternalMod} from 'external'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; @NgModule({ declarations: [MyCmpA, MyCmpB], imports: [ExternalMod], }) export class MyMod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); // Invalidate the external file. Only the referential identity of external symbols matters // for emit reuse, so invalidating this should cause all dependent components to be // re-emitted. env.invalidateCachedFile('node_modules/external/index.d.ts'); env.driveMain(); expectToHaveWritten([ // MyMod is written because it has a direct reference to ExternalMod, which was // invalidated. '/mod.js', // MyCmpA is written because it uses ExternalDir, which has not changed public API but has // changed identity. '/cmp-a.js', // MyCmpB is written because it uses ExternalDir, which has not changed public API but has // changed identity. '/cmp-b.js', ]); }); }); descri
{ "end_byte": 35909, "start_byte": 30678, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_35915_44696
mbol identity', () => { it('should recompile components when their declaration name changes', () => { // Testing setup: component Cmp depends on component Dep, which is directly exported. // // During the test, Dep's name is changed while keeping its public API the same. The test // verifies that Cmp is re-emitted. env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<dep></dep>', standalone: false, }) export class Cmp {} `, ); env.write( 'dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', standalone: false, }) export class Dep {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep] }) export class Mod {} `, ); env.driveMain(); env.write( 'dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', standalone: false, }) export class ChangedDep {} // Dep renamed to ChangedDep. `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {ChangedDep} from './dep'; @NgModule({ declarations: [Cmp, ChangedDep] }) export class Mod {} `, ); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep and Mod were directly updated. '/dep.js', '/mod.js', // Cmp required a re-emit because the name of Dep changed. '/cmp.js', ]); }); it('should not recompile components that use a local directive', () => { // Testing setup: a single source file 'cmp.ts' declares components `Cmp` and `Dir`, where // `Cmp` uses `Dir` in its template. This test verifies that the local reference of `Cmp` // that is emitted into `Dir` does not inadvertently cause `cmp.ts` to be emitted even when // nothing changed. env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', standalone: false, }) export class Dep {} @Component({ selector: 'cmp', template: '<dep></dep>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp, Dep} from './cmp'; @NgModule({ declarations: [Cmp, Dep] }) export class Mod {} `, ); env.driveMain(); env.invalidateCachedFile('mod.ts'); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Only `mod.js` should be written because it was invalidated. '/mod.js', ]); }); it('should recompile components when the name by which they are exported changes', () => { // Testing setup: component Cmp depends on component Dep, which is directly exported. // // During the test, Dep's exported name is changed while keeping its declaration name the // same. The test verifies that Cmp is re-emitted. env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<dep></dep>', standalone: false, }) export class Cmp {} `, ); env.write( 'dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', standalone: false, }) export class Dep {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep] }) export class Mod {} `, ); env.driveMain(); env.write( 'dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', standalone: false, }) class Dep {} export {Dep as ChangedDep}; // the export name of Dep is changed. `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {ChangedDep} from './dep'; @NgModule({ declarations: [Cmp, ChangedDep] }) export class Mod {} `, ); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep and Mod were directly updated. '/dep.js', '/mod.js', // Cmp required a re-emit because the exported name of Dep changed. '/cmp.js', ]); }); it('should recompile components when a re-export is renamed', () => { // Testing setup: CmpUser uses CmpDep in its template. CmpDep is both directly and // indirectly exported, and the compiler is guided into using the indirect export. // // During the test, the indirect export name is changed, and the test verifies that CmpUser // is re-emitted. env.write( 'cmp-user.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-user', template: '<cmp-dep></cmp-dep>', standalone: false, }) export class CmpUser {} `, ); env.write( 'cmp-dep.ts', ` import {Component} from '@angular/core'; export {CmpDep as CmpDepExport}; @Component({ selector: 'cmp-dep', template: 'Dep', standalone: false, }) class CmpDep {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {CmpDepExport} from './cmp-dep'; @NgModule({ declarations: [CmpUser, CmpDepExport] }) export class Module {} `, ); env.driveMain(); // Verify that the reference emitter used the export of `CmpDep` that appeared first in // the source, i.e. `CmpDepExport`. const userCmpJs = env.getContents('cmp-user.js'); expect(userCmpJs).toContain('CmpDepExport'); env.write( 'cmp-dep.ts', ` import {Component} from '@angular/core'; export {CmpDep as CmpDepExport2}; @Component({ selector: 'cmp-dep', template: 'Dep', standalone: false, }) class CmpDep {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {CmpDepExport2} from './cmp-dep'; @NgModule({ declarations: [CmpUser, CmpDepExport2] }) export class Module {} `, ); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // CmpDep and its module were directly updated. '/cmp-dep.js', '/module.js', // CmpUser required a re-emit because it was previous emitted as `CmpDepExport`, but // that export has since been renamed. '/cmp-user.js', ]); // Verify that `CmpUser` now correctly imports `CmpDep` using its renamed // re-export `CmpDepExport2`. const userCmp2Js = env.getContents('cmp-user.js'); expect(userCmp2Js).toContain('CmpDepExport2'); }); it('
{ "end_byte": 44696, "start_byte": 35915, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_44704_51160
ot recompile components when a directive is changed into a component', () => { env.write( 'cmp-user.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-user', template: '<div dep></div>', standalone: false, }) export class CmpUser {} `, ); env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {Dep} from './dep'; @NgModule({ declarations: [CmpUser, Dep] }) export class Module {} `, ); env.driveMain(); env.write( 'dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: '[dep]', template: 'Dep', standalone: false, }) export class Dep {} `, ); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep was directly changed. '/dep.js', // Module required a re-emit because its direct dependency (Dep) was changed. '/module.js', // CmpUser did not require a re-emit because its semantic dependencies were not affected. // Dep is still matched and still has the same public API. ]); }); it('should recompile components when a directive and pipe are swapped', () => { // CmpUser uses a directive DepA and a pipe DepB, with the same selector/name 'dep'. // // During the test, the decorators of DepA and DepB are swapped, effectively changing the // SemanticSymbol types for them into different species while ensuring that CmpUser's // template is still valid. The test then verifies that CmpUser is re-emitted. env.write( 'cmp-user.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-user', template: '<dep>{{1 | dep}}</dep>', standalone: false, }) export class CmpUser {} `, ); env.write( 'dep.ts', ` import {Directive, Pipe} from '@angular/core'; @Directive({ selector: 'dep', standalone: false, }) export class DepA {} @Pipe({ name: 'dep', standalone: false, }) export class DepB { transform() {} } `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {DepA, DepB} from './dep'; @NgModule({ declarations: [CmpUser, DepA, DepB], }) export class Module {} `, ); env.driveMain(); // The annotations on DepA and DepB are swapped. This ensures that when we're comparing the // public API of these symbols to the prior program, the prior symbols are of a different // type (pipe vs directive) than the new symbols, which should lead to a re-emit. env.write( 'dep.ts', ` import {Directive, Pipe} from '@angular/core'; @Pipe({ name: 'dep', standalone: false, }) export class DepA { transform() {} } @Directive({ selector: 'dep', standalone: false, }) export class DepB {} `, ); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep was directly changed. '/dep.js', // Module required a re-emit because its direct dependency (Dep) was changed. '/module.js', // CmpUser required a re-emit because the shape of its matched symbols changed. '/cmp-user.js', ]); }); it('should not recompile components when a component is changed into a directive', () => { // Testing setup: CmpUser depends on a component Dep with an attribute selector. // // During the test, Dep is changed into a directive, and the test verifies that CmpUser is // not re-emitted (as the public API of a directive and a component are the same). env.write( 'cmp-user.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-user', template: '<div dep></div>', standalone: false, }) export class CmpUser {} `, ); env.write( 'dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: '[dep]', template: 'Dep', standalone: false, }) export class Dep {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {Dep} from './dep'; @NgModule({ declarations: [CmpUser, Dep] }) export class Module {} `, ); env.driveMain(); env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', standalone: false, }) export class Dep {} `, ); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep was directly changed. '/dep.js', // Module required a re-emit because its direct dependency (Dep) was changed. '/module.js', // CmpUser did not require a re-emit because its semantic dependencies were not affected. // Dep is still matched and still has the same public API. ]); }); }); descri
{ "end_byte": 51160, "start_byte": 44704, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_51166_58374
mote scoping', () => { it('should not recompile an NgModule nor component when remote scoping is unaffected', () => { // Testing setup: MyCmpA and MyCmpB are two components with an indirect import cycle. That // is, each component consumes the other in its template. This forces the compiler to use // remote scoping to set the directiveDefs of at least one of the components in their // NgModule. // // During the test, an unrelated change is made to the template of MyCmpB, and the test // verifies that the NgModule for the components is not re-emitted. env.write('cmp-a-template.html', `<cmp-b><cmp-b>`); env.write( 'cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-a', templateUrl: './cmp-a-template.html', standalone: false, }) export class MyCmpA {} `, ); env.write('cmp-b-template.html', `<cmp-a><cmp-a>`); env.write( 'cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-b', templateUrl: './cmp-b-template.html', standalone: false, }) export class MyCmpB {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; @NgModule({ declarations: [MyCmpA, MyCmpB], }) export class MyMod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write('cmp-b-template.html', `<cmp-a>Update</cmp-a>`); env.driveMain(); expectToHaveWritten([ // MyCmpB is written because its template was updated. '/cmp-b.js', // MyCmpA should not be written because MyCmpB's public API didn't change. // MyMod should not be written because remote scoping didn't change. ]); }); it('should recompile an NgModule and component when an import cycle is introduced', () => { // Testing setup: MyCmpA and MyCmpB are two components where MyCmpB consumes MyCmpA in its // template. // // During the test, MyCmpA's template is updated to consume MyCmpB, creating an effective // import cycle and forcing the compiler to use remote scoping for at least one of the // components. The test verifies that the components' NgModule is emitted as a result. env.write('cmp-a-template.html', ``); env.write( 'cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-a', templateUrl: './cmp-a-template.html', standalone: false, }) export class MyCmpA {} `, ); env.write('cmp-b-template.html', `<cmp-a><cmp-a>`); env.write( 'cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-b', templateUrl: './cmp-b-template.html', standalone: false, }) export class MyCmpB {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; @NgModule({ declarations: [MyCmpA, MyCmpB], }) export class MyMod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write('cmp-a-template.html', `<cmp-b><cmp-b>`); env.driveMain(); expectToHaveWritten([ // MyMod is written because its remote scopes have changed. '/mod.js', // MyCmpA is written because its template was updated. '/cmp-a.js', // MyCmpB is written because it now requires remote scoping, where previously it did not. '/cmp-b.js', ]); // Validate the correctness of the assumptions made above: // * CmpA should not be using remote scoping. // * CmpB should be using remote scoping. const moduleJs = env.getContents('mod.js'); expect(moduleJs).not.toContain('setComponentScope(MyCmpA,'); expect(moduleJs).toContain('setComponentScope(MyCmpB,'); }); it('should recompile an NgModule and component when an import cycle is removed', () => { // Testing setup: MyCmpA and MyCmpB are two components that each consume the other in their // template, forcing the compiler to utilize remote scoping for at least one of them. // // During the test, MyCmpA's template is updated to no longer consume MyCmpB, breaking the // effective import cycle and causing remote scoping to no longer be required. The test // verifies that the components' NgModule is emitted as a result. env.write('cmp-a-template.html', `<cmp-b><cmp-b>`); env.write( 'cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-a', templateUrl: './cmp-a-template.html', standalone: false, }) export class MyCmpA {} `, ); env.write('cmp-b-template.html', `<cmp-a><cmp-a>`); env.write( 'cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-b', templateUrl: './cmp-b-template.html', standalone: false, }) export class MyCmpB {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; @NgModule({ declarations: [MyCmpA, MyCmpB], }) export class MyMod {} `, ); env.driveMain(); // Validate the correctness of the assumption that CmpB will be the remotely scoped // component due to the above cycle: const moduleJs = env.getContents('mod.js'); expect(moduleJs).not.toContain('setComponentScope(MyCmpA,'); expect(moduleJs).toContain('setComponentScope(MyCmpB,'); env.flushWrittenFileTracking(); env.write('cmp-a-template.html', ``); env.driveMain(); expectToHaveWritten([ // MyMod is written because its remote scopes have changed. '/mod.js', // MyCmpA is written because its template was updated. '/cmp-a.js', // MyCmpB is written because it no longer needs remote scoping. '/cmp-b.js', ]); }); it("
{ "end_byte": 58374, "start_byte": 51166, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_58382_64908
ecompile an NgModule when a remotely scoped component's scope is changed", () => { // Testing setup: MyCmpA and MyCmpB are two components that each consume the other in // their template, forcing the compiler to utilize remote scoping for MyCmpB (which is // verified). Dir is a directive which is initially unused by either component. // // During the test, MyCmpB is updated to additionally consume Dir in its template. This // changes the remote scope of MyCmpB, requiring a re-emit of its NgModule which the test // verifies. env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir {} `, ); env.write('cmp-a-template.html', `<cmp-b><cmp-b>`); env.write( 'cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-a', templateUrl: './cmp-a-template.html', standalone: false, }) export class MyCmpA {} `, ); env.write('cmp-b-template.html', `<cmp-a><cmp-a>`); env.write( 'cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-b', templateUrl: './cmp-b-template.html', standalone: false, }) export class MyCmpB {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; import {Dir} from './dir'; @NgModule({ declarations: [MyCmpA, MyCmpB, Dir], }) export class MyMod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); // Validate the correctness of the assumption that MyCmpB will be remotely scoped: const moduleJs = env.getContents('mod.js'); expect(moduleJs).not.toContain('setComponentScope(MyCmpA,'); expect(moduleJs).toContain('setComponentScope(MyCmpB,'); env.write('cmp-b-template.html', `<cmp-a dir>Update</cmp-a>`); env.driveMain(); expectToHaveWritten([ // MyCmpB is written because its template was updated. '/cmp-b.js', // MyMod should be written because one of its remotely scoped components has a changed // scope. '/mod.js', // MyCmpA should not be written because none of its dependencies have changed in their // public API. ]); }); it('should recompile an NgModule when its set of remotely scoped components changes', () => { // Testing setup: three components (MyCmpA, MyCmpB, and MyCmpC) are declared. MyCmpA // consumes the other two in its template, and MyCmpB consumes MyCmpA creating an effective // import cycle that forces the compiler to use remote scoping for MyCmpB (which is // verified). // // During the test, MyCmpC's template is changed to depend on MyCmpA, forcing remote // scoping for it as well. The test verifies that the NgModule is re-emitted as a new // component within it now requires remote scoping. env.write('cmp-a-template.html', `<cmp-b><cmp-b> <cmp-c></cmp-c>`); env.write( 'cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-a', templateUrl: './cmp-a-template.html', standalone: false, }) export class MyCmpA {} `, ); env.write('cmp-b-template.html', `<cmp-a><cmp-a>`); env.write( 'cmp-b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-b', templateUrl: './cmp-b-template.html', standalone: false, }) export class MyCmpB {} `, ); env.write('cmp-c-template.html', ``); env.write( 'cmp-c.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-c', templateUrl: './cmp-c-template.html', standalone: false, }) export class MyCmpC {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {MyCmpA} from './cmp-a'; import {MyCmpB} from './cmp-b'; import {MyCmpC} from './cmp-c'; @NgModule({ declarations: [MyCmpA, MyCmpB, MyCmpC], }) export class MyMod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); // Validate the correctness of the assumption that MyCmpB will be the only remotely // scoped component due to the MyCmpA <-> MyCmpB cycle: const moduleJsBefore = env.getContents('mod.js'); expect(moduleJsBefore).not.toContain('setComponentScope(MyCmpA,'); expect(moduleJsBefore).toContain('setComponentScope(MyCmpB,'); expect(moduleJsBefore).not.toContain('setComponentScope(MyCmpC,'); env.write('cmp-c-template.html', `<cmp-a>Update</cmp-a>`); env.driveMain(); // Validate the correctness of the assumption that MyCmpB and MyCmpC are now both // remotely scoped due to the MyCmpA <-> MyCmpB and MyCmpA <-> MyCmpC cycles: const moduleJsAfter = env.getContents('mod.js'); expect(moduleJsAfter).not.toContain('setComponentScope(MyCmpA,'); expect(moduleJsAfter).toContain('setComponentScope(MyCmpB,'); expect(moduleJsAfter).toContain('setComponentScope(MyCmpC,'); expectToHaveWritten([ // MyCmpC is written because its template was updated. '/cmp-c.js', // MyMod should be written because MyCmpC became remotely scoped '/mod.js', // MyCmpA and MyCmpB should not be written because none of their dependencies have // changed in their public API. ]); }); }); descri
{ "end_byte": 64908, "start_byte": 58382, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_64914_73574
Module declarations', () => { it('should recompile components when a matching directive is added in the direct scope', () => { // Testing setup: A component Cmp has a template which would match a directive Dir, // except Dir is not included in Cmp's NgModule. // // During the test, Dir is added to the NgModule, causing it to begin matching in Cmp's // template. The test verifies that Cmp is re-emitted to account for this. env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir {} `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; @NgModule({ declarations: [Cmp], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); expectToHaveWritten([ // Mod is written as it was directly changed. '/mod.js', // Cmp is written as a matching directive was added to Mod's scope. '/cmp.js', ]); }); it('should recompile components when a matching directive is removed from the direct scope', () => { // Testing setup: Cmp is a component with a template that matches a directive Dir. // // During the test, Dir is removed from Cmp's NgModule, which causes it to stop matching // in Cmp's template. The test verifies that Cmp is re-emitted as a result. env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir {} `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; @NgModule({ declarations: [Cmp], }) export class Mod {} `, ); env.driveMain(); expectToHaveWritten([ // Mod is written as it was directly changed. '/mod.js', // Cmp is written as a matching directive was removed from Mod's scope. '/cmp.js', ]); }); it('should recompile components when a matching directive is added in the transitive scope', () => { // Testing setup: A component Cmp has a template which would match a directive Dir, // except Dir is not included in Cmp's NgModule. // // During the test, Dir is added to the NgModule via an import, causing it to begin // matching in Cmp's template. The test verifies that Cmp is re-emitted to account for // this. env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir {} `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'deep.ts', ` import {NgModule} from '@angular/core'; @NgModule({ declarations: [], exports: [], }) export class Deep {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Deep} from './deep'; @NgModule({ declarations: [Cmp], imports: [Deep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'deep.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; @NgModule({ declarations: [Dir], exports: [Dir], }) export class Deep {} `, ); env.driveMain(); expectToHaveWritten([ // Mod is written as it was directly changed. '/deep.js', // Mod is written as its direct dependency (Deep) was changed. '/mod.js', // Cmp is written as a matching directive was added to Mod's transitive scope. '/cmp.js', ]); }); it('should recompile components when a matching directive is removed from the transitive scope', () => { // Testing setup: Cmp is a component with a template that matches a directive Dir, due to // Dir's NgModule being imported into Cmp's NgModule. // // During the test, this import link is removed, which causes Dir to stop matching in // Cmp's template. The test verifies that Cmp is re-emitted as a result. env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir {} `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'deep.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; @NgModule({ declarations: [Dir], exports: [Dir], }) export class Deep {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Deep} from './deep'; @NgModule({ declarations: [Cmp], imports: [Deep], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'deep.ts', ` import {NgModule} from '@angular/core'; @NgModule({ declarations: [], exports: [], }) export class Deep {} `, ); env.driveMain(); expectToHaveWritten([ // Mod is written as it was directly changed. '/deep.js', // Mod is written as its direct dependency (Deep) was changed. '/mod.js', // Cmp is written as a matching directive was removed from Mod's transitive scope. '/cmp.js', ]); }); it('
{ "end_byte": 73574, "start_byte": 64914, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts_73582_80846
ot recompile components when a non-matching directive is added in scope', () => { // Testing setup: A component Cmp has a template which does not match a directive Dir, // and Dir is not included in Cmp's NgModule. // // During the test, Dir is added to the NgModule, making it visible in Cmp's template. // However, Dir still does not match the template. The test verifies that Cmp is not // re-emitted. env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir {} `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; @NgModule({ declarations: [Cmp], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); expectToHaveWritten([ // Mod is written as it was directly changed. '/mod.js', // Cmp is not written as its used directives remains the same, since Dir does not match // within its template. ]); }); }); describe('error recovery', () => { it('should recompile a component when a matching directive is added that first contains an error', () => { // Testing setup: Cmp is a component which would match a directive with the selector // '[dir]'. // // During the test, an initial incremental compilation adds an import to a hypothetical // directive Dir to the NgModule, and adds Dir as a declaration. However, the import // points to a non-existent file. // // During a second incremental compilation, that missing file is added with a declaration // for Dir as a directive with the selector '[dir]', causing it to begin matching in // Cmp's template. The test verifies that Cmp is re-emitted once the program is correct. env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; @NgModule({ declarations: [Cmp], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); expect(env.driveDiagnostics().length).not.toBe(0); env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir {} `, ); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Mod is written as it was changed in the first incremental compilation, but had // errors and so was not written then. '/mod.js', // Dir is written as it was added in the second incremental compilation. '/dir.js', // Cmp is written as the cumulative effect of the two changes was to add Dir to its // scope and thus match in Cmp's template. '/cmp.js', ]); }); }); it('should correctly emit components when public API changes during a broken program', () => { // Testing setup: a component Cmp exists with a template that matches directive Dir. Cmp also // references an extra file with a constant declaration. // // During the test, a first incremental compilation both adds an input to Dir (changing its // public API) as well as introducing a compilation error by adding invalid syntax to the // extra file. // // A second incremental compilation then fixes the invalid syntax, and the test verifies that // Cmp is re-emitted due to the earlier public API change to Dir. env.write( 'other.ts', ` export const FOO = true; `, ); env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dirIn!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; import './other'; @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); env.flushWrittenFileTracking(); env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dirIn_changed!: string; } `, ); env.write( 'other.ts', ` export const FOO = ; `, ); expect(env.driveDiagnostics().length).not.toBe(0); env.flushWrittenFileTracking(); env.write( 'other.ts', ` export const FOO = false; `, ); env.driveMain(); expectToHaveWritten([ // Mod is written as its direct dependency (Dir) was changed. '/mod.js', // Dir is written as it was directly changed. '/dir.js', // other.js is written as it was directly changed. '/other.js', // Cmp is written as Dir's public API has changed. '/cmp.js', ]); }); }); });
{ "end_byte": 80846, "start_byte": 73582, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_semantic_changes_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/defer_spec.ts_0_3256
/** * @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 {ErrorCode, ngErrorCode} from '@angular/compiler-cli/src/ngtsc/diagnostics'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('ngtsc @defer block', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig(); }); it('should handle deferred blocks', () => { env.write( 'cmp-a.ts', ` import { Component } from '@angular/core'; @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { CmpA } from './cmp-a'; @Component({ selector: 'local-dep', standalone: true, template: 'Local dependency', }) export class LocalDep {} @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA, LocalDep], template: \` @defer { <cmp-a /> <local-dep /> } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain('() => [import("./cmp-a").then(m => m.CmpA), LocalDep]'); // The `CmpA` symbol wasn't referenced elsewhere, so it can be defer-loaded // via dynamic imports and an original import can be removed. expect(jsContents).not.toContain('import { CmpA }'); }); it('should include timer scheduler function when `after` or `minimum` parameters are used', () => { env.write( 'cmp-a.ts', ` import { Component } from '@angular/core'; @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { CmpA } from './cmp-a'; @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA], template: \` @defer { <cmp-a /> } @loading (after 500ms; minimum 300ms) { Loading... } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'ɵɵdefer(2, 0, TestCmp_Defer_2_DepsFn, 1, null, null, 0, null, i0.ɵɵdeferEnableTimerScheduling)', ); });
{ "end_byte": 3256, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/defer_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/defer_spec.ts_3262_12055
be('imports', () => { it('should retain regular imports when symbol is eagerly referenced', () => { env.write( 'cmp-a.ts', ` import { Component } from '@angular/core'; @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { CmpA } from './cmp-a'; @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA], template: \` @defer { <cmp-a /> } \`, }) export class TestCmp { constructor() { // This line retains the regular import of CmpA, // since it's eagerly referenced in the code. console.log(CmpA); } } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); // The dependency function doesn't have a dynamic import, because `CmpA` // was eagerly referenced in component's code, thus regular import can not be removed. expect(jsContents).toContain('() => [CmpA]'); expect(jsContents).toContain('import { CmpA }'); }); it('should retain regular imports when one of the symbols is eagerly referenced', () => { env.write( 'cmp-a.ts', ` import { Component } from '@angular/core'; @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} @Component({ standalone: true, selector: 'cmp-b', template: 'CmpB!' }) export class CmpB {} `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { CmpA, CmpB } from './cmp-a'; @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA, CmpB], template: \` @defer { <cmp-a /> <cmp-b /> } \`, }) export class TestCmp { constructor() { // This line retains the regular import of CmpA, // since it's eagerly referenced in the code. console.log(CmpA); } } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); // The dependency function doesn't have a dynamic import, because `CmpA` // was eagerly referenced in component's code, thus regular import can not be removed. // This also affects `CmpB`, since it was extracted from the same import. expect(jsContents).toContain('() => [CmpA, CmpB]'); expect(jsContents).toContain('import { CmpA, CmpB }'); }); it('should drop regular imports when none of the symbols are eagerly referenced', () => { env.write( 'cmp-a.ts', ` import { Component } from '@angular/core'; @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} @Component({ standalone: true, selector: 'cmp-b', template: 'CmpB!' }) export class CmpB {} `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { CmpA, CmpB } from './cmp-a'; @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA, CmpB], template: \` @defer { <cmp-a /> <cmp-b /> } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); // Both `CmpA` and `CmpB` were used inside the defer block and were not // referenced elsewhere, so we generate dynamic imports and drop a regular one. expect(jsContents).toContain( '() => [' + 'import("./cmp-a").then(m => m.CmpA), ' + 'import("./cmp-a").then(m => m.CmpB)]', ); expect(jsContents).not.toContain('import { CmpA, CmpB }'); }); it('should lazy-load dependency referenced with a fowrardRef', () => { env.write( 'cmp-a.ts', ` import { Component } from '@angular/core'; @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} `, ); env.write( '/test.ts', ` import { Component, forwardRef } from '@angular/core'; import { CmpA } from './cmp-a'; @Component({ selector: 'test-cmp', standalone: true, imports: [forwardRef(() => CmpA)], template: \` @defer { <cmp-a /> } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain('() => [import("./cmp-a").then(m => m.CmpA)]'); // The `CmpA` symbol wasn't referenced elsewhere, so it can be defer-loaded // via dynamic imports and an original import can be removed. expect(jsContents).not.toContain('import { CmpA }'); }); it('should drop imports when one is deferrable and the rest are type-only imports', () => { env.write( 'cmp-a.ts', ` import { Component } from '@angular/core'; export class Foo {} @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { CmpA, type Foo } from './cmp-a'; export const foo: Foo = {}; @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA], template: \` @defer { <cmp-a /> } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain('() => [import("./cmp-a").then(m => m.CmpA)]'); expect(jsContents).not.toContain('import { CmpA }'); }); it('should drop multiple imports to the same file when one is deferrable and the other has a single type-only element', () => { env.write( 'cmp-a.ts', ` import { Component } from '@angular/core'; export class Foo {} @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { CmpA } from './cmp-a'; import { type Foo } from './cmp-a'; export const foo: Foo = {}; @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA], template: \` @defer { <cmp-a /> } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain('() => [import("./cmp-a").then(m => m.CmpA)]'); expect(jsContents).not.toContain('import { CmpA }'); }); it('should
{ "end_byte": 12055, "start_byte": 3262, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/defer_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/defer_spec.ts_12063_20788
ltiple imports to the same file when one is deferrable and the other is type-only at the declaration level', () => { env.write( 'cmp-a.ts', ` import { Component } from '@angular/core'; export class Foo {} @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { CmpA } from './cmp-a'; import type { Foo, CmpA as CmpAlias } from './cmp-a'; export const foo: Foo|CmpAlias = {}; @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA], template: \` @defer { <cmp-a /> } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain('() => [import("./cmp-a").then(m => m.CmpA)]'); expect(jsContents).not.toContain('import { CmpA }'); }); it('should drop multiple imports to the same file when one is deferrable and the other is a type-only import of all symbols', () => { env.write( 'cmp-a.ts', ` import { Component } from '@angular/core'; export class Foo {} @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { CmpA } from './cmp-a'; import type * as allCmpA from './cmp-a'; export const foo: allCmpA.Foo|allCmpA.CmpA = {}; @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA], template: \` @defer { <cmp-a /> } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain('() => [import("./cmp-a").then(m => m.CmpA)]'); expect(jsContents).not.toContain('import { CmpA }'); }); it('should drop multiple imports of deferrable symbols from the same file', () => { env.write( 'cmps.ts', ` import { Component } from '@angular/core'; @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} @Component({ standalone: true, selector: 'cmp-b', template: 'CmpB!' }) export class CmpB {} `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { CmpA } from './cmps'; import { CmpB } from './cmps'; @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA, CmpB], template: \` @defer { <cmp-a /> <cmp-b /> } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain( '() => [import("./cmps").then(m => m.CmpA), import("./cmps").then(m => m.CmpB)]', ); expect(jsContents).not.toContain('import { CmpA }'); expect(jsContents).not.toContain('import { CmpB }'); }); it('should handle deferred dependencies imported through a default import', () => { env.write( 'cmp-a.ts', ` import { Component } from '@angular/core'; @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export default class CmpA {} `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import CmpA from './cmp-a'; @Component({ selector: 'local-dep', standalone: true, template: 'Local dependency', }) export class LocalDep {} @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA, LocalDep], template: \` @defer { <cmp-a /> <local-dep /> } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain( 'const TestCmp_Defer_1_DepsFn = () => [import("./cmp-a").then(m => m.default), LocalDep];', ); expect(jsContents).toContain( 'i0.ɵsetClassMetadataAsync(TestCmp, () => [import("./cmp-a").then(m => m.default)]', ); // The `CmpA` symbol wasn't referenced elsewhere, so it can be defer-loaded // via dynamic imports and an original import can be removed. expect(jsContents).not.toContain('import CmpA'); }); it('should defer symbol that is used only in types', () => { env.write( 'cmp.ts', ` import { Component } from '@angular/core'; @Component({ standalone: true, selector: 'cmp', template: 'Cmp!' }) export class Cmp {} `, ); env.write( '/test.ts', ` import { Component, viewChild } from '@angular/core'; import { Cmp } from './cmp'; const topLevelConst: Cmp = null!; @Component({ standalone: true, imports: [Cmp], template: \` @defer { <cmp #ref/> } \`, }) export class TestCmp { query = viewChild<Cmp>('ref'); asType: Cmp; inlineType: {foo: Cmp}; unionType: string | Cmp | number; constructor(param: Cmp) {} inMethod(param: Cmp): Cmp { let localVar: Cmp | null = null; return localVar!; } } function inFunction(param: Cmp): Cmp { return null!; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain('() => [import("./cmp").then(m => m.Cmp)]'); expect(jsContents).not.toContain('import { Cmp }'); }); it('should retain symbols used in types and eagerly', () => { env.write( 'cmp.ts', ` import { Component } from '@angular/core'; @Component({ standalone: true, selector: 'cmp', template: 'Cmp!' }) export class Cmp {} `, ); env.write( '/test.ts', ` import { Component, viewChild } from '@angular/core'; import { Cmp } from './cmp'; @Component({ standalone: true, imports: [Cmp], template: \` @defer { <cmp #ref/> } \`, }) export class TestCmp { // Type-only reference query = viewChild<Cmp>('ref'); // Directy reference otherQuery = viewChild(Cmp); } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain('() => [Cmp]'); expect(jsContents).toContain('import { Cmp }'); }); }); it('should detect pipe us
{ "end_byte": 20788, "start_byte": 12063, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/defer_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/defer_spec.ts_20794_23478
the `when` trigger as an eager dependency', () => { env.write( 'test-pipe.ts', ` import { Pipe } from '@angular/core'; @Pipe({name: 'test', standalone: true}) export class TestPipe { transform() { return 1; } } `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { TestPipe } from './test-pipe'; @Component({ selector: 'test-cmp', standalone: true, imports: [TestPipe], template: '@defer (when 1 | test) { hello }', }) export class TestCmp { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('dependencies: [TestPipe]'); }); it('should detect pipe used in the `prefetch when` trigger as an eager dependency', () => { env.write( 'test-pipe.ts', ` import { Pipe } from '@angular/core'; @Pipe({name: 'test', standalone: true}) export class TestPipe { transform() { return 1; } } `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { TestPipe } from './test-pipe'; @Component({ selector: 'test-cmp', standalone: true, imports: [TestPipe], template: '@defer (when 1 | test) { hello }', }) export class TestCmp { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('dependencies: [TestPipe]'); }); it('should detect pipe used both in a trigger and the deferred content as eager', () => { env.write( 'test-pipe.ts', ` import { Pipe } from '@angular/core'; @Pipe({name: 'test', standalone: true}) export class TestPipe { transform() { return 1; } } `, ); env.write( '/test.ts', ` import { Component } from '@angular/core'; import { TestPipe } from './test-pipe'; @Component({ selector: 'test-cmp', standalone: true, imports: [TestPipe], template: '@defer (when 1 | test) { {{1 | test}} }', }) export class TestCmp { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('dependencies: [TestPipe]'); }); describe('@Component.defe
{ "end_byte": 23478, "start_byte": 20794, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/defer_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/defer_spec.ts_23484_29776
ports', () => { beforeEach(() => { env.tsconfig({onlyExplicitDeferDependencyImports: true}); }); it('should handle `@Component.deferredImports` field', () => { env.write( 'deferred-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-a', template: 'DeferredCmpA contents', }) export class DeferredCmpA { } `, ); env.write( 'deferred-b.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-b', template: 'DeferredCmpB contents', }) export class DeferredCmpB { } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {DeferredCmpA} from './deferred-a'; import {DeferredCmpB} from './deferred-b'; @Component({ standalone: true, // @ts-ignore deferredImports: [DeferredCmpA, DeferredCmpB], template: \` @defer { <deferred-cmp-a /> } @defer { <deferred-cmp-b /> } \`, }) export class AppCmp { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Expect that all deferrableImports become dynamic imports. expect(jsContents).toContain( 'const AppCmp_Defer_1_DepsFn = () => [' + 'import("./deferred-a").then(m => m.DeferredCmpA)];', ); expect(jsContents).toContain( 'const AppCmp_Defer_4_DepsFn = () => [' + 'import("./deferred-b").then(m => m.DeferredCmpB)];', ); // Make sure there are no eager imports present in the output. expect(jsContents).not.toContain(`from './deferred-a'`); expect(jsContents).not.toContain(`from './deferred-b'`); // Defer instructions have different dependency functions in full mode. expect(jsContents).toContain('ɵɵdefer(1, 0, AppCmp_Defer_1_DepsFn);'); expect(jsContents).toContain('ɵɵdefer(4, 3, AppCmp_Defer_4_DepsFn);'); // Expect `ɵsetClassMetadataAsync` to contain dynamic imports too. expect(jsContents).toContain( 'ɵsetClassMetadataAsync(AppCmp, () => [' + 'import("./deferred-a").then(m => m.DeferredCmpA), ' + 'import("./deferred-b").then(m => m.DeferredCmpB)], ' + '(DeferredCmpA, DeferredCmpB) => {', ); }); it('should handle defer blocks that rely on deps from `deferredImports` and `imports`', () => { env.write( 'eager-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'eager-cmp-a', template: 'EagerCmpA contents', }) export class EagerCmpA { } `, ); env.write( 'deferred-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-a', template: 'DeferredCmpA contents', }) export class DeferredCmpA { } `, ); env.write( 'deferred-b.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-b', template: 'DeferredCmpB contents', }) export class DeferredCmpB { } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {DeferredCmpA} from './deferred-a'; import {DeferredCmpB} from './deferred-b'; import {EagerCmpA} from './eager-a'; @Component({ standalone: true, imports: [EagerCmpA], // @ts-ignore deferredImports: [DeferredCmpA, DeferredCmpB], template: \` @defer { <eager-cmp-a /> <deferred-cmp-a /> } @defer { <eager-cmp-a /> <deferred-cmp-b /> } \`, }) export class AppCmp { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Expect that all deferrableImports to become dynamic imports. // Other imported symbols remain eager. expect(jsContents).toContain( 'const AppCmp_Defer_1_DepsFn = () => [' + 'import("./deferred-a").then(m => m.DeferredCmpA), ' + 'EagerCmpA];', ); expect(jsContents).toContain( 'const AppCmp_Defer_4_DepsFn = () => [' + 'import("./deferred-b").then(m => m.DeferredCmpB), ' + 'EagerCmpA];', ); // Make sure there are no eager imports present in the output. expect(jsContents).not.toContain(`from './deferred-a'`); expect(jsContents).not.toContain(`from './deferred-b'`); // Eager dependencies retain their imports. expect(jsContents).toContain(`from './eager-a';`); // Defer blocks would have their own dependency functions in full mode. expect(jsContents).toContain('ɵɵdefer(1, 0, AppCmp_Defer_1_DepsFn);'); expect(jsContents).toContain('ɵɵdefer(4, 3, AppCmp_Defer_4_DepsFn);'); // Expect `ɵsetClassMetadataAsync` to contain dynamic imports too. expect(jsContents).toContain( 'ɵsetClassMetadataAsync(AppCmp, () => [' + 'import("./deferred-a").then(m => m.DeferredCmpA), ' + 'import("./deferred-b").then(m => m.DeferredCmpB)], ' + '(DeferredCmpA, DeferredCmpB) => {', ); }); describe('error handling', () => {
{ "end_byte": 29776, "start_byte": 23484, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/defer_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/defer_spec.ts_29784_38636
it('should produce an error when unsupported type (@Injectable) is used in `deferredImports`', () => { env.write( 'test.ts', ` import {Component, Injectable} from '@angular/core'; @Injectable() class MyInjectable {} @Component({ standalone: true, // @ts-ignore deferredImports: [MyInjectable], template: '', }) export class AppCmp { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_UNKNOWN_DEFERRED_IMPORT)); }); it('should produce an error when unsupported type (@NgModule) is used in `deferredImports`', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @NgModule() class MyModule {} @Component({ standalone: true, // @ts-ignore deferredImports: [MyModule], template: '', }) export class AppCmp { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_UNKNOWN_DEFERRED_IMPORT)); }); it('should produce an error when components from `deferredImports` are used outside of defer blocks', () => { env.write( 'deferred-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-a', template: 'DeferredCmpA contents', }) export class DeferredCmpA { } `, ); env.write( 'deferred-b.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-b', template: 'DeferredCmpB contents', }) export class DeferredCmpB { } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {DeferredCmpA} from './deferred-a'; import {DeferredCmpB} from './deferred-b'; @Component({ standalone: true, // @ts-ignore deferredImports: [DeferredCmpA, DeferredCmpB], template: \` <deferred-cmp-a /> @defer { <deferred-cmp-b /> } \`, }) export class AppCmp { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.DEFERRED_DIRECTIVE_USED_EAGERLY)); }); it('should produce an error the same component is referenced in both `deferredImports` and `imports`', () => { env.write( 'deferred-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-a', template: 'DeferredCmpA contents', }) export class DeferredCmpA { } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {DeferredCmpA} from './deferred-a'; @Component({ standalone: true, // @ts-ignore deferredImports: [DeferredCmpA], imports: [DeferredCmpA], template: \` @defer { <deferred-cmp-a /> } \`, }) export class AppCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.DEFERRED_DEPENDENCY_IMPORTED_EAGERLY)); }); it('should produce an error when pipes from `deferredImports` are used outside of defer blocks', () => { env.write( 'deferred-pipe-a.ts', ` import {Pipe} from '@angular/core'; @Pipe({ standalone: true, name: 'deferredPipeA' }) export class DeferredPipeA { transform() {} } `, ); env.write( 'deferred-pipe-b.ts', ` import {Pipe} from '@angular/core'; @Pipe({ standalone: true, name: 'deferredPipeB' }) export class DeferredPipeB { transform() {} } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {DeferredPipeA} from './deferred-pipe-a'; import {DeferredPipeB} from './deferred-pipe-b'; @Component({ standalone: true, // @ts-ignore deferredImports: [DeferredPipeA, DeferredPipeB], template: \` {{ 'Eager' | deferredPipeA }} @defer { {{ 'Deferred' | deferredPipeB }} } \`, }) export class AppCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.DEFERRED_PIPE_USED_EAGERLY)); }); it('should not produce an error when a deferred block is wrapped in a conditional', () => { env.write( 'deferred-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-a', template: 'DeferredCmpA contents', }) export class DeferredCmpA { } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {DeferredCmpA} from './deferred-a'; @Component({ standalone: true, // @ts-ignore deferredImports: [DeferredCmpA], template: \` @if (true) { @if (true) { @if (true) { @defer { <deferred-cmp-a /> } } } } \`, }) export class AppCmp { condition = true; } `, ); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); }); it('should not produce an error when a dependency is wrapped in a condition inside of a deferred block', () => { env.write( 'deferred-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-a', template: 'DeferredCmpA contents', }) export class DeferredCmpA { } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {DeferredCmpA} from './deferred-a'; @Component({ standalone: true, // @ts-ignore deferredImports: [DeferredCmpA], template: \` @defer { @if (true) { @if (true) { @if (true) { <deferred-cmp-a /> } } } } \`, }) export class AppCmp { condition = true; } `, ); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); }); }); }); describe('setClassMetadataAsync', ()
{ "end_byte": 38636, "start_byte": 29784, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/defer_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/defer_spec.ts_38642_43710
it('should generate setClassMetadataAsync for components with defer blocks', () => { env.write( 'cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} `, ); env.write( '/test.ts', ` import {Component} from '@angular/core'; import {CmpA} from './cmp-a'; @Component({ selector: 'local-dep', standalone: true, template: 'Local dependency', }) export class LocalDep {} @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA, LocalDep], template: \` @defer { <cmp-a /> <local-dep /> } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain( // ngDevMode check is present '(() => { (typeof ngDevMode === "undefined" || ngDevMode) && ' + // Main `setClassMetadataAsync` call 'i0.ɵsetClassMetadataAsync(TestCmp, ' + // Dependency loading function (note: no local `LocalDep` here) '() => [import("./cmp-a").then(m => m.CmpA)], ' + // Callback that invokes `setClassMetadata` at the end 'CmpA => { i0.ɵsetClassMetadata(TestCmp', ); }); it( 'should *not* generate setClassMetadataAsync for components with defer blocks ' + 'when dependencies are eagerly referenced as well', () => { env.write( 'cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export class CmpA {} `, ); env.write( '/test.ts', ` import {Component} from '@angular/core'; import {CmpA} from './cmp-a'; @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA], template: \` @defer { <cmp-a /> } \`, }) export class TestCmp { constructor() { // This eager reference retains 'CmpA' symbol as eager. console.log(CmpA); } } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Dependency function eagerly references `CmpA`. expect(jsContents).toContain('() => [CmpA]'); // The `setClassMetadataAsync` wasn't generated, since there are no deferrable // symbols. expect(jsContents).not.toContain('setClassMetadataAsync'); // But the regular `setClassMetadata` is present. expect(jsContents).toContain('setClassMetadata'); }, ); }); it('should generate setClassMetadataAsync for default imports', () => { env.write( 'cmp-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'cmp-a', template: 'CmpA!' }) export default class CmpA {} `, ); env.write( '/test.ts', ` import {Component} from '@angular/core'; import CmpA from './cmp-a'; @Component({ selector: 'local-dep', standalone: true, template: 'Local dependency', }) export class LocalDep {} @Component({ selector: 'test-cmp', standalone: true, imports: [CmpA, LocalDep], template: \` @defer { <cmp-a /> <local-dep /> } \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵdefer(1, 0, TestCmp_Defer_1_DepsFn)'); expect(jsContents).toContain( // ngDevMode check is present '(() => { (typeof ngDevMode === "undefined" || ngDevMode) && ' + // Main `setClassMetadataAsync` call 'i0.ɵsetClassMetadataAsync(TestCmp, ' + // Dependency loading function (note: no local `LocalDep` here) '() => [import("./cmp-a").then(m => m.default)], ' + // Callback that invokes `setClassMetadata` at the end 'CmpA => { i0.ɵsetClassMetadata(TestCmp', ); }); }); });
{ "end_byte": 43710, "start_byte": 38642, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/defer_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/standalone_spec.ts_0_581
/** * @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 ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../src/ngtsc/diagnostics'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import { diagnosticToNode, getSourceCodeForDiagnostic, loadStandardTestFiles, } from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles();
{ "end_byte": 581, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/standalone_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/standalone_spec.ts_583_9627
runInEachFileSystem(() => { describe('ngtsc compilation of standalone types', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({strictTemplates: true}); }); describe('component-side', () => { it('should compile a basic standalone component', () => { env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir {} @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [TestDir], }) export class TestCmp {} `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('dependencies: [TestDir]'); expect(jsCode).toContain('standalone: true'); const dtsCode = env.getContents('test.d.ts'); expect(dtsCode).toContain( 'i0.ɵɵDirectiveDeclaration<TestDir, "[dir]", never, {}, {}, never, never, true, never>;', ); expect(dtsCode).toContain( 'i0.ɵɵComponentDeclaration<TestCmp, "test-cmp", never, {}, {}, never, never, true, never>;', ); }); it('should compile a recursive standalone component', () => { env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<test-cmp></test-cmp>', standalone: true, }) export class TestCmp {} `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('dependencies: [TestCmp]'); expect(jsCode).toContain('standalone: true'); }); it('should compile a basic standalone pipe', () => { env.write( 'test.ts', ` import {Pipe} from '@angular/core'; @Pipe({ standalone: true, name: 'test', }) export class TestPipe { transform(value: any): any {} } `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('standalone: true'); const dtsCode = env.getContents('test.d.ts'); expect(dtsCode).toContain('i0.ɵɵPipeDeclaration<TestPipe, "test", true>'); }); it('should use existing imports for dependencies', () => { env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ standalone: true, selector: '[dir]', }) export class TestDir {} `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {TestDir} from './dep'; @Component({ standalone: true, imports: [TestDir], selector: 'test-cmp', template: '<div dir></div>', }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('dependencies: [TestDir]'); }); it('should compile a standalone component even in the presence of cycles', () => { env.write( 'dep.ts', ` import {Directive, Input} from '@angular/core'; // This import creates a cycle, since 'test.ts' imports 'dir.ts'. import {TestType} from './test'; @Directive({ standalone: true, selector: '[dir]', }) export class TestDir { @Input() value?: TestType; } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {TestDir} from './dep'; export interface TestType { value: string; } @Component({ standalone: true, imports: [TestDir], selector: 'test-cmp', template: '<div dir></div>', }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('dependencies: [TestDir]'); }); it('should compile a standalone component in a cycle with its module', () => { env.write( 'module.ts', ` import {Component, NgModule, forwardRef} from '@angular/core'; import {StandaloneCmp} from './component'; @Component({ selector: 'module-cmp', template: '<standalone-cmp></standalone-cmp>', standalone: false, }) export class ModuleCmp {} @NgModule({ declarations: [ModuleCmp], exports: [ModuleCmp], imports: [forwardRef(() => StandaloneCmp)], }) export class Module {} `, ); env.write( 'component.ts', ` import {Component, forwardRef} from '@angular/core'; import {Module} from './module'; @Component({ standalone: true, imports: [forwardRef(() => Module)], selector: 'standalone-cmp', template: '<module-cmp></module-cmp>', }) export class StandaloneCmp {} `, ); env.driveMain(); const moduleJs = env.getContents('module.js'); expect(moduleJs).toContain( 'i0.ɵɵsetComponentScope(ModuleCmp, function () { return [i1.StandaloneCmp]; }, []);', ); const cmpJs = env.getContents('component.js'); expect(cmpJs).toContain('dependencies: () => [Module, i1.ModuleCmp]'); }); it('should error when a non-standalone component tries to use imports', () => { env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir {} @Component({ selector: 'test-cmp', template: '<div dir></div>', imports: [TestDir], standalone: false, }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_NOT_STANDALONE)); expect(getSourceCodeForDiagnostic(diags[0])).toEqual('[TestDir]'); }); it('should compile a standalone component with schema support', () => { env.write( 'test.ts', ` import {Component, NO_ERRORS_SCHEMA} from '@angular/core'; @Component({ selector: 'test-cmp', standalone: true, template: '<is-unknown></is-unknown>', schemas: [NO_ERRORS_SCHEMA], }) export class TestCmp {} `, ); env.driveMain(); // verify that there are no compilation errors const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); // verify generated code for the unknown element const jsCode = env.getContents('test.js'); expect(jsCode).toContain('i0.ɵɵelement(0, "is-unknown");'); // verify schemas are not included in the generated code const jsCodeAoT = jsCode.slice( 0, jsCode.indexOf('(() => { (typeof ngDevMode === "undefined" || ngDevMode)'), ); expect(jsCodeAoT).not.toContain('schemas: [NO_ERRORS_SCHEMA]'); }); it('should error when a non-standalone component tries to use schemas', () => { env.write( 'test.ts', ` import {Component, NO_ERRORS_SCHEMA} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div></div>', schemas: [NO_ERRORS_SCHEMA], standalone: false, }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_NOT_STANDALONE)); expect(diags[0].messageText).toBe( `'schemas' is only valid on a component that is standalone.`, ); expect(getSourceCodeForDiagnostic(diags[0])).toEqual('[NO_ERRORS_SCHEMA]'); }); it
{ "end_byte": 9627, "start_byte": 583, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/standalone_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/standalone_spec.ts_9635_19254
compile a standalone component that imports an NgModule', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class TestDir {} @NgModule({ declarations: [TestDir], exports: [TestDir], }) export class TestModule {} @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [TestModule], }) export class TestCmp {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('dependencies: [TestModule, TestDir]'); }); it('should allow nested arrays in standalone component imports', () => { env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir {} export const DIRECTIVES = [TestDir]; @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [DIRECTIVES], }) export class TestCmp {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('dependencies: [TestDir]'); }); it('should deduplicate standalone component imports', () => { env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir {} export const DIRECTIVES = [TestDir]; @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [TestDir, DIRECTIVES], }) export class TestCmp {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('dependencies: [TestDir]'); }); it('should error when a standalone component imports a non-standalone entity', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class TestDir {} @NgModule({ declarations: [TestDir], exports: [TestDir], }) export class TestModule {} @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [TestDir], }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_IMPORT_NOT_STANDALONE)); expect(getSourceCodeForDiagnostic(diags[0])).toEqual('TestDir'); // The diagnostic produced here should suggest that the directive be imported via its // NgModule instead. expect(diags[0].relatedInformation).not.toBeUndefined(); expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![0])).toEqual('TestModule'); expect(diags[0].relatedInformation![0].messageText).toMatch( /It can be imported using its '.*' NgModule instead./, ); }); it('should error when a standalone component imports a ModuleWithProviders using a foreign function', () => { env.write( 'test.ts', ` import {Component, ModuleWithProviders, NgModule} from '@angular/core'; @NgModule({}) export class TestModule {} declare function moduleWithProviders(): ModuleWithProviders<TestModule>; @Component({ selector: 'test-cmp', template: '<div></div>', standalone: true, // @ts-ignore imports: [moduleWithProviders()], }) export class TestCmpWithLiteralImports {} const IMPORTS = [moduleWithProviders()]; @Component({ selector: 'test-cmp', template: '<div></div>', standalone: true, // @ts-ignore imports: IMPORTS, }) export class TestCmpWithReferencedImports {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_UNKNOWN_IMPORT)); // The import occurs within the array literal, such that the error can be reported for // the specific import that is rejected. expect(getSourceCodeForDiagnostic(diags[0])).toEqual('moduleWithProviders()'); expect(diags[1].code).toBe(ngErrorCode(ErrorCode.COMPONENT_UNKNOWN_IMPORT)); // The import occurs in a referenced variable, which reports the error on the full // `imports` expression. expect(getSourceCodeForDiagnostic(diags[1])).toEqual('IMPORTS'); }); it('should error when a standalone component imports a ModuleWithProviders', () => { env.write( 'test.ts', ` import {Component, ModuleWithProviders, NgModule} from '@angular/core'; @NgModule({}) export class TestModule { static forRoot(): ModuleWithProviders<TestModule> { return {ngModule: TestModule}; } } @Component({ selector: 'test-cmp', template: '<div></div>', standalone: true, // @ts-ignore imports: [TestModule.forRoot()], }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_UNKNOWN_IMPORT)); // The static interpreter does not track source locations for locally evaluated functions, // so the error is reported on the full `imports` expression. expect(getSourceCodeForDiagnostic(diags[0])).toEqual('[TestModule.forRoot()]'); }); it('should error when a standalone component imports a non-standalone entity, with a specific error when that entity is not exported', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class TestDir {} @NgModule({ declarations: [TestDir], }) export class TestModule {} @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [TestDir], }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_IMPORT_NOT_STANDALONE)); expect(getSourceCodeForDiagnostic(diags[0])).toEqual('TestDir'); expect(diags[0].relatedInformation).not.toBeUndefined(); expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![0])).toEqual('TestModule'); expect(diags[0].relatedInformation![0].messageText).toEqual( `It's declared in the 'TestModule' NgModule, but is not exported. Consider exporting it and importing the NgModule instead.`, ); }); it('should type-check standalone component templates', () => { env.write( 'test.ts', ` import {Component, Input, NgModule} from '@angular/core'; @Component({ selector: 'not-standalone', template: '', standalone: false, }) export class NotStandaloneCmp { @Input() value!: string; } @NgModule({ declarations: [NotStandaloneCmp], exports: [NotStandaloneCmp], }) export class NotStandaloneModule {} @Component({ standalone: true, selector: 'is-standalone', template: '', }) export class IsStandaloneCmp { @Input() value!: string; } @Component({ standalone: true, selector: 'test-cmp', imports: [NotStandaloneModule, IsStandaloneCmp], template: '<not-standalone [value]="3"></not-standalone><is-standalone [value]="true"></is-standalone>', }) export class TestCmp {} `, ); const diags = env.driveDiagnostics().map((diag) => diag.messageText); expect(diags.length).toBe(2); expect(diags).toContain(`Type 'number' is not assignable to type 'string'.`); expect(diags).toContain(`Type 'boolean' is not assignable to type 'string'.`); }); it
{ "end_byte": 19254, "start_byte": 9635, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/standalone_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/standalone_spec.ts_19262_27989
not spam errors if imports is misconfigured', () => { env.write( 'test.ts', ` import {Component, Input} from '@angular/core'; @Component({ standalone: true, selector: 'dep-cmp', template: '', }) export class DepCmp {} @Component({ // standalone: false, would ordinarily cause template type-checking errors // as well as an error about imports on a non-standalone component. imports: [DepCmp], selector: 'test-cmp', template: '<dep-cmp></dep-cmp>', standalone: false, }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('imports'); }); it('should handle a forwardRef used inside `imports`', () => { env.write( 'test.ts', ` import {Component, forwardRef} from '@angular/core'; @Component({ selector: 'test', standalone: true, imports: [forwardRef(() => StandaloneComponent)], template: "<other-standalone></other-standalone>" }) class TestComponent { } @Component({selector: 'other-standalone', standalone: true, template: ""}) class StandaloneComponent { } `, ); const diags = env.driveDiagnostics(); const jsCode = env.getContents('test.js'); expect(diags.length).toBe(0); expect(jsCode).toContain('standalone: true'); expect(jsCode).toContain('dependencies: () => [StandaloneComponent]'); }); }); describe('NgModule-side', () => { it('should not allow a standalone component to be declared in an NgModule', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test-cmp', template: 'Test', standalone: true, }) export class TestCmp {} @NgModule({ declarations: [TestCmp], }) export class TestModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.NGMODULE_DECLARATION_IS_STANDALONE)); expect(diags[0].messageText).toContain('Component TestCmp is standalone'); expect(getSourceCodeForDiagnostic(diags[0])).toEqual('TestCmp'); }); it('should not allow a standalone pipe to be declared in an NgModule', () => { env.write( 'test.ts', ` import {Pipe, NgModule} from '@angular/core'; @Pipe({ name: 'test', standalone: true, }) export class TestPipe {} @NgModule({ declarations: [TestPipe], }) export class TestModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.NGMODULE_DECLARATION_IS_STANDALONE)); expect(diags[0].messageText).toContain('Pipe TestPipe is standalone'); expect(getSourceCodeForDiagnostic(diags[0])).toEqual('TestPipe'); }); it('should allow a standalone component to be imported by an NgModule', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'st-cmp', standalone: true, template: 'Test', }) export class StandaloneCmp {} @Component({ selector: 'test-cmp', template: '<st-cmp></st-cmp>', standalone: false, }) export class TestCmp {} @NgModule({ declarations: [TestCmp], imports: [StandaloneCmp], }) export class TestModule {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('dependencies: [StandaloneCmp]'); }); it('should allow a standalone directive to be imported by an NgModule', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; @Directive({ selector: '[st-dir]', standalone: true, }) export class StandaloneDir {} @Component({ selector: 'test-cmp', template: '<div st-dir></div>', standalone: false, }) export class TestCmp {} @NgModule({ declarations: [TestCmp], imports: [StandaloneDir], }) export class TestModule {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('dependencies: [StandaloneDir]'); }); it('should allow a standalone pipe to be imported by an NgModule', () => { env.write( 'test.ts', ` import {Component, Pipe, NgModule} from '@angular/core'; @Pipe({ name: 'stpipe', standalone: true, }) export class StandalonePipe { transform(value: any): any { return value; } } @Component({ selector: 'test-cmp', template: '{{data | stpipe}}', standalone: false, }) export class TestCmp { data = 'test'; } @NgModule({ declarations: [TestCmp], imports: [StandalonePipe], }) export class TestModule {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('dependencies: [StandalonePipe]'); }); it('should error when a standalone entity is exported by an NgModule without importing it first', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir {} @NgModule({ exports: [TestDir], }) export class TestModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.NGMODULE_INVALID_REEXPORT)); expect(diags[0].messageText).toContain('it must be imported first'); expect(diagnosticToNode(diags[0], ts.isIdentifier).parent.parent.getText()).toEqual( 'exports: [TestDir]', ); }); it('should error when a non-standalone entity is imported into an NgModule', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class TestDir {} @NgModule({ imports: [TestDir], }) export class TestModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('is not standalone'); expect(diagnosticToNode(diags[0], ts.isIdentifier).parent.parent.getText()).toEqual( 'imports: [TestDir]', ); }); }); describe('other types', () => { it('should compile a basic standalone directive', () => { env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('standalone: true'); }); it('should compile a basic standalone pipe', () => { env.write( 'test.ts', ` import {Pipe} from '@angular/core'; @Pipe({ name: 'testpipe', standalone: true, }) export class TestPipe {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('standalone: true'); }); }); desc
{ "end_byte": 27989, "start_byte": 19262, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/standalone_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/standalone_spec.ts_27995_37063
from libraries', () => { it('should consume standalone directives from libraries', () => { env.write( 'lib.d.ts', ` import {ɵɵDirectiveDeclaration} from '@angular/core'; export declare class StandaloneDir { static ɵdir: ɵɵDirectiveDeclaration<StandaloneDir, "[dir]", never, {}, {}, never, never, true>; } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {StandaloneDir} from './lib'; @Component({ standalone: true, selector: 'test-cmp', template: '<div dir></div>', imports: [StandaloneDir], }) export class TestCmp {} `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('dependencies: [StandaloneDir]'); }); it('should consume standalone components from libraries', () => { env.write( 'lib.d.ts', ` import {ɵɵComponentDeclaration} from '@angular/core'; export declare class StandaloneCmp { static ɵcmp: ɵɵComponentDeclaration<StandaloneCmp, "standalone-cmp", never, {}, {}, never, never, true>; } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {StandaloneCmp} from './lib'; @Component({ standalone: true, selector: 'test-cmp', template: '<standalone-cmp></standalone-cmp>', imports: [StandaloneCmp], }) export class TestCmp {} `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('dependencies: [StandaloneCmp]'); }); it('should consume standalone pipes from libraries', () => { env.write( 'lib.d.ts', ` import {ɵɵPipeDeclaration} from '@angular/core'; export declare class StandalonePipe { transform(value: any): any; static ɵpipe: ɵɵPipeDeclaration<StandalonePipe, "standalone", true>; } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {StandalonePipe} from './lib'; @Component({ standalone: true, selector: 'test-cmp', template: '{{value | standalone}}', imports: [StandalonePipe], }) export class StandaloneComponent { value!: string; } `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('dependencies: [StandalonePipe]'); }); it('should compile imports using a const tuple in external library', () => { env.write( 'node_modules/external/index.d.ts', ` import {ɵɵDirectiveDeclaration} from '@angular/core'; export declare class StandaloneDir { static ɵdir: ɵɵDirectiveDeclaration<StandaloneDir, "[dir]", never, {}, {}, never, never, true>; } export declare const DECLARATIONS: readonly [typeof StandaloneDir]; `, ); env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; import {DECLARATIONS} from 'external'; @Component({ standalone: true, selector: 'test-cmp', template: '<div dir></div>', imports: [DECLARATIONS], }) export class TestCmp {} `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('import * as i1 from "external";'); expect(jsCode).toContain('dependencies: [i1.StandaloneDir]'); }); }); describe('optimizations', () => { it('does emit standalone components in injector imports if they contain providers', () => { env.write( 'test.ts', ` import {Component, Injectable, NgModule} from '@angular/core'; @Injectable() export class Service {} @NgModule({ providers: [Service], }) export class DepModule {} @Component({ standalone: true, selector: 'standalone-cmp', imports: [DepModule], template: '', }) export class StandaloneCmp {} @NgModule({ imports: [StandaloneCmp], exports: [StandaloneCmp], }) export class Module {} `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('i0.ɵɵdefineInjector({ imports: [StandaloneCmp] });'); }); it('does emit standalone components in injector imports if they import a NgModule from .d.ts', () => { env.write( 'dep.d.ts', ` import {ɵɵNgModuleDeclaration} from '@angular/core'; declare class DepModule { static ɵmod: ɵɵNgModuleDeclaration<DepModule, never, never, never>; } `, ); env.write( 'test.ts', ` import {Component, Injectable, NgModule} from '@angular/core'; import {DepModule} from './dep'; @Component({ standalone: true, selector: 'standalone-cmp', imports: [DepModule], template: '', }) export class StandaloneCmp {} @NgModule({ imports: [StandaloneCmp], exports: [StandaloneCmp], }) export class Module {} `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('i0.ɵɵdefineInjector({ imports: [StandaloneCmp] });'); }); it('does emit standalone components in injector imports if they import a component from .d.ts', () => { env.write( 'dep.d.ts', ` import {ɵɵComponentDeclaration} from '@angular/core'; export declare class DepCmp { static ɵcmp: ɵɵComponentDeclaration<DepCmp, "dep-cmp", never, {}, {}, never, never, true> } `, ); env.write( 'test.ts', ` import {Component, Injectable, NgModule} from '@angular/core'; import {DepCmp} from './dep'; @Component({ standalone: true, selector: 'standalone-cmp', imports: [DepCmp], template: '<dep-cmp/>', }) export class StandaloneCmp {} @NgModule({ imports: [StandaloneCmp], exports: [StandaloneCmp], }) export class Module {} `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('i0.ɵɵdefineInjector({ imports: [StandaloneCmp] });'); }); it('does not emit standalone directives or pipes in injector imports', () => { env.write( 'test.ts', ` import {Directive, NgModule, Pipe} from '@angular/core'; @Directive({ standalone: true, selector: '[dir]', }) export class StandaloneDir {} @Pipe({ standalone: true, name: 'standalone', }) export class StandalonePipe { transform(value: any): any {} } @NgModule({ imports: [StandaloneDir, StandalonePipe], exports: [StandaloneDir, StandalonePipe], }) export class Module {} `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('i0.ɵɵdefineInjector({});'); }); it('should exclude directives from NgModule imports if they expose no providers', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @NgModule({}) export class DepModule {} @Component({ standalone: true, selector: 'test-cmp', imports: [DepModule], template: '', }) export class TestCmp {} @NgModule({ imports: [TestCmp], exports: [TestCmp], }) export class TestModule {} `, ); env.driveMain(); const jsCode = env.getContents('test.js'); expect(jsCode).toContain('i0.ɵɵdefineInjector({});'); }); }); }); describe('strictStandalone flag', () => {
{ "end_byte": 37063, "start_byte": 27995, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/standalone_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/standalone_spec.ts_37067_39105
env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({strictTemplates: true, strictStandalone: true}); }); it('should not allow a non-standalone component', () => { env.write( 'app.ts', ` import {Component} from '@angular/core'; @Component({standalone: false, template: ''}) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toEqual(ngErrorCode(ErrorCode.NON_STANDALONE_NOT_ALLOWED)); expect(diags[0].messageText).toContain('component'); }); it('should not allow a non-standalone directive', () => { env.write( 'app.ts', ` import {Directive} from '@angular/core'; @Directive({standalone: false}) export class TestDir {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toEqual(ngErrorCode(ErrorCode.NON_STANDALONE_NOT_ALLOWED)); expect(diags[0].messageText).toContain('directive'); }); it('should allow a no-arg directive', () => { env.write( 'app.ts', ` import {Directive} from '@angular/core'; @Directive() export class TestDir {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not allow a non-standalone pipe', () => { env.write( 'app.ts', ` import {Pipe} from '@angular/core'; @Pipe({name: 'test', standalone: false}) export class TestPipe {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toEqual(ngErrorCode(ErrorCode.NON_STANDALONE_NOT_ALLOWED)); expect(diags[0].messageText).toContain('pipe'); }); }); });
{ "end_byte": 39105, "start_byte": 37067, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/standalone_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/hmr_spec.ts_0_383
/*! * @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 {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env';
{ "end_byte": 383, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/hmr_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/hmr_spec.ts_385_8574
runInEachFileSystem(() => { describe('HMR code generation', () => { const testFiles = loadStandardTestFiles(); let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig(); }); function enableHmr(): void { env.write( 'tsconfig.json', JSON.stringify({ extends: './tsconfig-base.json', angularCompilerOptions: { _enableHmr: true, }, }), ); } it('should not generate an HMR code by default', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: 'hello', standalone: true, }) export class Cmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const hmrContents = env.driveHmr('test.ts', 'Cmp'); expect(jsContents).not.toContain('import.meta.hot'); expect(jsContents).not.toContain('replaceMetadata'); expect(hmrContents).toBe(null); }); it('should generate an HMR initializer and update code when enabled', () => { enableHmr(); env.write( 'dep.ts', ` import {Directive, InjectionToken} from '@angular/core'; export const TOKEN = new InjectionToken<any>('token'); export function transformValue(value: string) { return parseInt(value); } @Directive({ selector: '[dep]', standalone: true, }) export class Dep {} `, ); env.write( 'test.ts', ` import {Component, ViewChild, Input, Inject} from '@angular/core'; import {Dep, transformValue, TOKEN} from './dep'; @Component({ selector: 'cmp', standalone: true, template: '<div dep><div>', imports: [Dep], }) export class Cmp { @ViewChild(Dep) dep: Dep; @Input({transform: transformValue}) value: number; constructor(@Inject(TOKEN) readonly token: any) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const hmrContents = env.driveHmr('test.ts', 'Cmp'); // We need a regex match here, because the file path changes based on // the file system and the timestamp will be different for each test run. expect(jsContents).toMatch( /import\.meta\.hot && import\.meta\.hot\.on\("angular:component-update", d => { if \(d\.id == "test\.ts%40Cmp"\) {/, ); expect(jsContents).toMatch( /import\(\s*\/\* @vite-ignore \*\/\s+"\/@ng\/component\?c=test\.ts%40Cmp&t=" \+ encodeURIComponent\(d.timestamp\)/, ); expect(jsContents).toMatch( /\).then\(m => i0\.ɵɵreplaceMetadata\(Cmp, m\.default, \[Dep, transformValue, TOKEN, Component, Inject, ViewChild, Input\]\)\);/, ); expect(hmrContents).toContain( 'export default function Cmp_UpdateMetadata(Cmp, __ngCore__, Dep, transformValue, TOKEN, Component, Inject, ViewChild, Input) {', ); expect(hmrContents).toContain('Cmp.ɵfac = function Cmp_Factory'); expect(hmrContents).toContain('Cmp.ɵcmp = /*@__PURE__*/ __ngCore__.ɵɵdefineComponent'); expect(hmrContents).toContain('__ngCore__.ɵsetClassMetadata(Cmp,'); expect(hmrContents).toContain('__ngCore__.ɵsetClassDebugInfo(Cmp,'); }); it('should generate an HMR update function for a component that has embedded views', () => { enableHmr(); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', standalone: true, template: '@if (true) {hello}', }) export class Cmp {} `, ); const hmrContents = env.driveHmr('test.ts', 'Cmp'); expect(hmrContents).toContain( 'export default function Cmp_UpdateMetadata(Cmp, __ngCore__, Component) {', ); expect(hmrContents).toContain('function Cmp_Conditional_0_Template(rf, ctx) {'); expect(hmrContents).toContain('__ngCore__.ɵɵtemplate(0, Cmp_Conditional_0_Template, 1, 0);'); }); it('should generate an HMR update function for a component whose definition produces variables', () => { enableHmr(); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', standalone: true, template: '<ng-content select="header"/><ng-content/>', }) export class Cmp {} `, ); const hmrContents = env.driveHmr('test.ts', 'Cmp'); expect(hmrContents).toContain( 'export default function Cmp_UpdateMetadata(Cmp, __ngCore__, Component) {', ); expect(hmrContents).toContain('const _c0 = [[["header"]], "*"];'); expect(hmrContents).toContain('const _c1 = ["header", "*"];'); expect(hmrContents).toContain('ngContentSelectors: _c1'); expect(hmrContents).toContain('__ngCore__.ɵɵprojectionDef(_c0);'); }); it('should not defer dependencies when HMR is enabled', () => { enableHmr(); env.write( 'dep.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dep]', standalone: true, }) export class Dep {} `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {Dep} from './dep'; @Component({ selector: 'cmp', standalone: true, template: '@defer (on timer(1000)) {<div dep></div>}', imports: [Dep], }) export class Cmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const hmrContents = env.driveHmr('test.ts', 'Cmp'); expect(jsContents).toContain(`import { Dep } from './dep';`); expect(jsContents).toContain('const Cmp_Defer_1_DepsFn = () => [Dep];'); expect(jsContents).toContain('function Cmp_Defer_0_Template(rf, ctx) { if (rf & 1) {'); expect(jsContents).toContain('i0.ɵɵdefer(1, 0, Cmp_Defer_1_DepsFn);'); expect(hmrContents).toContain( 'export default function Cmp_UpdateMetadata(Cmp, __ngCore__, Component, Dep) {', ); expect(hmrContents).toContain('const Cmp_Defer_1_DepsFn = () => [Dep];'); expect(hmrContents).toContain('function Cmp_Defer_0_Template(rf, ctx) {'); expect(hmrContents).toContain('__ngCore__.ɵɵdefer(1, 0, Cmp_Defer_1_DepsFn);'); expect(hmrContents).not.toContain('import('); }); it('should not generate an HMR update function for a component that has errors', () => { enableHmr(); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', standalone: true, template: '{{#invalid}}', }) export class Cmp {} `, ); const hmrContents = env.driveHmr('test.ts', 'Cmp'); expect(hmrContents).toBe(null); }); it('should not generate an HMR update function for an Angular class that does not support HMR', () => { enableHmr(); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Component({ selector: '[dir]', standalone: true }) export class Dir {} `, ); const hmrContents = env.driveHmr('test.ts', 'Dir'); expect(hmrContents).toBe(null); }); it('should not generate an HMR update function for an undecorated class', () => { enableHmr(); env.write( 'test.ts', ` export class Foo {} `, ); const hmrContents = env.driveHmr('test.ts', 'Foo'); expect(hmrContents).toBe(null); }); }); });
{ "end_byte": 8574, "start_byte": 385, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/hmr_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_0_1482
/** * @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 ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../src/ngtsc/diagnostics'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment, TsConfigOptions} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('local compilation', () => { let env!: NgtscTestEnvironment; function tsconfig(extraOpts: TsConfigOptions = {}) { const tsconfig: {[key: string]: any} = { extends: '../tsconfig-base.json', compilerOptions: { baseUrl: '.', rootDirs: ['/app'], }, angularCompilerOptions: { compilationMode: 'experimental-local', ...extraOpts, }, }; env.write('tsconfig.json', JSON.stringify(tsconfig, null, 2)); } beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); tsconfig(); }); it('should produce no TS semantic diagnostics', () => { env.write( 'test.ts', ` import {SubExternalStuff} from './some-where'; `, ); env.driveMain(); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); });
{ "end_byte": 1482, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_1488_10832
describe('extra imports generation', () => { beforeEach(() => { const tsconfig: {[key: string]: any} = { extends: '../tsconfig-base.json', compilerOptions: { baseUrl: '.', rootDirs: ['/app'], }, angularCompilerOptions: { compilationMode: 'experimental-local', generateExtraImportsInLocalMode: true, }, }; env.write('tsconfig.json', JSON.stringify(tsconfig, null, 2)); }); it('should only include NgModule external import as global import', () => { env.write( 'comp1.ts', ` import {Component} from '@angular/core'; @Component({template:''}) export class Comp1 { } `, ); env.write( 'module1.ts', ` import {NgModule} from '@angular/core'; import {Comp1} from 'comp1'; @NgModule({declarations:[Comp1]}) export class Module1 { } `, ); env.write( 'a.ts', ` import {NgModule} from '@angular/core'; import {SomeExternalStuff} from '/some_external_file'; import {SomeExternalStuff2} from '/some_external_file2'; import {BModule} from 'b'; @NgModule({imports: [SomeExternalStuff, BModule]}) export class AModule { } `, ); env.write( 'b.ts', ` import {NgModule} from '@angular/core'; @NgModule({}) export class BModule { } `, ); env.driveMain(); const Comp1Contents = env.getContents('comp1.js'); expect(Comp1Contents) .withContext('NgModule external imports should be included in the global imports') .toContain('import "/some_external_file"'); expect(Comp1Contents) .withContext( 'External import which is not an NgModule import should not be included in the global import', ) .not.toContain('import "/some_external_file2"'); expect(Comp1Contents) .withContext('NgModule internal import should not be included in the global import') .not.toContain('import "b"'); }); it('should include global imports only in the eligible files', () => { env.write( 'module_and_comp.ts', ` import {NgModule, Component} from '@angular/core'; @Component({template:'', standalone: true}) export class Comp3 { } @NgModule({declarations:[Comp3]}) export class Module3 { } `, ); env.write( 'standalone_comp.ts', ` import {Component} from '@angular/core'; @Component({template:'', standalone: true}) export class Comp2 { } `, ); env.write( 'comp1.ts', ` import {Component} from '@angular/core'; @Component({template:''}) export class Comp1 { } `, ); env.write( 'module1.ts', ` import {NgModule} from '@angular/core'; import {Comp1} from 'comp1'; @NgModule({declarations:[Comp1]}) export class Module1 { } `, ); env.write( 'a.ts', ` import {NgModule} from '@angular/core'; import {SomeExternalStuff} from '/some_external_file'; import {SomeExternalStuff2} from '/some_external_file2'; import {BModule} from 'b'; @NgModule({imports: [SomeExternalStuff, BModule]}) export class AModule { } `, ); env.write( 'b.ts', ` import {NgModule} from '@angular/core'; @NgModule({}) export class BModule { } `, ); env.write( 'c.ts', ` // Some code `, ); env.driveMain(); expect(env.getContents('comp1.js')) .withContext( 'Global imports should be generated when a component has its NgModule in a different file', ) .toContain('import "/some_external_file"'); expect(env.getContents('standalone_comp.js')) .withContext('Global imports should not be generated when all components are standalone') .not.toContain('import "/some_external_file"'); expect(env.getContents('module_and_comp.js')) .withContext( 'Global imports should not be generated when components and their NgModules are in the same file', ) .not.toContain('import "/some_external_file"'); expect(env.getContents('a.js')) .withContext('Global imports should not be generated when the file has no component') .not.toContain('import "/some_external_file"'); expect(env.getContents('c.js')) .withContext('Global imports should not be generated for non-Angular files') .not.toContain('import "/some_external_file"'); }); it('should include NgModule namespace external import as global import', () => { env.write( 'comp1.ts', ` import {Component} from '@angular/core'; @Component({template:''}) export class Comp1 { } `, ); env.write( 'module1.ts', ` import {NgModule} from '@angular/core'; import {Comp1} from 'comp1'; @NgModule({declarations:[Comp1]}) export class Module1 { } `, ); env.write( 'a.ts', ` import {NgModule} from '@angular/core'; import * as n from '/some_external_file'; import {BModule} from 'b'; @NgModule({imports: [n.SomeExternalStuff]}) export class AModule { } `, ); env.write( 'test.ts', ` // Some code `, ); env.driveMain(); expect(env.getContents('comp1.js')).toContain('import "/some_external_file"'); }); it('should include nested NgModule external import as global import - case of named import', () => { env.write( 'comp1.ts', ` import {Component} from '@angular/core'; @Component({template:''}) export class Comp1 { } `, ); env.write( 'module1.ts', ` import {NgModule} from '@angular/core'; import {Comp1} from 'comp1'; @NgModule({declarations:[Comp1]}) export class Module1 { } `, ); env.write( 'a.ts', ` import {NgModule} from '@angular/core'; import {SomeExternalStuff} from '/some_external_file'; import {BModule} from 'b'; @NgModule({imports: [[[SomeExternalStuff]]]}) export class AModule { } `, ); env.driveMain(); expect(env.getContents('comp1.js')).toContain('import "/some_external_file"'); }); it('should include nested NgModule external import as global import - case of namespace import', () => { env.write( 'comp1.ts', ` import {Component} from '@angular/core'; @Component({template:''}) export class Comp1 { } `, ); env.write( 'module1.ts', ` import {NgModule} from '@angular/core'; import {Comp1} from 'comp1'; @NgModule({declarations:[Comp1]}) export class Module1 { } `, ); env.write( 'a.ts', ` import {NgModule} from '@angular/core'; import * as n from '/some_external_file'; import {BModule} from 'b'; @NgModule({imports: [[[n.SomeExternalStuff]]]}) export class AModule { } `, ); env.driveMain(); expect(env.getContents('comp1.js')).toContain('import "/some_external_file"'); }); it('should include NgModule external imports as global imports - case of multiple nested imports including named and namespace imports', () => { env.write( 'comp1.ts', ` import {Component} from '@angular/core'; @Component({template:''}) export class Comp1 { } `, ); env.write( 'module1.ts', ` import {NgModule} from '@angular/core'; import {Comp1} from 'comp1'; @NgModule({declarations:[Comp1]}) export class Module1 { } `, ); env.write( 'a.ts', ` import {NgModule} from '@angular/core'; import {SomeExternalStuff} from '/some_external_file'; import * as n from '/some_external_file2'; import {BModule} from 'b'; @NgModule({imports: [[SomeExternalStuff], [n.SomeExternalStuff]]}) export class AModule { } `, ); env.driveMain(); expect(env.getContents('comp1.js')).toContain('import "/some_external_file"'); expect(env.getContents('comp1.js')).toContain('import "/some_external_file2"'); });
{ "end_byte": 10832, "start_byte": 1488, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_10840_14877
it('should include extra import for the local component dependencies (component, directive and pipe)', () => { env.write( 'internal_comp.ts', ` import {Component} from '@angular/core'; @Component({ template: '...', selector: 'internal-comp', standalone: false, }) export class InternalComp { } `, ); env.write( 'internal_dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[internal-dir]', standalone: false, }) export class InternalDir { } `, ); env.write( 'internal_pipe.ts', ` import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'internalPipe', standalone: false, }) export class InternalPipe implements PipeTransform { transform(value: number): number { return value*2; } } `, ); env.write( 'internal_module.ts', ` import {NgModule} from '@angular/core'; import {InternalComp} from 'internal_comp'; import {InternalDir} from 'internal_dir'; import {InternalPipe} from 'internal_pipe'; @NgModule({declarations: [InternalComp, InternalDir, InternalPipe], exports: [InternalComp, InternalDir, InternalPipe]}) export class InternalModule { } `, ); env.write( 'main_comp.ts', ` import {Component} from '@angular/core'; @Component({template: '<internal-comp></internal-comp> <span internal-dir></span> <span>{{2 | internalPipe}}</span>'}) export class MainComp { } `, ); env.write( 'main_module.ts', ` import {NgModule} from '@angular/core'; import {MainComp} from 'main_comp'; import {InternalModule} from 'internal_module'; @NgModule({declarations: [MainComp], imports: [InternalModule]}) export class MainModule { } `, ); env.driveMain(); expect(env.getContents('main_comp.js')).toContain('import "internal_comp"'); expect(env.getContents('main_comp.js')).toContain('import "internal_dir"'); expect(env.getContents('main_comp.js')).toContain('import "internal_pipe"'); }); it('should not include extra import and remote scope runtime for the local component dependencies when cycle is produced', () => { env.write( 'internal_comp.ts', ` import {Component} from '@angular/core'; import {cycleCreatingDep} from './main_comp'; @Component({template: '...', selector: 'internal-comp'}) export class InternalComp { } `, ); env.write( 'internal_module.ts', ` import {NgModule} from '@angular/core'; import {InternalComp} from 'internal_comp'; @NgModule({declarations: [InternalComp], exports: [InternalComp]}) export class InternalModule { } `, ); env.write( 'main_comp.ts', ` import {Component} from '@angular/core'; @Component({template: '<internal-comp></internal-comp>'}) export class MainComp { } `, ); env.write( 'main_module.ts', ` import {NgModule} from '@angular/core'; import {MainComp} from 'main_comp'; import {InternalModule} from 'internal_module'; @NgModule({declarations: [MainComp], imports: [InternalModule]}) export class MainModule { } `, ); env.driveMain(); expect(env.getContents('main_comp.js')).not.toContain('import "internal_comp"'); expect(env.getContents('main_module.js')).not.toContain('ɵɵsetComponentScope'); }); });
{ "end_byte": 14877, "start_byte": 10840, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_14883_20804
scribe('ng module injector def', () => { it('should produce empty injector def imports when module has no imports/exports', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; @NgModule({}) export class MainModule { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('MainModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({})'); }); it('should include raw module imports array elements (including forward refs) in the injector def imports', () => { env.write( 'test.ts', ` import {NgModule, forwardRef} from '@angular/core'; import {SubModule1} from './some-where'; import {SubModule2} from './another-where'; @NgModule({}) class LocalModule1 {} @NgModule({ imports: [SubModule1, forwardRef(() => SubModule2), LocalModule1, forwardRef(() => LocalModule2)], }) export class MainModule { } @NgModule({}) class LocalModule2 {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'MainModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ imports: [SubModule1, forwardRef(() => SubModule2), LocalModule1, forwardRef(() => LocalModule2)] })', ); }); it('should include non-array raw module imports as it is in the injector def imports', () => { env.write( 'test.ts', ` import {NgModule, forwardRef} from '@angular/core'; import {SubModule1} from './some-where'; import {SubModule2} from './another-where'; const NG_IMPORTS = [SubModule1, forwardRef(() => SubModule2), LocalModule1, forwardRef(() => LocalModule2)]; @NgModule({}) class LocalModule1 {} @NgModule({ imports: NG_IMPORTS, }) export class MainModule { } @NgModule({}) class LocalModule2 {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'MainModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ imports: [NG_IMPORTS] })', ); }); it('should include raw module exports array elements (including forward refs) in the injector def imports', () => { env.write( 'test.ts', ` import {NgModule, forwardRef} from '@angular/core'; import {SubModule1} from './some-where'; import {SubModule2} from './another-where'; @NgModule({}) class LocalModule1 {} @NgModule({ exports: [SubModule1, forwardRef(() => SubModule2), LocalModule1, forwardRef(() => LocalModule2)], }) export class MainModule { } @NgModule({}) class LocalModule2 {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'MainModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ imports: [SubModule1, forwardRef(() => SubModule2), LocalModule1, forwardRef(() => LocalModule2)] })', ); }); it('should include non-array raw module exports (including forward refs) in the injector def imports', () => { env.write( 'test.ts', ` import {NgModule, forwardRef} from '@angular/core'; import {SubModule1} from './some-where'; import {SubModule2} from './another-where'; const NG_EXPORTS = [SubModule1, forwardRef(() => SubModule2), LocalModule1, forwardRef(() => LocalModule2)]; @NgModule({}) class LocalModule1 {} @NgModule({ exports: NG_EXPORTS, }) export class MainModule { } @NgModule({}) class LocalModule2 {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'MainModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ imports: [NG_EXPORTS] })', ); }); it('should concat raw module imports and exports arrays (including forward refs) in the injector def imports', () => { env.write( 'test.ts', ` import {NgModule, forwardRef} from '@angular/core'; import {SubModule1, SubModule2} from './some-where'; import {SubModule3, SubModule4} from './another-where'; @NgModule({ imports: [SubModule1, forwardRef(() => SubModule2)], exports: [SubModule3, forwardRef(() => SubModule4)], }) export class MainModule { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'MainModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ imports: [SubModule1, forwardRef(() => SubModule2), SubModule3, forwardRef(() => SubModule4)] })', ); }); it('should combines non-array raw module imports and exports (including forward refs) in the injector def imports', () => { env.write( 'test.ts', ` import {NgModule, forwardRef} from '@angular/core'; import {NG_IMPORTS} from './some-where'; import {NG_EXPORTS} from './another-where'; @NgModule({ imports: NG_IMPORTS, exports: NG_EXPORTS, }) export class MainModule { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'MainModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ imports: [NG_IMPORTS, NG_EXPORTS] })', ); }); }); describe('compone
{ "end_byte": 20804, "start_byte": 14883, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_20810_28901
endencies', () => { it('should generate ɵɵgetComponentDepsFactory for component def dependencies - for non-standalone component ', () => { env.write( 'test.ts', ` import {NgModule, Component} from '@angular/core'; @Component({ selector: 'test-main', template: '<span>Hello world!</span>', standalone: false, }) export class MainComponent { } @NgModule({ declarations: [MainComponent], }) export class MainModule { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('dependencies: i0.ɵɵgetComponentDepsFactory(MainComponent)'); }); it('should generate ɵɵgetComponentDepsFactory with raw imports as second param for component def dependencies - for standalone component with non-empty imports', () => { env.write( 'test.ts', ` import {Component, forwardRef} from '@angular/core'; import {SomeThing} from 'some-where'; import {SomeThing2} from 'some-where2'; @Component({ standalone: true, imports: [SomeThing, forwardRef(()=>SomeThing2)], selector: 'test-main', template: '<span>Hello world!</span>', }) export class MainComponent { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'dependencies: i0.ɵɵgetComponentDepsFactory(MainComponent, [SomeThing, forwardRef(() => SomeThing2)])', ); }); it('should generate ɵɵgetComponentDepsFactory with raw non-array imports as second param for component def dependencies - for standalone component with non-empty imports', () => { env.write( 'test.ts', ` import {Component, forwardRef} from '@angular/core'; import {SomeThing} from 'some-where'; import {SomeThing2} from 'some-where2'; const NG_IMPORTS = [SomeThing, forwardRef(()=>SomeThing2)]; @Component({ standalone: true, imports: NG_IMPORTS, selector: 'test-main', template: '<span>Hello world!</span>', }) export class MainComponent { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'dependencies: i0.ɵɵgetComponentDepsFactory(MainComponent, NG_IMPORTS)', ); }); it('should generate ɵɵgetComponentDepsFactory with empty array as secon d arg for standalone component with empty imports', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, imports: [], selector: 'test-main', template: '<span>Hello world!</span>', }) export class MainComponent { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'dependencies: i0.ɵɵgetComponentDepsFactory(MainComponent, [])', ); }); it('should not generate ɵɵgetComponentDepsFactory for standalone component with no imports', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'test-main', template: '<span>Hello world!</span>', }) export class MainComponent { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('i0.ɵɵgetComponentDepsFactory'); }); }); describe('component fields', () => { it('should place the changeDetection as it is into the component def', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; import {SomeWeirdThing} from 'some-where'; @Component({ changeDetection: SomeWeirdThing, template: '<span>Hello world!</span>', }) export class MainComponent { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('changeDetection: SomeWeirdThing'); }); it('should place the correct value of encapsulation into the component def - case of ViewEncapsulation.Emulated with no styles', () => { env.write( 'test.ts', ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ encapsulation: ViewEncapsulation.Emulated, template: '<span>Hello world!</span>', }) export class MainComponent { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // If there is no style, don't generate css selectors on elements by setting // encapsulation to none (=2) expect(jsContents).toContain('encapsulation: 2'); }); it('should place the correct value of encapsulation into the component def - case of ViewEncapsulation.Emulated with styles', () => { env.write( 'test.ts', ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ encapsulation: ViewEncapsulation.Emulated, styles: ['color: blue'], template: '<span>Hello world!</span>', }) export class MainComponent { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // encapsulation is set only for non-default value expect(jsContents).not.toContain('encapsulation: 0'); expect(jsContents).toContain('styles: ["color: blue"]'); }); it('should place the correct value of encapsulation into the component def - case of ViewEncapsulation.ShadowDom', () => { env.write( 'test.ts', ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ encapsulation: ViewEncapsulation.ShadowDom, template: '<span>Hello world!</span>', }) export class MainComponent { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('encapsulation: 3'); }); it('should place the correct value of encapsulation into the component def - case of ViewEncapsulation.None', () => { env.write( 'test.ts', ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ encapsulation: ViewEncapsulation.None, template: '<span>Hello world!</span>', }) export class MainComponent { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('encapsulation: 2'); }); it('should default encapsulation to Emulated', () => { env.write( 'test.ts', ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ template: '<span>Hello world!</span>', }) export class MainComponent { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // If there is no style, don't generate css selectors on elements by setting // encapsulation to none (=2) expect(jsContents).toContain('encapsulation: 2'); }); }); describe('constructor injection', ()
{ "end_byte": 28901, "start_byte": 20810, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_28907_37176
it('should include injector types with all possible import/injection styles into component factory', () => { env.write( 'test.ts', ` import {Component, NgModule, Attribute, Inject} from '@angular/core'; import {SomeClass} from './some-where' import {SomeService1} from './some-where1' import SomeService2 from './some-where2' import * as SomeWhere3 from './some-where3' import * as SomeWhere4 from './some-where4' @Component({ selector: 'test-main', template: '<span>Hello world</span>', }) export class MainComponent { constructor( private someService1: SomeService1, private someService2: SomeService2, private someService3: SomeWhere3.SomeService3, private someService4: SomeWhere4.nested.SomeService4, @Attribute('title') title: string, @Inject(MESSAGE_TOKEN) tokenMessage: SomeClass, ) {} } @NgModule({ declarations: [MainComponent], }) export class MainModule { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainComponent.ɵfac = function MainComponent_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MainComponent)(i0.ɵɵdirectiveInject(i1.SomeService1), i0.ɵɵdirectiveInject(SomeService2), i0.ɵɵdirectiveInject(i2.SomeService3), i0.ɵɵdirectiveInject(i3.nested.SomeService4), i0.ɵɵinjectAttribute('title'), i0.ɵɵdirectiveInject(MESSAGE_TOKEN)); };`, ); }); it('should include injector types with all possible import/injection styles into standalone component factory', () => { env.write( 'test.ts', ` import {Component, NgModule, Attribute, Inject} from '@angular/core'; import {SomeClass} from './some-where' import {SomeService1} from './some-where1' import SomeService2 from './some-where2' import * as SomeWhere3 from './some-where3' import * as SomeWhere4 from './some-where4' @Component({ standalone: true, selector: 'test-main', template: '<span>Hello world</span>', }) export class MainComponent { constructor( private someService1: SomeService1, private someService2: SomeService2, private someService3: SomeWhere3.SomeService3, private someService4: SomeWhere4.nested.SomeService4, @Attribute('title') title: string, @Inject(MESSAGE_TOKEN) tokenMessage: SomeClass, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainComponent.ɵfac = function MainComponent_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MainComponent)(i0.ɵɵdirectiveInject(i1.SomeService1), i0.ɵɵdirectiveInject(SomeService2), i0.ɵɵdirectiveInject(i2.SomeService3), i0.ɵɵdirectiveInject(i3.nested.SomeService4), i0.ɵɵinjectAttribute('title'), i0.ɵɵdirectiveInject(MESSAGE_TOKEN)); };`, ); }); it('should include injector types with all possible import/injection styles into directive factory', () => { env.write( 'test.ts', ` import {Directive, NgModule, Attribute, Inject} from '@angular/core'; import {SomeClass} from './some-where' import {SomeService1} from './some-where1' import SomeService2 from './some-where2' import * as SomeWhere3 from './some-where3' import * as SomeWhere4 from './some-where4' @Directive({ }) export class MainDirective { constructor( private someService1: SomeService1, private someService2: SomeService2, private someService3: SomeWhere3.SomeService3, private someService4: SomeWhere4.nested.SomeService4, @Attribute('title') title: string, @Inject(MESSAGE_TOKEN) tokenMessage: SomeClass, ) {} } @NgModule({ declarations: [MainDirective], }) export class MainModule { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainDirective.ɵfac = function MainDirective_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MainDirective)(i0.ɵɵdirectiveInject(i1.SomeService1), i0.ɵɵdirectiveInject(SomeService2), i0.ɵɵdirectiveInject(i2.SomeService3), i0.ɵɵdirectiveInject(i3.nested.SomeService4), i0.ɵɵinjectAttribute('title'), i0.ɵɵdirectiveInject(MESSAGE_TOKEN)); };`, ); }); it('should include injector types with all possible import/injection styles into standalone directive factory', () => { env.write( 'test.ts', ` import {Directive, Attribute, Inject} from '@angular/core'; import {SomeClass} from './some-where' import {SomeService1} from './some-where1' import SomeService2 from './some-where2' import * as SomeWhere3 from './some-where3' import * as SomeWhere4 from './some-where4' @Directive({ standalone: true, }) export class MainDirective { constructor( private someService1: SomeService1, private someService2: SomeService2, private someService3: SomeWhere3.SomeService3, private someService4: SomeWhere4.nested.SomeService4, @Attribute('title') title: string, @Inject(MESSAGE_TOKEN) tokenMessage: SomeClass, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainDirective.ɵfac = function MainDirective_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MainDirective)(i0.ɵɵdirectiveInject(i1.SomeService1), i0.ɵɵdirectiveInject(SomeService2), i0.ɵɵdirectiveInject(i2.SomeService3), i0.ɵɵdirectiveInject(i3.nested.SomeService4), i0.ɵɵinjectAttribute('title'), i0.ɵɵdirectiveInject(MESSAGE_TOKEN)); };`, ); }); it('should include injector types with all possible import/injection styles into pipe factory', () => { env.write( 'test.ts', ` import {Pipe, NgModule, Attribute, Inject} from '@angular/core'; import {SomeClass} from './some-where' import {SomeService1} from './some-where1' import SomeService2 from './some-where2' import * as SomeWhere3 from './some-where3' import * as SomeWhere4 from './some-where4' @Pipe({name: 'pipe'}) export class MainPipe { constructor( private someService1: SomeService1, private someService2: SomeService2, private someService3: SomeWhere3.SomeService3, private someService4: SomeWhere4.nested.SomeService4, @Attribute('title') title: string, @Inject(MESSAGE_TOKEN) tokenMessage: SomeClass, ) {} } @NgModule({ declarations: [MainPipe], }) export class MainModule { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainPipe.ɵfac = function MainPipe_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MainPipe)(i0.ɵɵdirectiveInject(i1.SomeService1, 16), i0.ɵɵdirectiveInject(SomeService2, 16), i0.ɵɵdirectiveInject(i2.SomeService3, 16), i0.ɵɵdirectiveInject(i3.nested.SomeService4, 16), i0.ɵɵinjectAttribute('title'), i0.ɵɵdirectiveInject(MESSAGE_TOKEN, 16)); };`, ); }); it('should include injector types with all possible import/injection styles into standalone pipe fac
{ "end_byte": 37176, "start_byte": 28907, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_37184_45786
) => { env.write( 'test.ts', ` import {Pipe, Attribute, Inject} from '@angular/core'; import {SomeClass} from './some-where' import {SomeService1} from './some-where1' import SomeService2 from './some-where2' import * as SomeWhere3 from './some-where3' import * as SomeWhere4 from './some-where4' @Pipe({ name: 'pipe', standalone: true, }) export class MainPipe { constructor( private someService1: SomeService1, private someService2: SomeService2, private someService3: SomeWhere3.SomeService3, private someService4: SomeWhere4.nested.SomeService4, @Attribute('title') title: string, @Inject(MESSAGE_TOKEN) tokenMessage: SomeClass, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainPipe.ɵfac = function MainPipe_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MainPipe)(i0.ɵɵdirectiveInject(i1.SomeService1, 16), i0.ɵɵdirectiveInject(SomeService2, 16), i0.ɵɵdirectiveInject(i2.SomeService3, 16), i0.ɵɵdirectiveInject(i3.nested.SomeService4, 16), i0.ɵɵinjectAttribute('title'), i0.ɵɵdirectiveInject(MESSAGE_TOKEN, 16)); };`, ); }); it('should include injector types with all possible import/injection styles into injectable factory', () => { env.write( 'test.ts', ` import {Injectable, Attribute, Inject} from '@angular/core'; import {SomeClass} from './some-where' import {SomeService1} from './some-where1' import SomeService2 from './some-where2' import * as SomeWhere3 from './some-where3' import * as SomeWhere4 from './some-where4' @Injectable({ providedIn: 'root', }) export class MainService { constructor( private someService1: SomeService1, private someService2: SomeService2, private someService3: SomeWhere3.SomeService3, private someService4: SomeWhere4.nested.SomeService4, @Attribute('title') title: string, @Inject(MESSAGE_TOKEN) tokenMessage: SomeClass, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainService.ɵfac = function MainService_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MainService)(i0.ɵɵinject(i1.SomeService1), i0.ɵɵinject(SomeService2), i0.ɵɵinject(i2.SomeService3), i0.ɵɵinject(i3.nested.SomeService4), i0.ɵɵinjectAttribute('title'), i0.ɵɵinject(MESSAGE_TOKEN)); };`, ); }); it('should include injector types with all possible import/injection styles into ng module factory', () => { env.write( 'test.ts', ` import {Component, NgModule, Attribute, Inject} from '@angular/core'; import {SomeClass} from './some-where' import {SomeService1} from './some-where1' import SomeService2 from './some-where2' import * as SomeWhere3 from './some-where3' import * as SomeWhere4 from './some-where4' @NgModule({ }) export class MainModule { constructor( private someService1: SomeService1, private someService2: SomeService2, private someService3: SomeWhere3.SomeService3, private someService4: SomeWhere4.nested.SomeService4, @Attribute('title') title: string, @Inject(MESSAGE_TOKEN) tokenMessage: SomeClass, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainModule.ɵfac = function MainModule_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MainModule)(i0.ɵɵinject(i1.SomeService1), i0.ɵɵinject(SomeService2), i0.ɵɵinject(i2.SomeService3), i0.ɵɵinject(i3.nested.SomeService4), i0.ɵɵinjectAttribute('title'), i0.ɵɵinject(MESSAGE_TOKEN)); };`, ); }); it('should generate invalid factory for injectable when type parameter types are used as token', () => { env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable() export class MainService<S> { constructor( private someService1: S, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainService.ɵfac = function MainService_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory(); };`, ); }); it('should generate invalid factory for injectable when when token is imported as type', () => { env.write( 'test.ts', ` import {Injectable} from '@angular/core'; import {type MyService} from './somewhere'; @Injectable() export class MainService { constructor( private myService: MyService, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainService.ɵfac = function MainService_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory(); };`, ); }); it('should generate invalid factory for injectable when when token is a type', () => { env.write( 'test.ts', ` import {Injectable} from '@angular/core'; type MyService = {a:string}; @Injectable() export class MainService { constructor( private myService: MyService, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainService.ɵfac = function MainService_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory(); };`, ); }); it('should generate invalid factory for injectable when when token is an interface', () => { env.write( 'test.ts', ` import {Injectable} from '@angular/core'; interface MyService {a:string} @Injectable() export class MainService { constructor( private myService: MyService, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MainService.ɵfac = function MainService_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory(); };`, ); }); it('should generate invalid factory for directive without selector type parameter types are used as token', () => { env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive() export class MyDirective<S> { constructor( private myService: S, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MyDirective.ɵfac = function MyDirective_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory(); };`, ); }); it('should generate invalid factory for directive without selector when token is imported as type', () => { env.write( 'test.ts', ` import {Directive} from '@angular/core'; import {type MyService} from './somewhere'; @Directive() export class MyDirective { constructor( private myService: MyService, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MyDirective.ɵfac = function MyDirective_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory(); };`, ); }); it('should generate invalid factory for directive without selector when token is a type', () => { env.write( 'test.ts', `
{ "end_byte": 45786, "start_byte": 37184, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_45794_47172
t {Directive} from '@angular/core'; type MyService = {a:string}; @Directive() export class MyDirective { constructor( private myService: MyService, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MyDirective.ɵfac = function MyDirective_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory(); };`, ); }); it('should generate invalid factory for directive without selector when token is an interface', () => { env.write( 'test.ts', ` import {Directive} from '@angular/core'; interface MyService {a:string} @Directive() export class MyDirective { constructor( private myService: MyService, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `MyDirective.ɵfac = function MyDirective_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory(); };`, ); }); }); describe('LOCAL_COMPILATION_UNRESOLVED_CONST errors', () => { it('should show correct error message when using an external symbol for component template', () =
{ "end_byte": 47172, "start_byte": 45794, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_47178_56161
env.write( 'test.ts', ` import {Component} from '@angular/core'; import {ExternalString} from './some-where'; @Component({ template: ExternalString, }) export class Main { } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const {code, messageText, length, relatedInformation} = errors[0]; expect(code).toBe(ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST)); expect(length).toBe(14); expect(relatedInformation).toBeUndefined(); const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(text).toEqual( 'Unresolved identifier found for @Component.template field! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declaration into a file within the compilation unit, 2) Inline the template, 3) Move the template into a separate .html file and include it using @Component.templateUrl', ); }); it('should show correct error message when using an external symbol for component styles array', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; import {ExternalString} from './some-where'; const InternalStyle = "p{color:blue}"; @Component({ styles: [InternalStyle, ExternalString], template: '', }) export class Main { } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const {code, messageText, relatedInformation, length} = errors[0]; expect(code).toBe(ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST)); expect(length).toBe(14), expect(relatedInformation).toBeUndefined(); const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(text).toEqual( 'Unresolved identifier found for @Component.styles field! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declarations into a file within the compilation unit, 2) Inline the styles, 3) Move the styles into separate files and include it using @Component.styleUrls', ); }); it('should show correct error message when using an external symbol for component styles', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; import {ExternalString} from './some-where'; @Component({ styles: ExternalString, template: '', }) export class Main { } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const {code, messageText, relatedInformation, length} = errors[0]; expect(code).toBe(ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST)); expect(length).toBe(14), expect(relatedInformation).toBeUndefined(); const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(text).toEqual( 'Unresolved identifier found for @Component.styles field! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declarations into a file within the compilation unit, 2) Inline the styles, 3) Move the styles into separate files and include it using @Component.styleUrls', ); }); it('should show correct error message when using an external symbol for component selector', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; import {ExternalString} from './some-where'; @Component({ selector: ExternalString, template: '', }) export class Main { } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const {code, messageText, relatedInformation, length} = errors[0]; expect(code).toBe(ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST)); expect(length).toBe(14), expect(relatedInformation).toBeUndefined(); const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(text).toEqual( 'Unresolved identifier found for @Component.selector field! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declarations into a file within the compilation unit, 2) Inline the selector', ); }); it("should show correct error message when using an external symbol for component @HostListener's event name argument", () => { env.write( 'test.ts', ` import {Component, HostListener} from '@angular/core'; import {ExternalString} from './some-where'; @Component({ template: '', }) export class Main { @HostListener(ExternalString, ['$event']) handle() {} } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const {code, messageText, relatedInformation, length} = errors[0]; expect(code).toBe(ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST)); expect(length).toBe(14), expect(relatedInformation).toBeUndefined(); const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(text).toEqual( `Unresolved identifier found for @HostListener's event name argument! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declaration into a file within the compilation unit, 2) Inline the argument`, ); }); it("should show correct error message when using an external symbol for directive @HostListener's event name argument", () => { env.write( 'test.ts', ` import {Directive, HostListener} from '@angular/core'; import {ExternalString} from './some-where'; @Directive({selector: '[test]'}) export class Main { @HostListener(ExternalString, ['$event']) handle() {} } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const {code, messageText, relatedInformation, length} = errors[0]; expect(code).toBe(ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST)); expect(length).toBe(14), expect(relatedInformation).toBeUndefined(); const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(text).toEqual( `Unresolved identifier found for @HostListener's event name argument! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declaration into a file within the compilation unit, 2) Inline the argument`, ); }); it("should show correct error message when using an external symbol for component @HostBinding's argument", () => { env.write( 'test.ts', ` import {Component, HostBinding} from '@angular/core'; import {ExternalString} from './some-where'; @Component({template: ''}) export class Main { @HostBinding(ExternalString) id = 'some thing'; } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const {code, messageText, relatedInformation, length} = errors[0]; expect(code).toBe(ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST)); expect(length).toBe(14), expect(relatedInformation).toBeUndefined(); const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(text).toEqual( `Unresolved identifier found for @HostBinding's argument! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declaration into a file within the compilation unit, 2) Inline the argument`, ); }); it("should show correct error message when using an external symbol for directive @HostBinding's argument", () => { env.write( 'test.ts',
{ "end_byte": 56161, "start_byte": 47178, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_56169_60169
import {Directive, HostBinding} from '@angular/core'; import {ExternalString} from './some-where'; @Directive({selector: '[test]'}) export class Main { @HostBinding(ExternalString) id = 'some thing'; } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const {code, messageText, relatedInformation, length} = errors[0]; expect(code).toBe(ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST)); expect(length).toBe(14), expect(relatedInformation).toBeUndefined(); const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(text).toEqual( `Unresolved identifier found for @HostBinding's argument! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declaration into a file within the compilation unit, 2) Inline the argument`, ); }); it('should show correct error message when using an external symbol for @Directive.exportAs argument', () => { env.write( 'test.ts', ` import {Directive} from '@angular/core'; import {ExternalString} from './some-where'; @Directive({selector: '[test]', exportAs: ExternalString}) export class Main { } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const {code, messageText, relatedInformation, length} = errors[0]; expect(code).toBe(ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST)); expect(length).toBe(14), expect(relatedInformation).toBeUndefined(); const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(text).toEqual( `Unresolved identifier found for exportAs field! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declarations into a file within the compilation unit, 2) Inline the selector`, ); }); }); describe('ng module bootstrap def', () => { it('should include the bootstrap definition in ɵɵsetNgModuleScope instead of ɵɵdefineNgModule', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {App} from './some-where'; @NgModule({ declarations: [App], bootstrap: [App], }) export class AppModule { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'AppModule.ɵmod = /*@__PURE__*/ i0.ɵɵdefineNgModule({ type: AppModule });', ); expect(jsContents).toContain( 'ɵɵsetNgModuleScope(AppModule, { declarations: [App], bootstrap: [App] }); })();', ); }); it('should include no bootstrap definition in ɵɵsetNgModuleScope if the NgModule has no bootstrap field', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {App} from './some-where'; @NgModule({ declarations: [App], }) export class AppModule { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'AppModule.ɵmod = /*@__PURE__*/ i0.ɵɵdefineNgModule({ type: AppModule });', ); expect(jsContents).toContain( 'ɵɵsetNgModuleScope(AppModule, { declarations: [App] }); })();', ); }); }); describe('host directives', () => { it('should generate component hostDirectives definition without input and output', () => { env.write( 'test.ts',
{ "end_byte": 60169, "start_byte": 56169, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_60175_66541
import {Directive, Component} from '@angular/core'; import {ExternalDirective} from 'some_where'; import * as n from 'some_where2'; @Directive({standalone: true}) export class LocalDirective { } @Component({ selector: 'my-comp', template: '', hostDirectives: [ExternalDirective, n.ExternalDirective, LocalDirective], standalone: false, }) export class MyComp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature([ExternalDirective, n.ExternalDirective, LocalDirective])]', ); }); it('should generate component hostDirectives definition for externally imported directives with input and output', () => { env.write( 'test.ts', ` import {Directive, Component} from '@angular/core'; import {HostDir} from 'some_where'; @Component({ selector: 'my-comp', template: '', hostDirectives: [{ directive: HostDir, inputs: ['value', 'color: colorAlias'], outputs: ['opened', 'closed: closedAlias'], }], standalone: false, }) export class MyComp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature([{ directive: HostDir, ' + 'inputs: ["value", "value", "color", "colorAlias"], ' + 'outputs: ["opened", "opened", "closed", "closedAlias"] }])]', ); }); it('should generate component hostDirectives definition for local directives with input and output', () => { env.write( 'test.ts', ` import {Directive, Component} from '@angular/core'; @Directive({ standalone: true }) export class LocalDirective { } @Component({ selector: 'my-comp', template: '', hostDirectives: [{ directive: LocalDirective, inputs: ['value', 'color: colorAlias'], outputs: ['opened', 'closed: closedAlias'], }], standalone: false, }) export class MyComp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature([{ directive: LocalDirective, ' + 'inputs: ["value", "value", "color", "colorAlias"], ' + 'outputs: ["opened", "opened", "closed", "closedAlias"] }])]', ); }); it('should generate directive hostDirectives definitions', () => { env.write( 'test.ts', ` import {Directive, Component} from '@angular/core'; import {ExternalDirective} from 'some_where'; @Directive({ standalone: true, hostDirectives: [ExternalDirective], }) export class LocalDirective { } @Directive({ standalone: true, hostDirectives: [LocalDirective], }) export class LocalDirective2 { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'ɵɵdefineDirective({ type: LocalDirective, ' + 'features: [i0.ɵɵHostDirectivesFeature([ExternalDirective])] });', ); expect(jsContents).toContain( 'ɵɵdefineDirective({ type: LocalDirective2, ' + 'features: [i0.ɵɵHostDirectivesFeature([LocalDirective])] });', ); }); it('should generate hostDirectives definition with forward references of local directives', () => { env.write( 'test.ts', ` import {Component, Directive, forwardRef, Input} from '@angular/core'; @Component({ selector: 'my-component', template: '', hostDirectives: [forwardRef(() => DirectiveB)], standalone: false, }) export class MyComponent { } @Directive({ standalone: true, hostDirectives: [{directive: forwardRef(() => DirectiveA), inputs: ['value']}], }) export class DirectiveB { } @Directive({standalone: true}) export class DirectiveA { @Input() value: any; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature(function () { return [DirectiveB]; })]', ); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature(function () { return [{ directive: DirectiveA, inputs: ["value", "value"] }]; })]', ); }); it('should produce fatal diagnostics for host directives with forward references of externally imported directive', () => { env.write( 'test.ts', ` import {Component, Directive, forwardRef} from '@angular/core'; import {ExternalDirective} from 'some_where'; @Component({ selector: 'my-component', template: '', hostDirectives: [forwardRef(() => ExternalDirective)] //hostDirectives: [ExternalDirective] }) export class MyComponent { } `, ); const messages = env.driveDiagnostics(); expect(messages[0].code).toBe( ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNSUPPORTED_EXPRESSION), ); expect(messages[0].messageText).toEqual( 'In local compilation mode, host directive cannot be an expression. Use an identifier instead', ); }); }); describe('input transform', () => { it('should generate input info for transform function imported externally using name', () => { env.write( 'test.ts', ` im
{ "end_byte": 66541, "start_byte": 60175, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_66547_69739
Component, NgModule, Input} from '@angular/core'; import {externalFunc} from './some_where'; @Component({ template: '<span>{{x}}</span>', }) export class Main { @Input({transform: externalFunc}) x: string = ''; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('inputs: { x: [2, "x", "x", externalFunc] }'); }); it('should generate input info for transform function imported externally using namespace', () => { env.write( 'test.ts', ` import {Component, NgModule, Input} from '@angular/core'; import * as n from './some_where'; @Component({ template: '<span>{{x}}</span>', }) export class Main { @Input({transform: n.externalFunc}) x: string = ''; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('inputs: { x: [2, "x", "x", n.externalFunc] }'); }); it('should generate input info for transform function defined locally', () => { env.write( 'test.ts', ` import {Component, NgModule, Input} from '@angular/core'; @Component({ template: '<span>{{x}}</span>', }) export class Main { @Input({transform: localFunc}) x: string = ''; } function localFunc(value: string) { return value; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('inputs: { x: [2, "x", "x", localFunc] }'); }); it('should generate input info for inline transform function', () => { env.write( 'test.ts', ` import {Component, NgModule, Input} from '@angular/core'; @Component({ template: '<span>{{x}}</span>', }) export class Main { @Input({transform: (v: string) => v + 'TRANSFORMED!'}) x: string = ''; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('inputs: { x: [2, "x", "x", (v) => v + \'TRANSFORMED!\'] }'); }); it('should not check inline function param type', () => { env.write( 'test.ts', ` import {Component, NgModule, Input} from '@angular/core'; @Component({ template: '<span>{{x}}</span>', }) export class Main { @Input({transform: v => v + 'TRANSFORMED!'}) x: string = ''; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('inputs: { x: [2, "x", "x", v => v + \'TRANSFORMED!\'] }'); }); }); describe('@defer', () => { beforeEach(() => { tsconfig({onlyExplicitDeferDependencyImports: true}); }); it('should handle `@Component.deferredImports` field', () => {
{ "end_byte": 69739, "start_byte": 66547, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_69745_77696
.write( 'deferred-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-a', template: 'DeferredCmpA contents', }) export class DeferredCmpA { } `, ); env.write( 'deferred-b.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-b', template: 'DeferredCmpB contents', }) export class DeferredCmpB { } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {DeferredCmpA} from './deferred-a'; import {DeferredCmpB} from './deferred-b'; @Component({ standalone: true, deferredImports: [DeferredCmpA, DeferredCmpB], template: \` @defer { <deferred-cmp-a /> } @defer { <deferred-cmp-b /> } \`, }) export class AppCmp { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Expect that all deferrableImports in local compilation mode // are located in a single function (since we can't detect in // the local mode which components belong to which block). expect(jsContents).toContain( 'const AppCmp_DeferFn = () => [' + 'import("./deferred-a").then(m => m.DeferredCmpA), ' + 'import("./deferred-b").then(m => m.DeferredCmpB)];', ); // Make sure there are no eager imports present in the output. expect(jsContents).not.toContain(`from './deferred-a'`); expect(jsContents).not.toContain(`from './deferred-b'`); // All defer instructions use the same dependency function. expect(jsContents).toContain('ɵɵdefer(1, 0, AppCmp_DeferFn);'); expect(jsContents).toContain('ɵɵdefer(4, 3, AppCmp_DeferFn);'); // Expect `ɵsetClassMetadataAsync` to contain dynamic imports too. expect(jsContents).toContain( 'ɵsetClassMetadataAsync(AppCmp, () => [' + 'import("./deferred-a").then(m => m.DeferredCmpA), ' + 'import("./deferred-b").then(m => m.DeferredCmpB)], ' + '(DeferredCmpA, DeferredCmpB) => {', ); }); it('should handle `@Component.imports` field', () => { env.write( 'deferred-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-a', template: 'DeferredCmpA contents', }) export class DeferredCmpA { } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {DeferredCmpA} from './deferred-a'; @Component({ standalone: true, imports: [DeferredCmpA], template: \` @defer { <deferred-cmp-a /> } \`, }) export class AppCmp { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // In local compilation mode we can't detect which components // belong to `@defer` blocks, thus can't determine whether corresponding // classes can be defer-loaded. In this case we retain eager imports // and do not generate defer dependency functions for `@defer` instructions. // Eager imports are retained in the output. expect(jsContents).toContain(`from './deferred-a'`); // Defer instructions do not have a dependency function, // since all dependencies were defined in `@Component.imports`. expect(jsContents).toContain('ɵɵdefer(1, 0);'); // Expect `ɵsetClassMetadata` (sync) to be generated. expect(jsContents).toContain('ɵsetClassMetadata(AppCmp,'); }); it('should handle defer blocks that rely on deps from `deferredImports` and `imports`', () => { env.write( 'eager-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'eager-cmp-a', template: 'EagerCmpA contents', }) export class EagerCmpA { } `, ); env.write( 'deferred-a.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-a', template: 'DeferredCmpA contents', }) export class DeferredCmpA { } `, ); env.write( 'deferred-b.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-b', template: 'DeferredCmpB contents', }) export class DeferredCmpB { } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {DeferredCmpA} from './deferred-a'; import {DeferredCmpB} from './deferred-b'; import {EagerCmpA} from './eager-a'; @Component({ standalone: true, imports: [EagerCmpA], deferredImports: [DeferredCmpA, DeferredCmpB], template: \` @defer { <eager-cmp-a /> <deferred-cmp-a /> } @defer { <eager-cmp-a /> <deferred-cmp-b /> } \`, }) export class AppCmp { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Expect that all deferrableImports in local compilation mode // are located in a single function (since we can't detect in // the local mode which components belong to which block). // Eager dependencies are **not* included here. expect(jsContents).toContain( 'const AppCmp_DeferFn = () => [' + 'import("./deferred-a").then(m => m.DeferredCmpA), ' + 'import("./deferred-b").then(m => m.DeferredCmpB)];', ); // Make sure there are no eager imports present in the output. expect(jsContents).not.toContain(`from './deferred-a'`); expect(jsContents).not.toContain(`from './deferred-b'`); // Eager dependencies retain their imports. expect(jsContents).toContain(`from './eager-a';`); // All defer instructions use the same dependency function. expect(jsContents).toContain('ɵɵdefer(1, 0, AppCmp_DeferFn);'); expect(jsContents).toContain('ɵɵdefer(4, 3, AppCmp_DeferFn);'); // Expect `ɵsetClassMetadataAsync` to contain dynamic imports too. expect(jsContents).toContain( 'ɵsetClassMetadataAsync(AppCmp, () => [' + 'import("./deferred-a").then(m => m.DeferredCmpA), ' + 'import("./deferred-b").then(m => m.DeferredCmpB)], ' + '(DeferredCmpA, DeferredCmpB) => {', ); }); it( 'should support importing multiple deferrable deps from a single file ' + 'and use them within `@Component.deferrableImports` field', () => { env.write( 'deferre
{ "end_byte": 77696, "start_byte": 69745, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts_77704_86695
s', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-a', template: 'DeferredCmpA contents', }) export class DeferredCmpA { } @Component({ standalone: true, selector: 'deferred-cmp-b', template: 'DeferredCmpB contents', }) export class DeferredCmpB { } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; // This import brings multiple symbols, but all of them are // used within @Component.deferredImports, thus this import // can be removed in favor of dynamic imports. import {DeferredCmpA, DeferredCmpB} from './deferred-deps'; @Component({ standalone: true, deferredImports: [DeferredCmpA], template: \` @defer { <deferred-cmp-a /> } \`, }) export class AppCmpA {} @Component({ standalone: true, deferredImports: [DeferredCmpB], template: \` @defer { <deferred-cmp-b /> } \`, }) export class AppCmpB {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Expect that we generate 2 different defer functions // (one for each component). expect(jsContents).toContain( 'const AppCmpA_DeferFn = () => [' + 'import("./deferred-deps").then(m => m.DeferredCmpA)]', ); expect(jsContents).toContain( 'const AppCmpB_DeferFn = () => [' + 'import("./deferred-deps").then(m => m.DeferredCmpB)]', ); // Make sure there are no eager imports present in the output. expect(jsContents).not.toContain(`from './deferred-deps'`); // Defer instructions use per-component dependency function. expect(jsContents).toContain('ɵɵdefer(1, 0, AppCmpA_DeferFn)'); expect(jsContents).toContain('ɵɵdefer(1, 0, AppCmpB_DeferFn)'); // Expect `ɵsetClassMetadataAsync` to contain dynamic imports too. expect(jsContents).toContain( 'ɵsetClassMetadataAsync(AppCmpA, () => [' + 'import("./deferred-deps").then(m => m.DeferredCmpA)]', ); expect(jsContents).toContain( 'ɵsetClassMetadataAsync(AppCmpB, () => [' + 'import("./deferred-deps").then(m => m.DeferredCmpB)]', ); }, ); it( 'should produce a diagnostic in case imports with symbols used ' + 'in `deferredImports` can not be removed', () => { env.write( 'deferred-deps.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'deferred-cmp-a', template: 'DeferredCmpA contents', }) export class DeferredCmpA { } @Component({ standalone: true, selector: 'deferred-cmp-b', template: 'DeferredCmpB contents', }) export class DeferredCmpB { } export function utilityFn() {} `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; // This import can not be removed, since it'd contain // 'utilityFn' symbol once we remove 'DeferredCmpA' and // 'DeferredCmpB' and generate a dynamic import for it. // In this situation compiler produces a diagnostic to // indicate that. import {DeferredCmpA, DeferredCmpB, utilityFn} from './deferred-deps'; @Component({ standalone: true, deferredImports: [DeferredCmpA], template: \` @defer { <deferred-cmp-a /> } \`, }) export class AppCmpA { ngOnInit() { utilityFn(); } } @Component({ standalone: true, deferredImports: [DeferredCmpB], template: \` @defer { <deferred-cmp-b /> } \`, }) export class AppCmpB {} @Component({ standalone: true, template: 'Component without any dependencies' }) export class ComponentWithoutDeps {} `, ); const diags = env.driveDiagnostics(); // Expect 2 diagnostics: one for each component `AppCmpA` and `AppCmpB`, // since both of them refer to symbols from an import declaration that // can not be removed. expect(diags.length).toBe(2); for (let i = 0; i < 2; i++) { const {code, messageText} = diags[i]; expect(code).toBe(ngErrorCode(ErrorCode.DEFERRED_DEPENDENCY_IMPORTED_EAGERLY)); expect(messageText).toContain( 'This import contains symbols that are used both inside and outside ' + 'of the `@Component.deferredImports` fields in the file.', ); } }, ); }); describe('custom decorator', () => { it('should produce diagnostic for each custom decorator', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; import {customDecorator1, customDecorator2} from './some-where'; @customDecorator1('hello') @Component({ template: ExternalString, }) @customDecorator2 export class Main { } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(2); const text1 = ts.flattenDiagnosticMessageText(errors[0].messageText, '\n'); const text2 = ts.flattenDiagnosticMessageText(errors[1].messageText, '\n'); expect(errors[0].code).toBe(ngErrorCode(ErrorCode.DECORATOR_UNEXPECTED)); expect(errors[1].code).toBe(ngErrorCode(ErrorCode.DECORATOR_UNEXPECTED)); expect(text1).toContain( 'In local compilation mode, Angular does not support custom decorators', ); expect(text2).toContain( 'In local compilation mode, Angular does not support custom decorators', ); }); }); describe('template diagnostics', () => { it('should show correct error message for syntatic template errors - case of inline template', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '<span Hello! </span>', }) export class Main { } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBeGreaterThanOrEqual(1); const {code, messageText} = errors[0]; expect(code).toBe(ngErrorCode(ErrorCode.TEMPLATE_PARSE_ERROR)); const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(text).toContain('Opening tag "span" not terminated'); }); it('should show correct error message for syntatic template errors - case of external template', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: 'test.ng.html', }) export class Main { } `, ); env.write( 'test.ng.html', ` <span Hello! </span> `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBeGreaterThanOrEqual(1); const {code, messageText} = errors[0]; expect(code).toBe(ngErrorCode(ErrorCode.TEMPLATE_PARSE_ERROR)); const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(text).toContain('Opening tag "span" not terminated'); }); }); }); });
{ "end_byte": 86695, "start_byte": 77704, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/local_compilation_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/component_indexing_spec.ts_0_6656
/** * @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 { AbsoluteFsPath, getFileSystem, PathManipulation, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import { AbsoluteSourceSpan, IdentifierKind, IndexedComponent, TopLevelIdentifier, } from '@angular/compiler-cli/src/ngtsc/indexer'; import {ParseSourceFile} from '@angular/compiler/src/compiler'; import {NgtscTestEnvironment} from './env'; runInEachFileSystem(() => { describe('ngtsc component indexing', () => { let fs: PathManipulation; let env!: NgtscTestEnvironment; let testSourceFile: AbsoluteFsPath; let testTemplateFile: AbsoluteFsPath; beforeEach(() => { env = NgtscTestEnvironment.setup(); env.tsconfig(); fs = getFileSystem(); testSourceFile = fs.resolve(env.basePath, 'test.ts'); testTemplateFile = fs.resolve(env.basePath, 'test.html'); }); describe('indexing metadata', () => { it('should generate component metadata', () => { const componentContent = ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div></div>', }) export class TestCmp {} `; env.write(testSourceFile, componentContent); const indexed = env.driveIndexer(); expect(indexed.size).toBe(1); const [[decl, indexedComp]] = Array.from(indexed.entries()); expect(decl.getText()).toContain('export class TestCmp {}'); expect(indexedComp).toEqual( jasmine.objectContaining<IndexedComponent>({ name: 'TestCmp', selector: 'test-cmp', file: new ParseSourceFile(componentContent, testSourceFile), }), ); }); it('should index inline templates', () => { const componentContent = ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '{{foo}}', }) export class TestCmp { foo = 0; } `; env.write(testSourceFile, componentContent); const indexed = env.driveIndexer(); const [[_, indexedComp]] = Array.from(indexed.entries()); const template = indexedComp.template; expect(template).toEqual({ identifiers: new Set<TopLevelIdentifier>([ { name: 'foo', kind: IdentifierKind.Property, span: new AbsoluteSourceSpan(127, 130), target: null, }, ]), usedComponents: new Set(), isInline: true, file: new ParseSourceFile(componentContent, testSourceFile), }); }); it('should index external templates', () => { env.write( testSourceFile, ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', templateUrl: './test.html', }) export class TestCmp { foo = 0; } `, ); env.write(testTemplateFile, '{{foo}}'); const indexed = env.driveIndexer(); const [[_, indexedComp]] = Array.from(indexed.entries()); const template = indexedComp.template; expect(template).toEqual({ identifiers: new Set<TopLevelIdentifier>([ { name: 'foo', kind: IdentifierKind.Property, span: new AbsoluteSourceSpan(2, 5), target: null, }, ]), usedComponents: new Set(), isInline: false, file: new ParseSourceFile('{{foo}}', testTemplateFile), }); }); it('should index templates compiled without preserving whitespace', () => { env.tsconfig({ preserveWhitespaces: false, }); env.write( testSourceFile, ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', templateUrl: './test.html', }) export class TestCmp { foo = 0; } `, ); env.write(testTemplateFile, ' \n {{foo}}'); const indexed = env.driveIndexer(); const [[_, indexedComp]] = Array.from(indexed.entries()); const template = indexedComp.template; expect(template).toEqual({ identifiers: new Set<TopLevelIdentifier>([ { name: 'foo', kind: IdentifierKind.Property, span: new AbsoluteSourceSpan(7, 10), target: null, }, ]), usedComponents: new Set(), isInline: false, file: new ParseSourceFile(' \n {{foo}}', testTemplateFile), }); }); it('should generate information about used components', () => { env.write( testSourceFile, ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', templateUrl: './test.html', standalone: false, }) export class TestCmp {} `, ); env.write(testTemplateFile, '<div></div>'); env.write( 'test_import.ts', ` import {Component, NgModule} from '@angular/core'; import {TestCmp} from './test'; @Component({ templateUrl: './test_import.html', standalone: false, }) export class TestImportCmp {} @NgModule({ declarations: [ TestCmp, TestImportCmp, ], bootstrap: [TestImportCmp] }) export class TestModule {} `, ); env.write('test_import.html', '<test-cmp></test-cmp>'); const indexed = env.driveIndexer(); expect(indexed.size).toBe(2); const indexedComps = Array.from(indexed.values()); const testComp = indexedComps.find((comp) => comp.name === 'TestCmp'); const testImportComp = indexedComps.find((cmp) => cmp.name === 'TestImportCmp'); expect(testComp).toBeDefined(); expect(testImportComp).toBeDefined(); expect(testComp!.template.usedComponents.size).toBe(0); expect(testImportComp!.template.usedComponents.size).toBe(1); const [usedComp] = Array.from(testImportComp!.template.usedComponents); expect(indexed.get(usedComp)).toEqual(testComp); }); }); }); });
{ "end_byte": 6656, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/component_indexing_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/authoring_models_spec.ts_0_7906
/** * @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 ts from 'typescript'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('initializer-based model() API', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({strictTemplates: true}); }); it('should declare an input/output pair for a field initialized to a model()', () => { env.write( 'test.ts', ` import {Directive, model} from '@angular/core'; @Directive() export class TestDir { value = model(1); } `, ); env.driveMain(); const js = env.getContents('test.js'); const dts = env.getContents('test.d.ts'); expect(js).toContain('inputs: { value: [1, "value"] }'); expect(js).toContain('outputs: { value: "valueChange" }'); expect(dts).toContain( 'static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, never, never, ' + '{ "value": { "alias": "value"; "required": false; "isSignal": true; }; }, ' + '{ "value": "valueChange"; }, never, never, true, never>;', ); }); it('should declare an input/output pair for a field initialized to an aliased model()', () => { env.write( 'test.ts', ` import {Directive, model} from '@angular/core'; @Directive() export class TestDir { value = model(1, {alias: 'alias'}); } `, ); env.driveMain(); const js = env.getContents('test.js'); const dts = env.getContents('test.d.ts'); expect(js).toContain('inputs: { value: [1, "alias", "value"] }'); expect(js).toContain('outputs: { value: "aliasChange" }'); expect(dts).toContain( 'static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, never, never, ' + '{ "value": { "alias": "alias"; "required": false; "isSignal": true; }; }, ' + '{ "value": "aliasChange"; }, never, never, true, never>;', ); }); it('should declare an input/output pair for a field initialized to a required model()', () => { env.write( 'test.ts', ` import {Directive, model} from '@angular/core'; @Directive() export class TestDir { value = model.required<string>(); } `, ); env.driveMain(); const js = env.getContents('test.js'); const dts = env.getContents('test.d.ts'); expect(js).toContain('inputs: { value: [1, "value"] }'); expect(js).toContain('outputs: { value: "valueChange" }'); expect(dts).toContain( 'static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, never, never, ' + '{ "value": { "alias": "value"; "required": true; "isSignal": true; }; }, ' + '{ "value": "valueChange"; }, never, never, true, never>;', ); }); it('should report a diagnostic if a model field is decorated with @Input', () => { env.write( 'test.ts', ` import {Directive, Input, model} from '@angular/core'; @Directive() export class TestDir { @Input() value = model('test'); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe('Using @Input with a model input is not allowed.'); }); it('should report a diagnostic if a model field is decorated with @Output', () => { env.write( 'test.ts', ` import {Directive, Output, model} from '@angular/core'; @Directive() export class TestDir { @Output() value = model('test'); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe('Using @Output with a model input is not allowed.'); }); it('should report a diagnostic if a model input is also declared in the `inputs` field', () => { env.write( 'test.ts', ` import {Directive, model} from '@angular/core'; @Directive({ inputs: ['value'], }) export class TestDir { value = model('test'); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( 'Input "value" is also declared as non-signal in @Directive.', ); }); it('should produce a diagnostic if the alias of a model cannot be analyzed', () => { env.write( 'test.ts', ` import {Directive, model} from '@angular/core'; const ALIAS = 'bla'; @Directive() export class TestDir { value = model('test', {alias: ALIAS}); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( 'Alias needs to be a string that is statically analyzable.', ); }); it('should report a diagnostic if the options of a model signal cannot be analyzed', () => { env.write( 'test.ts', ` import {Directive, model} from '@angular/core'; const OPTIONS = {}; @Directive() export class TestDir { value = model('test', OPTIONS); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( 'Argument needs to be an object literal that is statically analyzable.', ); }); it('should report a diagnostic if a model input is declared on a static member', () => { env.write( 'test.ts', ` import {Directive, model} from '@angular/core'; @Directive() export class TestDir { static value = model('test'); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( 'Input "value" is incorrectly declared as static member of "TestDir".', ); }); it('should a diagnostic if a required model input declares an initial value', () => { env.write( 'test.ts', ` import {Directive, model} from '@angular/core'; @Directive() export class TestDir { value = model.required({ initialValue: 'bla', }); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Object literal may only specify known properties, ` + `and 'initialValue' does not exist in type 'ModelOptions'.`, ); }); it('should report if a signal getter is invoked in a two-way binding', () => { env.write( 'test.ts', ` import {Component, Directive, model, signal} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir { value = model(1); } @Component({ standalone: true, template: \`<div dir [(value)]="value()"></div>\`, imports: [TestDir], }) export class TestComp { value = signal(0); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe('Unsupported expression in a two-way binding'); }); des
{ "end_byte": 7906, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/authoring_models_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/authoring_models_spec.ts_7912_16744
'type checking', () => { it('should check a primitive value bound to a model input', () => { env.write( 'test.ts', ` import {Component, Directive, model} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir { value = model(1); } @Component({ standalone: true, template: \`<div dir [(value)]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = false; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Type 'boolean' is not assignable to type 'number'.`); }); it('should check a signal value bound to a model input via a two-way binding', () => { env.write( 'test.ts', ` import {Component, Directive, model, signal} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir { value = model(1); } @Component({ standalone: true, template: \`<div dir [(value)]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = signal(false); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Type 'boolean' is not assignable to type 'number'.`); }); it('should check two-way binding of a signal to a decorator-based input/output pair', () => { env.write( 'test.ts', ` import {Component, Directive, Input, Output, signal, EventEmitter} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir { @Input() value = 0; @Output() valueChange = new EventEmitter<number>(); } @Component({ standalone: true, template: \`<div dir [(value)]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = signal(false); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Type 'boolean' is not assignable to type 'number'.`); }); it('should not allow a non-writable signal to be assigned to a model', () => { env.write( 'test.ts', ` import {Component, Directive, model, input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir { value = model(1); } @Component({ standalone: true, template: \`<div dir [(value)]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = input(0); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Type 'InputSignal<number>' is not assignable to type 'number'.`, ); }); it('should allow a model signal to be bound to another model signal', () => { env.write( 'test.ts', ` import {Component, Directive, model} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir { value = model(1); } @Component({ standalone: true, template: \`<div dir [(value)]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = model(0); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should check the event declared by a model input', () => { env.write( 'test.ts', ` import {Component, Directive, model} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir { value = model(1); } @Component({ standalone: true, template: \`<div dir (valueChange)="acceptsString($event)"></div>\`, imports: [TestDir], }) export class TestComp { acceptsString(value: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); }); it('should report unset required model inputs', () => { env.write( 'test.ts', ` import {Component, Directive, model} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir { value = model.required<number>(); } @Component({ standalone: true, template: \`<div dir></div>\`, imports: [TestDir], }) export class TestComp { } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics[0].messageText).toBe( `Required input 'value' from directive TestDir must be specified.`, ); }); it('should check generic two-way model binding with a primitive value', () => { env.write( 'test.ts', ` import {Component, Directive, model} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir<T extends {id: string}> { value = model.required<T>(); } @Component({ standalone: true, template: \`<div dir [(value)]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = {id: 1}; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( jasmine.objectContaining({ messageText: `Type '{ id: number; }' is not assignable to type '{ id: string; }'.`, }), ); }); it('should check generic two-way model binding with a signal value', () => { env.write( 'test.ts', ` import {Component, Directive, model, signal} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir<T extends {id: string}> { value = model.required<T>(); } @Component({ standalone: true, template: \`<div dir [(value)]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = signal({id: 1}); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( jasmine.objectContaining({ messageText: `Type '{ id: number; }' is not assignable to type '{ id: string; }'.`, }), ); }); it('should report unwrapped signals assigned to a model in a one-way binding', () => { env.write( 'test.ts', ` import {Component, Directive, model, signal} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir { value = model(0); } @Component({ standalone: true, template: \`<div dir [value]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = signal(1); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics[0].messageText).toBe( `Type 'WritableSignal<number>' is not assignable to type 'number'.`, ); }); }); it(
{ "end_byte": 16744, "start_byte": 7912, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/authoring_models_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/authoring_models_spec.ts_16750_21749
d allow two-way binding to a generic model input', () => { env.write( 'test.ts', ` import {Component, Directive, model, signal} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir<T> { value = model.required<T>(); } @Component({ standalone: true, template: \`<div dir [(value)]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = signal(1); } `, ); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); }); // TODO(atscott): fix this test which was broken by #54711 xit('should not widen the type of two-way bindings on Angular versions less than 17.2', () => { env.tsconfig({_angularCoreVersion: '16.50.60', strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter, signal} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir { @Input() value = 0; @Output() valueChange = new EventEmitter<number>(); } @Component({ standalone: true, template: \`<div dir [(value)]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = signal(1); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Type 'WritableSignal<number>' is not assignable to type 'number'.`, ); }); it('should widen the type of two-way bindings on supported Angular versions', () => { ['17.2.0', '17.2.0-rc.0', '0.0.0-PLACEHOLDER', '18.0.0'].forEach((version) => { env.tsconfig({_angularCoreVersion: version, strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter, signal} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir { @Input() value = 0; @Output() valueChange = new EventEmitter<number>(); } @Component({ standalone: true, template: \`<div dir [(value)]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = signal(1); } `, ); const diags = env.driveDiagnostics(); expect(diags).withContext(`On version ${version}`).toEqual([]); }); }); describe('diagnostics', () => { it('should error when declared using an ES private field', () => { env.write( 'test.ts', ` import {Directive, model} from '@angular/core'; @Directive({ selector: '[directiveName]', standalone: true, }) export class TestDir { #data = model.required<boolean>(); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining<ts.Diagnostic>({ messageText: jasmine.objectContaining<ts.DiagnosticMessageChain>({ messageText: `Cannot use "model" on a class member that is declared as ES private.`, }), }), ]); }); it('should error when declared using a `private` field', () => { env.write( 'test.ts', ` import {Directive, model} from '@angular/core'; @Directive({ selector: '[directiveName]', standalone: true, }) export class TestDir { private data = model.required<boolean>(); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining<ts.Diagnostic>({ messageText: jasmine.objectContaining<ts.DiagnosticMessageChain>({ messageText: `Cannot use "model" on a class member that is declared as private.`, }), }), ]); }); it('should allow using a `protected` field', () => { env.write( 'test.ts', ` import {Directive, model} from '@angular/core'; @Directive({ selector: '[directiveName]', standalone: true, }) export class TestDir { protected data = model.required<boolean>(); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(0); }); }); }); });
{ "end_byte": 21749, "start_byte": 16750, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/authoring_models_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/monorepo_spec.ts_0_3492
/** * @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 {absoluteFrom} from '../../src/ngtsc/file_system'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('monorepos', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles, absoluteFrom('/app')); env.tsconfig(); // env.tsconfig() will write to /app/tsconfig.json, but list it as extending // ./tsconfig-base.json. So that file should exist, and redirect to ../tsconfig-base.json. env.write('/app/tsconfig-base.json', JSON.stringify({'extends': '../tsconfig-base.json'})); }); it('should compile a project with a reference above the current dir', () => { env.write( '/app/index.ts', ` import {Component, NgModule} from '@angular/core'; import {LibModule} from '../lib/module'; @Component({ selector: 'app-cmp', template: '<lib-cmp></lib-cmp>', standalone: false, }) export class AppCmp {} @NgModule({ declarations: [AppCmp], imports: [LibModule], }) export class AppModule {} `, ); env.write( '/lib/module.ts', ` import {NgModule} from '@angular/core'; import {LibCmp} from './cmp'; @NgModule({ declarations: [LibCmp], exports: [LibCmp], }) export class LibModule {} `, ); env.write( '/lib/cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'lib-cmp', template: '...', standalone: false, }) export class LibCmp {} `, ); env.driveMain(); const jsContents = env.getContents('app/index.js'); expect(jsContents).toContain(`import * as i1 from "../lib/cmp";`); }); it('should compile a project with a reference into the same dir', () => { env.write( '/app/index.ts', ` import {Component, NgModule} from '@angular/core'; import {TargetModule} from './target'; @Component({ selector: 'app-cmp', template: '<target-cmp></target-cmp>', standalone: false, }) export class AppCmp {} @NgModule({ declarations: [AppCmp], imports: [TargetModule], }) export class AppModule {} `, ); env.write( '/app/target.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'target-cmp', template: '...', standalone: false, }) export class TargetCmp {} @NgModule({ declarations: [TargetCmp], exports: [TargetCmp], }) export class TargetModule {} `, ); env.driveMain(); const jsContents = env.getContents('app/index.js'); // Check that the relative import has the leading './'. expect(jsContents).toContain(`import * as i1 from "./target";`); }); }); });
{ "end_byte": 3492, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/monorepo_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_0_871
/** * @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 ts from 'typescript'; import {DiagnosticCategoryLabel} from '../../src/ngtsc/core/api'; import {ErrorCode, ngErrorCode} from '../../src/ngtsc/diagnostics'; import {absoluteFrom as _, getSourceFileOrError} from '../../src/ngtsc/file_system'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import { expectCompleteReuse, getSourceCodeForDiagnostic, loadStandardTestFiles, } from '../../src/ngtsc/testing'; import {factory as invalidBananaInBoxFactory} from '../../src/ngtsc/typecheck/extended/checks/invalid_banana_in_box'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles({fakeCommon: true});
{ "end_byte": 871, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_873_9233
runInEachFileSystem(() => { describe('ngtsc type checking', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({fullTemplateTypeCheck: true}); env.write( 'node_modules/@angular/animations/index.d.ts', ` export declare class AnimationEvent { element: any; } `, ); }); it('should check a simple component', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: 'I am a simple template with no type info', standalone: false, }) class TestCmp {} @NgModule({ declarations: [TestCmp], }) class Module {} `, ); env.driveMain(); }); it('should have accurate diagnostics in a template using crlf line endings', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', templateUrl: './test.html', standalone: false, }) class TestCmp {} `, ); env.write('test.html', '<span>\r\n{{does_not_exist}}\r\n</span>'); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getSourceCodeForDiagnostic(diags[0])).toBe('does_not_exist'); }); it('should not fail with a runtime error when generating TCB', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, input} from '@angular/core'; @Component({ selector: 'sub-cmp', standalone: true, template: '', }) class Sub { // intentionally not exported someInput = input.required<string>(); } @Component({ template: \`<sub-cmp [someInput]="''" />\`, standalone: true, imports: [Sub], }) export class MyComponent {} `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: jasmine.objectContaining({messageText: 'Unable to import symbol Sub.'}), }), ]); }); it('should check regular attributes that are directive inputs', () => { env.tsconfig({ fullTemplateTypeCheck: true, strictInputTypes: true, strictAttributeTypes: true, }); env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Component({ selector: 'test', template: '<div dir foo="2"></div>', standalone: false, }) class TestCmp {} @Directive({ selector: '[dir]', standalone: false, }) class TestDir { @Input() foo: number; } @NgModule({ declarations: [TestCmp, TestDir], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual(`Type 'string' is not assignable to type 'number'.`); // The reported error code should be in the TS error space, not a -99 "NG" code. expect(diags[0].code).toBeGreaterThan(0); }); it('should produce diagnostics when mapping to multiple fields and bound types are incorrect', () => { env.tsconfig({ fullTemplateTypeCheck: true, strictInputTypes: true, strictAttributeTypes: true, }); env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Component({ selector: 'test', template: '<div dir foo="2"></div>', standalone: false, }) class TestCmp {} @Directive({ selector: '[dir]', standalone: false, }) class TestDir { @Input('foo') foo1: number; @Input('foo') foo2: number; } @NgModule({ declarations: [TestCmp, TestDir], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual(`Type 'string' is not assignable to type 'number'.`); expect(diags[1].messageText).toEqual(`Type 'string' is not assignable to type 'number'.`); }); it('should support inputs and outputs with names that are not JavaScript identifiers', () => { env.tsconfig({ fullTemplateTypeCheck: true, strictInputTypes: true, strictOutputEventTypes: true, }); env.write( 'test.ts', ` import {Component, Directive, NgModule, EventEmitter} from '@angular/core'; @Component({ selector: 'test', template: '<div dir [some-input.xs]="2" (some-output)="handleEvent($event)"></div>', standalone: false, }) class TestCmp { handleEvent(event: number): void {} } @Directive({ selector: '[dir]', inputs: ['some-input.xs'], outputs: ['some-output'], standalone: false, }) class TestDir { 'some-input.xs': string; 'some-output': EventEmitter<string>; } @NgModule({ declarations: [TestCmp, TestDir], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual(`Type 'number' is not assignable to type 'string'.`); expect(diags[1].messageText).toEqual( `Argument of type 'string' is not assignable to parameter of type 'number'.`, ); }); it('should support one input property mapping to multiple fields', () => { env.write( 'test.ts', ` import {Component, Directive, Input, NgModule} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input('propertyName') fieldA!: string; @Input('propertyName') fieldB!: string; } @Component({ selector: 'test-cmp', template: '<div dir propertyName="test"></div>', standalone: false, }) export class Cmp {} @NgModule({declarations: [Dir, Cmp]}) export class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should check event bindings', () => { env.tsconfig({fullTemplateTypeCheck: true, strictOutputEventTypes: true}); env.write( 'test.ts', ` import {Component, Directive, EventEmitter, NgModule, Output} from '@angular/core'; @Component({ selector: 'test', template: '<div dir (update)="update($event); updated = true" (focus)="update($event); focused = true"></div>', standalone: false, }) class TestCmp { update(data: string) {} } @Directive({ selector: '[dir]', standalone: false, }) class TestDir { @Output() update = new EventEmitter<number>(); } @NgModule({ declarations: [TestCmp, TestDir], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(3); expect(diags[0].messageText).toEqual( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); expect(diags[1].messageText).toEqual( `Property 'updated' does not exist on type 'TestCmp'. Did you mean 'update'?`, ); // Disabled because `checkTypeOfDomEvents` is disabled by default // expect(diags[2].messageText) // .toEqual( // `Argument of type 'FocusEvent' is not assignable to parameter of type 'string'.`); expect(diags[2].messageText).toEqual(`Property 'focused' does not exist on type 'TestCmp'.`); }); // https://github.com/angular/angular/issues/35073
{ "end_byte": 9233, "start_byte": 873, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_9238_17627
it('ngIf should narrow on output types', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngIf="person" (click)="handleEvent(person.name)"></div>', standalone: false, }) class TestCmp { person?: { name: string; }; handleEvent(name: string) {} } @NgModule({ imports: [CommonModule], declarations: [TestCmp], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('ngIf should narrow on output types across multiple guards', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngIf="person"><div *ngIf="person.name" (click)="handleEvent(person.name)"></div></div>', standalone: false, }) class TestCmp { person?: { name?: string; }; handleEvent(name: string) {} } @NgModule({ imports: [CommonModule], declarations: [TestCmp], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should support a directive being used in its own input expression', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Component({ selector: 'test', template: '<target-cmp #ref [foo]="ref.bar"></target-cmp>', standalone: false, }) export class TestCmp {} @Component({ template: '', selector: 'target-cmp', standalone: false, }) export class TargetCmp { readonly bar = 'test'; @Input() foo: string; } @NgModule({ declarations: [TestCmp, TargetCmp], }) export class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); // https://devblogs.microsoft.com/typescript/announcing-typescript-4-3-beta/#separate-write-types-on-properties it('should support separate write types on inputs', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, NgModule, Input} from '@angular/core'; @Component({ selector: 'test', template: '<target-cmp disabled></target-cmp>', standalone: false, }) export class TestCmp {} @Component({ template: '', selector: 'target-cmp', standalone: false, }) export class TargetCmp { @Input() get disabled(): boolean { return this._disabled; } set disabled(value: string|boolean) { this._disabled = value === '' || !!value; } private _disabled = false; } @NgModule({ declarations: [TestCmp, TargetCmp], }) export class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should check split two way binding', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Input, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<child-cmp [(value)]="counterValue"></child-cmp>', standalone: false, }) export class TestCmp { counterValue = 0; } @Component({ selector: 'child-cmp', template: '', standalone: false, }) export class ChildCmp { @Input() value = 0; } @NgModule({ declarations: [TestCmp, ChildCmp], }) export class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.SPLIT_TWO_WAY_BINDING)); expect(getSourceCodeForDiagnostic(diags[0])).toBe('value'); expect(diags[0].relatedInformation!.length).toBe(2); expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![0])).toBe('ChildCmp'); expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![1])).toBe('child-cmp'); }); it('when input and output go to different directives', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Input, NgModule, Output, Directive} from '@angular/core'; @Component({ selector: 'test', template: '<child-cmp [(value)]="counterValue"></child-cmp>', standalone: false, }) export class TestCmp { counterValue = 0; } @Directive({ selector: 'child-cmp', standalone: false, }) export class ChildCmpDir { @Output() valueChange: any; } @Component({ selector: 'child-cmp', template: '', standalone: false, }) export class ChildCmp { @Input() value = 0; } @NgModule({ declarations: [TestCmp, ChildCmp, ChildCmpDir], }) export class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.SPLIT_TWO_WAY_BINDING)); expect(getSourceCodeForDiagnostic(diags[0])).toBe('value'); expect(diags[0].relatedInformation!.length).toBe(2); expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![0])).toBe('ChildCmp'); expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![1])).toBe('ChildCmpDir'); }); it('should type check a two-way binding to a generic property', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter} from '@angular/core'; @Directive({selector: '[dir]', standalone: true}) export class Dir<T extends {id: string}> { @Input() val!: T; @Output() valChange = new EventEmitter<T>(); } @Component({ template: '<input dir [(val)]="invalidType">', standalone: true, imports: [Dir], }) export class FooCmp { invalidType = {id: 1}; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( jasmine.objectContaining({ messageText: `Type '{ id: number; }' is not assignable to type '{ id: string; }'.`, }), ); }); it('should use the setter type when assigning using a two-way binding to an input with different getter and setter types', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter} from '@angular/core'; @Directive({selector: '[dir]', standalone: true}) export class Dir { @Input() set val(value: string | null | undefined) { this._val = value as string; } get val(): string { return this._val; } private _val: string; @Output() valChange = new EventEmitter<string>(); } @Component({ template: '<input dir [(val)]="nullableType">', standalone: true, imports: [Dir], }) export class FooCmp { nullableType = null; } `, ); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); });
{ "end_byte": 17627, "start_byte": 9238, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_17633_25405
it('should type check a two-way binding to a function value', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter} from '@angular/core'; type TestFn = (val: number | null | undefined) => string; @Directive({selector: '[dir]', standalone: true}) export class Dir { @Input() val!: TestFn; @Output() valChange = new EventEmitter<TestFn>(); } @Component({ template: '<input dir [(val)]="invalidType">', standalone: true, imports: [Dir], }) export class FooCmp { invalidType = (val: string) => 0; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( jasmine.objectContaining({ messageText: `Type '(val: string) => number' is not assignable to type 'TestFn'.`, }), ); }); it('should check the fallback content of ng-content', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, template: \` <ng-content> <button (click)="acceptsNumber('hello')"></button> </ng-content> \`, }) class TestCmp { acceptsNumber(value: number) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( `Argument of type 'string' is not assignable to parameter of type 'number'.`, ); }); it('should not allow references to the default content of ng-content', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, template: \` <ng-content> <input #input/> </ng-content> {{input.value}} \`, }) class TestCmp { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain(`Property 'input' does not exist on type 'TestCmp'.`); }); it('should error on non valid typeof expressions', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, template: \` {{typeof {} === 'foobar'}} \`, }) class TestCmp { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain(`This comparison appears to be unintentional`); }); it('should error on misused logical not in typeof expressions', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, // should be !(typeof {} === 'object') template: \` {{!typeof {} === 'object'}} \`, }) class TestCmp { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain(`This comparison appears to be unintentional`); }); describe('strictInputTypes', () => { beforeEach(() => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Component({ selector: 'test', template: '<div dir [foo]="!!invalid"></div>', standalone: false, }) class TestCmp {} @Directive({ selector: '[dir]', standalone: false, }) class TestDir { @Input() foo: string; } @NgModule({ declarations: [TestCmp, TestDir], }) class Module {} `, ); }); it('should check expressions and their type when enabled', () => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual(`Type 'boolean' is not assignable to type 'string'.`); expect(diags[1].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); it('should check expressions and their type when overall strictness is enabled', () => { env.tsconfig({strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual(`Type 'boolean' is not assignable to type 'string'.`); expect(diags[1].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); it('should check expressions but not their type when not enabled', () => { env.tsconfig({fullTemplateTypeCheck: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); }); describe('strictNullInputTypes', () => { beforeEach(() => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Component({ selector: 'test', template: '<div dir [foo]="!!invalid && nullable"></div>', standalone: false, }) class TestCmp { nullable: boolean | null | undefined; } @Directive({ selector: '[dir]', standalone: false, }) class TestDir { @Input() foo: boolean; } @NgModule({ declarations: [TestCmp, TestDir], }) class Module {} `, ); }); it('should check expressions and their nullability when enabled', () => { env.tsconfig({ fullTemplateTypeCheck: true, strictInputTypes: true, strictNullInputTypes: true, }); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect((diags[0].messageText as ts.DiagnosticMessageChain).messageText).toEqual( `Type 'boolean | null | undefined' is not assignable to type 'boolean'.`, ); expect(diags[1].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); it('should check expressions and their nullability when overall strictness is enabled', () => { env.tsconfig({strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect((diags[0].messageText as ts.DiagnosticMessageChain).messageText).toEqual( `Type 'boolean | null | undefined' is not assignable to type 'boolean'.`, ); expect(diags[1].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); it('should check expressions but not their nullability when not enabled', () => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); });
{ "end_byte": 25405, "start_byte": 17633, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_25411_33626
describe('strictSafeNavigationTypes', () => { beforeEach(() => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Component({ selector: 'test', template: '<div dir [foo]="!!invalid && user?.isMember"></div>', standalone: false, }) class TestCmp { user?: {isMember: boolean}; } @Directive({ selector: '[dir]', standalone: false, }) class TestDir { @Input() foo: boolean; } @NgModule({ declarations: [TestCmp, TestDir], }) class Module {} `, ); }); it('should infer result type for safe navigation expressions when enabled', () => { env.tsconfig({ fullTemplateTypeCheck: true, strictInputTypes: true, strictNullInputTypes: true, strictSafeNavigationTypes: true, }); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect((diags[0].messageText as ts.DiagnosticMessageChain).messageText).toEqual( `Type 'boolean | undefined' is not assignable to type 'boolean'.`, ); expect(diags[1].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); it('should infer result type for safe navigation expressions when overall strictness is enabled', () => { env.tsconfig({strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect((diags[0].messageText as ts.DiagnosticMessageChain).messageText).toEqual( `Type 'boolean | undefined' is not assignable to type 'boolean'.`, ); expect(diags[1].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); it('should not infer result type for safe navigation expressions when not enabled', () => { env.tsconfig({ fullTemplateTypeCheck: true, strictInputTypes: true, }); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); }); describe('strictOutputEventTypes', () => { beforeEach(() => { env.write( 'test.ts', ` import {Component, Directive, EventEmitter, NgModule, Output} from '@angular/core'; @Component({ selector: 'test', template: '<div dir (update)="invalid && update($event);"></div>', standalone: false, }) class TestCmp { update(data: string) {} } @Directive({ selector: '[dir]', standalone: false, }) class TestDir { @Output() update = new EventEmitter<number>(); } @NgModule({ declarations: [TestCmp, TestDir], }) class Module {} `, ); }); it('should expressions and infer type of $event when enabled', () => { env.tsconfig({fullTemplateTypeCheck: true, strictOutputEventTypes: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); expect(diags[1].messageText).toEqual( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); }); it('should expressions and infer type of $event when overall strictness is enabled', () => { env.tsconfig({strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); expect(diags[1].messageText).toEqual( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); }); it('should check expressions but not infer type of $event when not enabled', () => { env.tsconfig({fullTemplateTypeCheck: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); }); describe('strictOutputEventTypes and animation event bindings', () => { beforeEach(() => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div (@animation.done)="invalid; update($event);"></div>', standalone: false, }) class TestCmp { update(data: string) {} } @NgModule({ declarations: [TestCmp], }) class Module {} `, ); }); it('should check expressions and let $event be of type AnimationEvent when enabled', () => { env.tsconfig({fullTemplateTypeCheck: true, strictOutputEventTypes: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); expect(diags[1].messageText).toEqual( `Argument of type 'AnimationEvent' is not assignable to parameter of type 'string'.`, ); }); it('should check expressions and let $event be of type AnimationEvent when overall strictness is enabled', () => { env.tsconfig({strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); expect(diags[1].messageText).toEqual( `Argument of type 'AnimationEvent' is not assignable to parameter of type 'string'.`, ); }); it('should check expressions and let $event be of type any when not enabled', () => { env.tsconfig({fullTemplateTypeCheck: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); }); describe('strictDomLocalRefTypes', () => { beforeEach(() => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<input #ref>{{ref.does_not_exist}}', standalone: false, }) class TestCmp {} @NgModule({ declarations: [TestCmp], }) class Module {} `, ); }); it('should infer the type of DOM references when enabled', () => { env.tsconfig({fullTemplateTypeCheck: true, strictDomLocalRefTypes: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( `Property 'does_not_exist' does not exist on type 'HTMLInputElement'.`, ); }); it('should infer the type of DOM references when overall strictness is enabled', () => { env.tsconfig({strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( `Property 'does_not_exist' does not exist on type 'HTMLInputElement'.`, ); }); it('should let the type of DOM references be any when not enabled', () => { env.tsconfig({fullTemplateTypeCheck: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); });
{ "end_byte": 33626, "start_byte": 25411, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_33632_41500
describe('strictAttributeTypes', () => { beforeEach(() => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Component({ selector: 'test', template: '<textarea dir disabled cols="3"></textarea>', standalone: false, }) class TestCmp {} @Directive({ selector: '[dir]', standalone: false, }) class TestDir { @Input() disabled: boolean; @Input() cols: number; } @NgModule({ declarations: [TestCmp, TestDir], }) class Module {} `, ); }); it('should produce an error for text attributes when enabled', () => { env.tsconfig({ fullTemplateTypeCheck: true, strictInputTypes: true, strictAttributeTypes: true, }); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual(`Type 'string' is not assignable to type 'boolean'.`); expect(diags[1].messageText).toEqual(`Type 'string' is not assignable to type 'number'.`); }); it('should produce an error for text attributes when overall strictness is enabled', () => { env.tsconfig({strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual(`Type 'string' is not assignable to type 'boolean'.`); expect(diags[1].messageText).toEqual(`Type 'string' is not assignable to type 'number'.`); }); it('should not produce an error for text attributes when not enabled', () => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); }); describe('strictDomEventTypes', () => { beforeEach(() => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div (focus)="invalid; update($event)"></div>', standalone: false, }) class TestCmp { update(data: string) {} } @NgModule({ declarations: [TestCmp], }) class Module {} `, ); }); it('should check expressions and infer type of $event when enabled', () => { env.tsconfig({fullTemplateTypeCheck: true, strictDomEventTypes: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); expect(diags[1].messageText).toEqual( `Argument of type 'FocusEvent' is not assignable to parameter of type 'string'.`, ); }); it('should check expressions and infer type of $event when overall strictness is enabled', () => { env.tsconfig({strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); expect(diags[1].messageText).toEqual( `Argument of type 'FocusEvent' is not assignable to parameter of type 'string'.`, ); }); it('should check expressions but not infer type of $event when not enabled', () => { env.tsconfig({fullTemplateTypeCheck: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( `Property 'invalid' does not exist on type 'TestCmp'.`, ); }); }); it('should check basic usage of NgIf', () => { env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngIf="user">{{user.name}}</div>', standalone: false, }) class TestCmp { user: {name: string}|null; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); env.driveMain(); }); it('should check usage of NgIf with explicit non-null guard', () => { env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngIf="user !== null">{{user.name}}</div>', standalone: false, }) class TestCmp { user: {name: string}|null; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); env.driveMain(); }); it('should check usage of NgIf when using "let" to capture $implicit context variable', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngIf="user; let u">{{u.name}}</div>', standalone: false, }) class TestCmp { user: {name: string}|null|false; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); env.driveMain(); }); it('should check usage of NgIf when using "as" to capture `ngIf` context variable', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngIf="user as u">{{u.name}}</div>', standalone: false, }) class TestCmp { user: {name: string}|null|false; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); env.driveMain(); }); it('should check basic usage of NgFor', () => { env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngFor="let user of users">{{user.name}}</div>', standalone: false, }) class TestCmp { users: {name: string}[]; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); env.driveMain(); }); it('should report an error inside the NgFor template', () => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngFor="let user of users">{{user.does_not_exist}}</div>', standalone: false, }) export class TestCmp { users: {name: string}[]; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) export class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual( `Property 'does_not_exist' does not exist on type '{ name: string; }'.`, ); expect(getSourceCodeForDiagnostic(diags[0])).toBe('does_not_exist'); });
{ "end_byte": 41500, "start_byte": 33632, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_41506_49823
it('should accept an NgFor iteration over an any-typed value', () => { env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngFor="let user of users">{{user.name}}</div>', standalone: false, }) export class TestCmp { users: any; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) export class Module {} `, ); env.driveMain(); }); it('should accept NgFor iteration over a QueryList', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule, QueryList} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngFor="let user of users">{{user.name}}</div>', standalone: false, }) class TestCmp { users!: QueryList<{name: string}>; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); env.driveMain(); }); // https://github.com/angular/angular/issues/40125 it('should accept NgFor iteration when trackBy is used with a wider type', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; interface Base { id: string; } interface Derived extends Base { name: string; } @Component({ selector: 'test', template: '<div *ngFor="let derived of derivedList; trackBy: trackByBase">{{derived.name}}</div>', standalone: false, }) class TestCmp { derivedList!: Derived[]; trackByBase(index: number, item: Base): string { return item.id; } } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); env.driveMain(); }); // https://github.com/angular/angular/issues/42609 it('should accept NgFor iteration when trackBy is used with an `any` array', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; interface ItemType { id: string; } @Component({ selector: 'test', template: '<div *ngFor="let item of anyList; trackBy: trackByBase">{{item.name}}</div>', standalone: false, }) class TestCmp { anyList!: any[]; trackByBase(index: number, item: ItemType): string { return item.id; } } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); env.driveMain(); }); it('should reject NgFor iteration when trackBy is incompatible with item type', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; interface ItemType { id: string; } interface UnrelatedType { name: string; } @Component({ selector: 'test', template: '<div *ngFor="let item of unrelatedList; trackBy: trackByBase">{{item.name}}</div>', standalone: false, }) class TestCmp { unrelatedList!: UnrelatedType[]; trackByBase(index: number, item: ItemType): string { return item.id; } } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect((diags[0].messageText as ts.DiagnosticMessageChain).messageText).toContain( `is not assignable to type 'TrackByFunction<UnrelatedType>'.`, ); }); it('should infer the context of NgFor', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngFor="let user of users as all">{{all.length}}</div>', standalone: false, }) class TestCmp { users: {name: string}[]; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should allow the implicit value of an NgFor to be invoked', () => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngFor="let fn of functions">{{fn()}}</div>', standalone: false, }) class TestCmp { functions = [() => 1, () => 2]; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); env.driveMain(); }); it('should infer the context of NgIf', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngIf="getUser(); let user">{{user.nonExistingProp}}</div>', standalone: false, }) class TestCmp { getUser(): {name: string} { return {name: 'frodo'}; } } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Property 'nonExistingProp' does not exist on type '{ name: string; }'.`, ); }); it('should report an error with an unknown local ref target', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div #ref="unknownTarget"></div>', standalone: false, }) class TestCmp {} @NgModule({ declarations: [TestCmp], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`No directive found with exportAs 'unknownTarget'.`); expect(getSourceCodeForDiagnostic(diags[0])).toBe('unknownTarget'); }); it('should treat an unknown local ref target as type any', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div #ref="unknownTarget">{{ use(ref) }}</div>', standalone: false, }) class TestCmp { use(ref: string): string { return ref; } } @NgModule({ declarations: [TestCmp], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`No directive found with exportAs 'unknownTarget'.`); expect(getSourceCodeForDiagnostic(diags[0])).toBe('unknownTarget'); });
{ "end_byte": 49823, "start_byte": 41506, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_49829_56806
it('should report an error with an unknown pipe', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '{{expr | unknown}}', standalone: false, }) class TestCmp { expr = 3; } @NgModule({ declarations: [TestCmp], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`No pipe found with name 'unknown'.`); expect(getSourceCodeForDiagnostic(diags[0])).toBe('unknown'); }); it('should report an error with an unknown pipe even if `fullTemplateTypeCheck` is disabled', () => { env.tsconfig({fullTemplateTypeCheck: false}); env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '{{expr | unknown}}', standalone: false, }) class TestCmp { expr = 3; } @NgModule({ declarations: [TestCmp], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`No pipe found with name 'unknown'.`); expect(getSourceCodeForDiagnostic(diags[0])).toBe('unknown'); }); it('should report an error with pipe bindings', () => { env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: \` checking the input type to the pipe: {{user | index: 1}} checking the return type of the pipe: {{(users | index: 1).does_not_exist}} checking the argument type: {{users | index: 'test'}} checking the argument count: {{users | index: 1:2}} \`, standalone: false, }) class TestCmp { user: {name: string}; users: {name: string}[]; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(4); const allErrors = [ `'does_not_exist' does not exist on type '{ name: string; }'`, `Expected 2 arguments, but got 3.`, `Argument of type 'string' is not assignable to parameter of type 'number'`, `Argument of type '{ name: string; }' is not assignable to parameter of type 'unknown[]'`, ]; for (const error of allErrors) { if ( !diags.some( (diag) => ts.flattenDiagnosticMessageText(diag.messageText, '').indexOf(error) > -1, ) ) { fail(`Expected a diagnostic message with text: ${error}`); } } }); it('should constrain types using type parameter bounds', () => { env.tsconfig({ fullTemplateTypeCheck: true, strictInputTypes: true, strictContextGenerics: true, }); env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, Input, NgModule} from '@angular/core'; @Component({ selector: 'test', template: '<div *ngFor="let user of users">{{user.does_not_exist}}</div>', standalone: false, }) class TestCmp<T extends {name: string}> { @Input() users: T[]; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual(`Property 'does_not_exist' does not exist on type 'T'.`); expect(getSourceCodeForDiagnostic(diags[0])).toBe('does_not_exist'); }); describe('microsyntax variables', () => { beforeEach(() => { // Use the same template for both tests env.write( 'test.ts', ` import {CommonModule} from '@angular/common'; import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: \`<div *ngFor="let foo of foos as foos"> {{foo.name}} of {{foos.nonExistingProp}} </div> \`, standalone: false, }) export class TestCmp { foos: {name: string}[]; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) export class Module {} `, ); }); it("should be treated as 'any' without strictTemplates", () => { env.tsconfig({fullTemplateTypeCheck: true, strictTemplates: false}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should be correctly inferred under strictTemplates', () => { env.tsconfig({strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Property 'nonExistingProp' does not exist on type '{ name: string; }[]'.`, ); }); }); it('should properly type-check inherited directives', () => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); env.write( 'test.ts', ` import {Component, Directive, Input, NgModule} from '@angular/core'; @Directive() class AbstractDir { @Input() fromAbstract!: number; } @Directive({ selector: '[base]', standalone: false, }) class BaseDir extends AbstractDir { @Input() fromBase!: string; } @Directive({ selector: '[child]', standalone: false, }) class ChildDir extends BaseDir { @Input() fromChild!: boolean; } @Component({ selector: 'test', template: '<div child [fromAbstract]="true" [fromBase]="3" [fromChild]="4"></div>', standalone: false, }) class TestCmp {} @NgModule({ declarations: [TestCmp, ChildDir], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(3); expect(diags[0].messageText).toBe(`Type 'boolean' is not assignable to type 'number'.`); expect(getSourceCodeForDiagnostic(diags[0])).toEqual('fromAbstract'); expect(diags[1].messageText).toBe(`Type 'number' is not assignable to type 'string'.`); expect(getSourceCodeForDiagnostic(diags[1])).toEqual('fromBase'); expect(diags[2].messageText).toBe(`Type 'number' is not assignable to type 'boolean'.`); expect(getSourceCodeForDiagnostic(diags[2])).toEqual('fromChild'); });
{ "end_byte": 56806, "start_byte": 49829, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_56812_63561
it('should properly type-check inherited directives from external libraries', () => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); env.write( 'node_modules/external/index.d.ts', ` import * as i0 from '@angular/core'; export declare class AbstractDir { fromAbstract: number; static ɵdir: i0.ɵɵDirectiveDeclaration<AbstractDir, never, never, {'fromAbstract': 'fromAbstract'}, never, never>; } export declare class BaseDir extends AbstractDir { fromBase: string; static ɵdir: i0.ɵɵDirectiveDeclaration<BaseDir, '[base]', never, {'fromBase': 'fromBase'}, never, never>; } export declare class ExternalModule { static ɵmod: i0.ɵɵNgModuleDeclaration<ExternalModule, [typeof BaseDir], never, [typeof BaseDir]>; } `, ); env.write( 'test.ts', ` import {Component, Directive, Input, NgModule} from '@angular/core'; import {BaseDir, ExternalModule} from 'external'; @Directive({ selector: '[child]', standalone: false, }) class ChildDir extends BaseDir { @Input() fromChild!: boolean; } @Component({ selector: 'test', template: '<div child [fromAbstract]="true" [fromBase]="3" [fromChild]="4"></div>', standalone: false, }) class TestCmp {} @NgModule({ declarations: [TestCmp, ChildDir], imports: [ExternalModule], }) class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(3); expect(diags[0].messageText).toBe(`Type 'boolean' is not assignable to type 'number'.`); expect(getSourceCodeForDiagnostic(diags[0])).toEqual('fromAbstract'); expect(diags[1].messageText).toBe(`Type 'number' is not assignable to type 'string'.`); expect(getSourceCodeForDiagnostic(diags[1])).toEqual('fromBase'); expect(diags[2].messageText).toBe(`Type 'number' is not assignable to type 'boolean'.`); expect(getSourceCodeForDiagnostic(diags[2])).toEqual('fromChild'); }); it('should detect an illegal write to a template variable', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; @Component({ selector: 'test', template: \` <div *ngIf="x as y"> <button (click)="y = !y">Toggle</button> </div> \`, standalone: false, }) export class TestCmp { x!: boolean; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) export class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toEqual(1); expect(getSourceCodeForDiagnostic(diags[0])).toEqual('y = !y'); }); it('should detect a duplicate variable declaration', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; @Component({ selector: 'test', template: \` <div *ngFor="let i of items; let i = index"> {{i}} </div> \`, standalone: false, }) export class TestCmp { items!: string[]; } @NgModule({ declarations: [TestCmp], imports: [CommonModule], }) export class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toEqual(1); expect(diags[0].code).toEqual(ngErrorCode(ErrorCode.DUPLICATE_VARIABLE_DECLARATION)); expect(getSourceCodeForDiagnostic(diags[0])).toContain('let i = index'); }); it('should still type-check when fileToModuleName aliasing is enabled, but alias exports are not in the .d.ts file', () => { // The template type-checking file imports directives/pipes in order to type-check their // usage. When `UnifiedModulesHost` aliasing is enabled, these imports would ordinarily use // aliased values. However, such aliases are not guaranteed to exist in the .d.ts files, // and so feeding such imports back into TypeScript does not work. // // Instead, direct imports should be used within template type-checking code. This test // verifies that template type-checking is able to cope with such a scenario where // aliasing is enabled and alias re-exports don't exist in .d.ts files. env.tsconfig({ // Setting this private flag turns on aliasing. '_useHostForImportGeneration': true, // Because the tsconfig is overridden, template type-checking needs to be turned back on // explicitly as well. 'fullTemplateTypeCheck': true, }); // 'alpha' declares the directive which will ultimately be imported. env.write( 'alpha.d.ts', ` import {ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core'; export declare class ExternalDir { input: string; static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, { 'input': "input" }, never, never>; } export declare class AlphaModule { static ɵmod: ɵɵNgModuleDeclaration<AlphaModule, [typeof ExternalDir], never, [typeof ExternalDir]>; } `, ); // 'beta' re-exports AlphaModule from alpha. env.write( 'beta.d.ts', ` import {ɵɵNgModuleDeclaration} from '@angular/core'; import {AlphaModule} from './alpha'; export declare class BetaModule { static ɵmod: ɵɵNgModuleDeclaration<BetaModule, never, never, [typeof AlphaModule]>; } `, ); // The application imports BetaModule from beta, gaining visibility of ExternalDir from // alpha. env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; import {BetaModule} from './beta'; @Component({ selector: 'cmp', template: '<div test input="value"></div>', standalone: false, }) export class Cmp {} @NgModule({ declarations: [Cmp], imports: [BetaModule], }) export class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); describe('input co
{ "end_byte": 63561, "start_byte": 56812, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_63567_72311
', () => { beforeEach(() => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); env.write( 'node_modules/@angular/material/index.d.ts', ` import * as i0 from '@angular/core'; export declare class MatInput { value: string; static ɵdir: i0.ɵɵDirectiveDeclaration<MatInput, '[matInput]', never, {'value': 'value'}, {}, never>; static ngAcceptInputType_value: string|number; } export declare class MatInputModule { static ɵmod: i0.ɵɵNgModuleDeclaration<MatInputModule, [typeof MatInput], never, [typeof MatInput]>; } `, ); }); function getDiagnosticLines(diag: ts.Diagnostic): string[] { const separator = '~~~~~'; return ts.flattenDiagnosticMessageText(diag.messageText, separator).split(separator); } it('should coerce an input using a transform function if provided', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; import {MatInputModule} from '@angular/material'; @Component({ selector: 'blah', template: '<input matInput [value]="someNumber">', standalone: false, }) export class FooCmp { someNumber = 3; } @NgModule({ declarations: [FooCmp], imports: [MatInputModule], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should apply coercion members of base classes', () => { env.write( 'test.ts', ` import {Component, Directive, Input, NgModule} from '@angular/core'; @Directive() export class BaseDir { @Input() value: string; static ngAcceptInputType_value: string|number; } @Directive({ selector: '[dir]', standalone: false, }) export class MyDir extends BaseDir {} @Component({ selector: 'blah', template: '<input dir [value]="someNumber">', standalone: false, }) export class FooCmp { someNumber = 3; } @NgModule({ declarations: [MyDir, FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should give an error if the binding expression type is not accepted by the coercion function', () => { env.write( 'test.ts', ` import {Component, NgModule, Input, Directive} from '@angular/core'; import {MatInputModule} from '@angular/material'; @Component({ selector: 'blah', template: '<input matInput [value]="invalidType">', standalone: false, }) export class FooCmp { invalidType = true; } @NgModule({ declarations: [FooCmp], imports: [MatInputModule], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Type 'boolean' is not assignable to type 'string | number'.`, ); }); it('should give an error for undefined bindings into regular inputs when coercion members are present', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Component({ selector: 'blah', template: '<input dir [regular]="undefined" [coerced]="1">', standalone: false, }) export class FooCmp { invalidType = true; } @Directive({ selector: '[dir]', standalone: false, }) export class CoercionDir { @Input() regular: string; @Input() coerced: boolean; static ngAcceptInputType_coerced: boolean|number; } @NgModule({ declarations: [FooCmp, CoercionDir], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Type 'undefined' is not assignable to type 'string'.`); }); it('should type check using the first parameter type of a simple transform function', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; export function toNumber(val: boolean | string) { return 1; } @Directive({selector: '[dir]', standalone: true}) export class CoercionDir { @Input({transform: toNumber}) val!: number; } @Component({ template: '<input dir [val]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = 1; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Type 'number' is not assignable to type 'string | boolean'.`, ); }); it('should type checking using the first parameter type of a simple inline transform function', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; @Directive({selector: '[dir]', standalone: true}) export class CoercionDir { @Input({transform: (val: boolean | string) => 1}) val!: number; } @Component({ template: '<input dir [val]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = 1; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Type 'number' is not assignable to type 'string | boolean'.`, ); }); it('should type check using the transform function specified in the `inputs` array', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; export function toNumber(val: boolean | string) { return 1; } @Directive({ selector: '[dir]', standalone: true, inputs: [{ name: 'val', transform: toNumber }] }) export class CoercionDir { val!: number; } @Component({ template: '<input dir [val]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = 1; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Type 'number' is not assignable to type 'string | boolean'.`, ); }); it('should type check using the first parameter type of a built-in function', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; @Directive({selector: '[dir]', standalone: true}) export class CoercionDir { @Input({transform: parseInt}) val!: number; } @Component({ template: '<input dir [val]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = 1; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Type 'number' is not assignable to type 'string'.`); }); it('should type check
{ "end_byte": 72311, "start_byte": 63567, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_72319_81236
ted transform function with a complex type', () => { env.tsconfig({strictTemplates: true}); env.write( 'types.ts', ` export class ComplexObjValue { foo: boolean; } export interface ComplexObj { value: ComplexObjValue; } `, ); env.write( 'utils.ts', ` import {ComplexObj} from './types'; export type ToNumberType = string | boolean | ComplexObj; export function toNumber(val: ToNumberType) { return 1; } `, ); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; import {toNumber} from './utils'; @Directive({selector: '[dir]', standalone: true}) export class CoercionDir { @Input({transform: toNumber}) val!: number; } @Component({ template: '<input dir [val]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = { value: { foo: 'hello' } }; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getDiagnosticLines(diags[0])).toEqual([ `Type '{ value: { foo: string; }; }' is not assignable to type 'ToNumberType'.`, ` Type '{ value: { foo: string; }; }' is not assignable to type 'ComplexObj'.`, ` The types of 'value.foo' are incompatible between these types.`, ` Type 'string' is not assignable to type 'boolean'.`, ]); }); it('should type check an imported transform function with a complex type from an external library', () => { env.tsconfig({strictTemplates: true}); env.write( 'node_modules/external/index.d.ts', ` export class ExternalComplexObjValue { foo: boolean; } export interface ExternalComplexObj { value: ExternalComplexObjValue; } export type ExternalToNumberType = string | boolean | ExternalComplexObj; export declare function externalToNumber(val: ExternalToNumberType): number; `, ); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; import {externalToNumber} from 'external'; @Directive({selector: '[dir]', standalone: true}) export class CoercionDir { @Input({transform: externalToNumber}) val!: number; } @Component({ template: '<input dir [val]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = { value: { foo: 'hello' } }; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getDiagnosticLines(diags[0])).toEqual([ `Type '{ value: { foo: string; }; }' is not assignable to type 'ExternalToNumberType'.`, ` Type '{ value: { foo: string; }; }' is not assignable to type 'ExternalComplexObj'.`, ` The types of 'value.foo' are incompatible between these types.`, ` Type 'string' is not assignable to type 'boolean'.`, ]); }); it('should type check an input with a generic transform type', () => { env.tsconfig({strictTemplates: true}); env.write( 'generics.ts', ` export interface GenericWrapper<T> { value: T; } `, ); env.write( 'types.ts', ` export class ExportedClass { foo: boolean; } `, ); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; import {GenericWrapper} from './generics'; import {ExportedClass} from './types'; export interface LocalInterface { foo: string; } @Directive({selector: '[dir]', standalone: true}) export class CoercionDir { @Input({transform: (val: GenericWrapper<ExportedClass>) => 1}) importedVal!: number; @Input({transform: (val: GenericWrapper<LocalInterface>) => 1}) localVal!: number; } @Component({ template: '<input dir [importedVal]="invalidType" [localVal]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = { value: { foo: 1 } }; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(getDiagnosticLines(diags[0])).toEqual([ `Type '{ value: { foo: number; }; }' is not assignable to type 'GenericWrapper<ExportedClass>'.`, ` The types of 'value.foo' are incompatible between these types.`, ` Type 'number' is not assignable to type 'boolean'.`, ]); expect(getDiagnosticLines(diags[1])).toEqual([ `Type '{ value: { foo: number; }; }' is not assignable to type 'GenericWrapper<LocalInterface>'.`, ` The types of 'value.foo' are incompatible between these types.`, ` Type 'number' is not assignable to type 'string'.`, ]); }); it('should type check an input with a generic transform union type', () => { env.tsconfig({strictTemplates: true}); env.write( 'types.ts', ` interface GenericWrapper<T> { value: T; } export type CoercionType<T> = boolean | string | GenericWrapper<T>; `, ); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; import {CoercionType} from './types'; @Directive({selector: '[dir]', standalone: true}) export class CoercionDir { @Input({transform: (val: CoercionType<string>) => 1}) val!: number; } @Component({ template: '<input dir [val]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = {value: 1}; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getDiagnosticLines(diags[0])).toEqual([ `Type '{ value: number; }' is not assignable to type 'CoercionType<string>'.`, ` Type '{ value: number; }' is not assignable to type 'GenericWrapper<string>'.`, ` Types of property 'value' are incompatible.`, ` Type 'number' is not assignable to type 'string'.`, ]); }); it('should type check an input with a generic transform type from an external library', () => { env.tsconfig({strictTemplates: true}); env.write( 'node_modules/external/index.d.ts', ` export interface ExternalGenericWrapper<T> { value: T; } export declare class ExternalClass { foo: boolean; } `, ); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; import {ExternalGenericWrapper, ExternalClass} from 'external'; @Directive({selector: '[dir]', standalone: true}) export class CoercionDir { @Input({transform: (val: ExternalGenericWrapper<ExternalClass>) => 1}) val!: number; } @Component({ template: '<input dir [val]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = { value: { foo: 1 } }; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getDiagnosticLines(diags[0])).toEqual([ `Type '{ value: { foo: number; }; }' is not assignable to type 'ExternalGenericWrapper<ExternalClass>'.`, ` The types of 'value.foo' are incompatible between these types.`, ` Type 'number' is not assignable to type 'boolean'.`, ]); }); it('should allow any v
{ "end_byte": 81236, "start_byte": 72319, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_81244_88456
be assigned if the transform function has no parameters', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; @Directive({selector: '[dir]', standalone: true}) export class CoercionDir { @Input({transform: () => 1}) val!: number; } @Component({ template: '<input dir [val]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = {}; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should type check static inputs against the transform function type', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; export function toNumber(val: number | boolean) { return 1; } @Directive({selector: '[dir]', standalone: true}) export class CoercionDir { @Input({transform: toNumber}) val!: number; } @Component({ template: '<input dir val="test">', standalone: true, imports: [CoercionDir], }) export class FooCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Type '"test"' is not assignable to type 'number | boolean'.`, ); }); it('should type check inputs with a transform function coming from a host directive', () => { env.tsconfig({strictTemplates: true}); env.write( 'host-dir.ts', ` import {Directive, Input} from '@angular/core'; export interface HostDirType { value: number; } @Directive({standalone: true}) export class HostDir { @Input({transform: (val: HostDirType) => 1}) val!: number; } `, ); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; import {HostDir} from './host-dir'; @Directive({ selector: '[dir]', standalone: true, hostDirectives: [{ directive: HostDir, inputs: ['val'] }] }) export class CoercionDir {} @Component({ template: '<input dir [val]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = { value: 'hello' }; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getDiagnosticLines(diags[0])).toEqual([ `Type '{ value: string; }' is not assignable to type 'HostDirType'.`, ` Types of property 'value' are incompatible.`, ` Type 'string' is not assignable to type 'number'.`, ]); }); it('should type check inputs with a transform inherited from a parent class', () => { env.tsconfig({strictTemplates: true}); env.write( 'host-dir.ts', ` import {Directive, Input} from '@angular/core'; export interface ParentType { value: number; } @Directive({standalone: true}) export class Parent { @Input({transform: (val: ParentType) => 1}) val!: number; } `, ); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; import {Parent} from './host-dir'; @Directive({ selector: '[dir]', standalone: true }) export class CoercionDir extends Parent {} @Component({ template: '<input dir [val]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = { value: 'hello' }; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getDiagnosticLines(diags[0])).toEqual([ `Type '{ value: string; }' is not assignable to type 'ParentType'.`, ` Types of property 'value' are incompatible.`, ` Type 'string' is not assignable to type 'number'.`, ]); }); it('should type check inputs with transforms referring to an ambient type', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; export class ElementRef<T> { nativeElement: T; } @Directive({ selector: '[dir]', standalone: true, }) export class Dir { @Input({transform: (val: HTMLInputElement | ElementRef<HTMLInputElement>) => { return val instanceof ElementRef ? val.nativeElement.value : val.value; }}) expectsInput: string | null = null; } @Component({ standalone: true, imports: [Dir], template: '<div dir [expectsInput]="someDiv"></div>', }) export class App { someDiv!: HTMLDivElement; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getDiagnosticLines(diags[0]).join('\n')).toContain( `Type 'HTMLDivElement' is not assignable to type ` + `'HTMLInputElement | ElementRef<HTMLInputElement>'`, ); }); it('should type check a two-way binding to an input with a transform', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter} from '@angular/core'; export function toNumber(val: boolean | string) { return 1; } @Directive({selector: '[dir]', standalone: true}) export class CoercionDir { @Input({transform: toNumber}) val!: number; @Output() valChange = new EventEmitter<number>(); } @Component({ template: '<input dir [(val)]="invalidType">', standalone: true, imports: [CoercionDir], }) export class FooCmp { invalidType = 1; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Type 'number' is not assignable to type 'string | boolean'.`, ); }); }); describe('restricted inp
{ "end_byte": 88456, "start_byte": 81244, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_88462_97931
() => { const directiveDeclaration = ` @Directive({ selector: '[dir]', standalone: false, }) export class TestDir { @Input() protected protectedField!: string; @Input() private privateField!: string; @Input() readonly readonlyField!: string; } `; const correctTypeInputsToRestrictedFields = ` import {Component, NgModule, Input, Directive} from '@angular/core'; @Component({ selector: 'blah', template: '<div dir [readonlyField]="value" [protectedField]="value" [privateField]="value"></div>', standalone: false, }) export class FooCmp { value = "value"; } ${directiveDeclaration} @NgModule({ declarations: [FooCmp, TestDir], }) export class FooModule {} `; const correctInputsToRestrictedFieldsFromBaseClass = ` import {Component, NgModule, Input, Directive} from '@angular/core'; @Component({ selector: 'blah', template: '<div child-dir [readonlyField]="value" [protectedField]="value" [privateField]="value"></div>', standalone: false, }) export class FooCmp { value = "value"; } ${directiveDeclaration} @Directive({ selector: '[child-dir]', standalone: false, }) export class ChildDir extends TestDir { } @NgModule({ declarations: [FooCmp, ChildDir], }) export class FooModule {} `; describe('with strictInputAccessModifiers', () => { beforeEach(() => { env.tsconfig({ fullTemplateTypeCheck: true, strictInputTypes: true, strictInputAccessModifiers: true, }); }); it('should produce diagnostics for inputs which assign to readonly, private, and protected fields', () => { env.write('test.ts', correctTypeInputsToRestrictedFields); expectIllegalAssignmentErrors(env.driveDiagnostics()); }); it('should produce diagnostics for inputs which assign to readonly, private, and protected fields inherited from a base class', () => { env.write('test.ts', correctInputsToRestrictedFieldsFromBaseClass); expectIllegalAssignmentErrors(env.driveDiagnostics()); }); function expectIllegalAssignmentErrors(diags: ReadonlyArray<ts.Diagnostic>) { expect(diags.length).toBe(3); const actualMessages = diags.map((d) => d.messageText).sort(); const expectedMessages = [ `Property 'protectedField' is protected and only accessible within class 'TestDir' and its subclasses.`, `Property 'privateField' is private and only accessible within class 'TestDir'.`, `Cannot assign to 'readonlyField' because it is a read-only property.`, ].sort(); expect(actualMessages).toEqual(expectedMessages); } it('should report invalid type assignment when field name is not a valid JS identifier', () => { env.write( 'test.ts', ` import {Component, NgModule, Input, Directive} from '@angular/core'; @Component({ selector: 'blah', template: '<div dir [private-input.xs]="value"></div>', standalone: false, }) export class FooCmp { value = 5; } @Directive({ selector: '[dir]', standalone: false, }) export class TestDir { @Input() private 'private-input.xs'!: string; } @NgModule({ declarations: [FooCmp, TestDir], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual(`Type 'number' is not assignable to type 'string'.`); }); }); describe('with strict inputs', () => { beforeEach(() => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); }); it('should not produce diagnostics for correct inputs which assign to readonly, private, or protected fields', () => { env.write('test.ts', correctTypeInputsToRestrictedFields); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not produce diagnostics for correct inputs which assign to readonly, private, or protected fields inherited from a base class', () => { env.write('test.ts', correctInputsToRestrictedFieldsFromBaseClass); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should produce diagnostics when assigning incorrect type to readonly, private, or protected fields', () => { env.write( 'test.ts', ` import {Component, NgModule, Input, Directive} from '@angular/core'; @Component({ selector: 'blah', template: '<div dir [readonlyField]="value" [protectedField]="value" [privateField]="value"></div>', standalone: false, }) export class FooCmp { value = 1; } ${directiveDeclaration} @NgModule({ declarations: [FooCmp, TestDir], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(3); expect(diags[0].messageText).toEqual(`Type 'number' is not assignable to type 'string'.`); expect(diags[1].messageText).toEqual(`Type 'number' is not assignable to type 'string'.`); expect(diags[2].messageText).toEqual(`Type 'number' is not assignable to type 'string'.`); }); }); }); it('should not produce diagnostics for undeclared inputs', () => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); env.write( 'test.ts', ` import {Component, NgModule, Input, Directive} from '@angular/core'; @Component({ selector: 'blah', template: '<div dir [undeclared]="value"></div>', standalone: false, }) export class FooCmp { value = "value"; } @Directive({ selector: '[dir]', inputs: ['undeclared'], standalone: false, }) export class TestDir { } @NgModule({ declarations: [FooCmp, TestDir], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should produce diagnostics for invalid expressions when assigned into an undeclared input', () => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); env.write( 'test.ts', ` import {Component, NgModule, Input, Directive} from '@angular/core'; @Component({ selector: 'blah', template: '<div dir [undeclared]="value"></div>', standalone: false, }) export class FooCmp { } @Directive({ selector: '[dir]', inputs: ['undeclared'], standalone: false, }) export class TestDir { } @NgModule({ declarations: [FooCmp, TestDir], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Property 'value' does not exist on type 'FooCmp'.`); }); it('should not produce diagnostics for undeclared inputs inherited from a base class', () => { env.tsconfig({fullTemplateTypeCheck: true, strictInputTypes: true}); env.write( 'test.ts', ` import {Component, NgModule, Input, Directive} from '@angular/core'; @Component({ selector: 'blah', template: '<div dir [undeclaredBase]="value"></div>', standalone: false, }) export class FooCmp { value = "value"; } @Directive({ inputs: ['undeclaredBase'], standalone: false, }) export class BaseDir { } @Directive({ selector: '[dir]', standalone: false, }) export class TestDir extends BaseDir { } @NgModule({ declarations: [FooCmp, TestDir], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); describe('legacy schema
{ "end_byte": 97931, "start_byte": 88462, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_97937_106347
ng with the DOM schema', () => { beforeEach(() => { env.tsconfig({fullTemplateTypeCheck: false}); }); it('should check for unknown elements', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<foo>test</foo>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`'foo' is not a known element: 1. If 'foo' is an Angular component, then verify that it is part of this module. 2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`); }); it('should check for unknown elements in standalone components', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<foo>test</foo>', standalone: true, }) export class FooCmp {} @NgModule({ imports: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`'foo' is not a known element: 1. If 'foo' is an Angular component, then verify that it is included in the '@Component.imports' of this component. 2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@Component.schemas' of this component.`); }); it('should check for unknown properties in standalone components', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-comp', template: '...', standalone: true, }) export class MyComp {} @Component({ selector: 'blah', imports: [MyComp], template: '<my-comp [foo]="true"></my-comp>', standalone: true, }) export class FooCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText) .toMatch(`Can't bind to 'foo' since it isn't a known property of 'my-comp'. 1. If 'my-comp' is an Angular component and it has 'foo' input, then verify that it is included in the '@Component.imports' of this component. 2. If 'my-comp' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@Component.schemas' of this component to suppress this message. 3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@Component.schemas' of this component.`); }); it('should have a descriptive error for unknown elements that contain a dash', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<my-foo>test</my-foo>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`'my-foo' is not a known element: 1. If 'my-foo' is an Angular component, then verify that it is part of this module. 2. If 'my-foo' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`); }); it('should have a descriptive error for unknown elements that contain a dash in standalone components', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<my-foo>test</my-foo>', standalone: true, }) export class FooCmp {} @NgModule({ imports: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`'my-foo' is not a known element: 1. If 'my-foo' is an Angular component, then verify that it is included in the '@Component.imports' of this component. 2. If 'my-foo' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@Component.schemas' of this component to suppress this message.`); }); it('should check for unknown properties', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<div [foo]="1">test</div>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Can't bind to 'foo' since it isn't a known property of 'div'.`, ); }); it('should have a descriptive error for unknown properties with an "ng-" prefix', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<div [foo]="1">test</div>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Can't bind to 'foo' since it isn't a known property of 'div'.`, ); }); it('should convert property names when binding special properties', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<label [for]="test">', standalone: false, }) export class FooCmp { test: string = 'test'; } @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); // Should not be an error to bind [for] of <label>, even though the actual property in the // DOM schema. expect(diags.length).toBe(0); }); it('should produce diagnostics for custom-elements-style elements when not using the CUSTOM_ELEMENTS_SCHEMA', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<custom-element [foo]="1">test</custom-element>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toBe(`'custom-element' is not a known element: 1. If 'custom-element' is an Angular component, then verify that it is part of this module. 2. If 'custom-element' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`); expect(diags[1].messageText) .toBe(`Can't bind to 'foo' since it isn't a known property of 'custom-element'. 1. If 'custom-element' is an Angular component and it has 'foo' input, then verify that it is part of this module. 2. If 'custom-element' 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.`); }); it('should not produce
{ "end_byte": 106347, "start_byte": 97937, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_106355_114804
tics for custom-elements-style elements when using the CUSTOM_ELEMENTS_SCHEMA', () => { env.write( 'test.ts', ` import {Component, NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; @Component({ selector: 'blah', template: '<custom-element [foo]="1">test</custom-element>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); }); it('should not produce diagnostics when using the NO_ERRORS_SCHEMA', () => { env.write( 'test.ts', ` import {Component, NgModule, NO_ERRORS_SCHEMA} from '@angular/core'; @Component({ selector: 'blah', template: '<foo [bar]="1"></foo>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], schemas: [NO_ERRORS_SCHEMA], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); }); it('should allow HTML elements inside SVG foreignObject', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: \` <svg> <svg:foreignObject> <xhtml:div>Hello</xhtml:div> </svg:foreignObject> </svg> \`, standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should allow HTML elements without explicit namespace inside SVG foreignObject', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ template: \` <svg> <foreignObject> <div>Hello</div> </foreignObject> </svg> \`, standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should check for unknown elements inside an SVG foreignObject', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: \` <svg> <svg:foreignObject> <xhtml:foo>Hello</xhtml:foo> </svg:foreignObject> </svg> \`, standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`'foo' is not a known element: 1. If 'foo' is an Angular component, then verify that it is part of this module. 2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`); }); it('should check for unknown elements without explicit namespace inside an SVG foreignObject', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: \` <svg> <foreignObject> <foo>Hello</foo> </foreignObject> </svg> \`, standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`'foo' is not a known element: 1. If 'foo' is an Angular component, then verify that it is part of this module. 2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`); }); it('should allow math elements', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` <math> <mfrac> <mn>1</mn> <msqrt> <mn>2</mn> </msqrt> </mfrac> </math> \`, standalone: true, }) export class MathCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); }); // Test both sync and async compilations, see https://github.com/angular/angular/issues/32538 ['sync', 'async'].forEach((mode) => { describe(`error locations [${mode}]`, () => { let driveDiagnostics: () => Promise<ReadonlyArray<ts.Diagnostic>>; beforeEach(() => { if (mode === 'async') { env.enablePreloading(); driveDiagnostics = () => env.driveDiagnosticsAsync(); } else { driveDiagnostics = () => Promise.resolve(env.driveDiagnostics()); } }); it('should be correct for direct templates', async () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', template: \`<p> {{user.does_not_exist}} </p>\`, standalone: false, }) export class TestCmp { user: {name: string}[]; }`, ); const diags = await driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].file!.fileName).toBe(_('/test.ts')); expect(getSourceCodeForDiagnostic(diags[0])).toBe('does_not_exist'); }); it('should be correct for indirect templates', async () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; const TEMPLATE = \`<p> {{user.does_not_exist}} </p>\`; @Component({ selector: 'test', template: TEMPLATE, standalone: false, }) export class TestCmp { user: {name: string}[]; }`, ); const diags = await driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].file!.fileName).toBe(_('/test.ts') + ' (TestCmp template)'); expect(getSourceCodeForDiagnostic(diags[0])).toBe('does_not_exist'); expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![0])).toBe('TEMPLATE'); }); it('should be correct for external templates', async () => { env.write( 'template.html', `<p> {{user.does_not_exist}} </p>`, ); env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test', templateUrl: './template.html', standalone: false, }) export class TestCmp { user: {name: string}[]; }`, ); const diags = await driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].file!.fileName).toBe(_('/template.html')); expect(getSourceCodeForDiagnostic(diags[0])).toBe('does_not_exist'); expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![0])).toBe( `'./template.html'`, ); }); }); }); describe('option compati
{ "end_byte": 114804, "start_byte": 106355, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_114810_121866
verification', () => { beforeEach(() => env.write('index.ts', `export const a = 1;`)); it('should error if "fullTemplateTypeCheck" is false when "strictTemplates" is true', () => { env.tsconfig({fullTemplateTypeCheck: false, strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Angular compiler option "strictTemplates" is enabled, however "fullTemplateTypeCheck" is disabled.', ); }); it('should not error if "fullTemplateTypeCheck" is false when "strictTemplates" is false', () => { env.tsconfig({fullTemplateTypeCheck: false, strictTemplates: false}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not error if "fullTemplateTypeCheck" is not set when "strictTemplates" is true', () => { env.tsconfig({strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not error if "fullTemplateTypeCheck" is true set when "strictTemplates" is true', () => { env.tsconfig({strictTemplates: true}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should error if "strictTemplates" is false when "extendedDiagnostics" is configured', () => { env.tsconfig({strictTemplates: false, extendedDiagnostics: {}}); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Angular compiler option "extendedDiagnostics" is configured, however "strictTemplates" is disabled.', ); }); it('should not error if "strictTemplates" is true when "extendedDiagnostics" is configured', () => { env.tsconfig({strictTemplates: true, extendedDiagnostics: {}}); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); }); it('should not error if "strictTemplates" is false when "extendedDiagnostics" is not configured', () => { env.tsconfig({strictTemplates: false}); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); }); it('should error if "extendedDiagnostics.defaultCategory" is set to an unknown value', () => { env.tsconfig({ extendedDiagnostics: { defaultCategory: 'does-not-exist', }, }); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Angular compiler option "extendedDiagnostics.defaultCategory" has an unknown diagnostic category: "does-not-exist".', ); expect(diags[0].messageText).toContain( ` Allowed diagnostic categories are: warning error suppress `.trim(), ); }); it('should not error if "extendedDiagnostics.defaultCategory" is set to a known value', () => { env.tsconfig({ extendedDiagnostics: { defaultCategory: DiagnosticCategoryLabel.Error, }, }); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); }); it('should error if "extendedDiagnostics.checks" contains an unknown check', () => { env.tsconfig({ extendedDiagnostics: { checks: { doesNotExist: DiagnosticCategoryLabel.Error, }, }, }); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Angular compiler option "extendedDiagnostics.checks" has an unknown check: "doesNotExist".', ); }); it('should not error if "extendedDiagnostics.checks" contains all known checks', () => { env.tsconfig({ extendedDiagnostics: { checks: { [invalidBananaInBoxFactory.name]: DiagnosticCategoryLabel.Error, }, }, }); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); }); it('should error if "extendedDiagnostics.checks" contains an unknown diagnostic category', () => { env.tsconfig({ extendedDiagnostics: { checks: { [invalidBananaInBoxFactory.name]: 'does-not-exist', }, }, }); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( `Angular compiler option "extendedDiagnostics.checks['${invalidBananaInBoxFactory.name}']" has an unknown diagnostic category: "does-not-exist".`, ); expect(diags[0].messageText).toContain( ` Allowed diagnostic categories are: warning error suppress `.trim(), ); }); it('should not error if "extendedDiagnostics.checks" contains all known diagnostic categories', () => { env.tsconfig({ extendedDiagnostics: { checks: { [invalidBananaInBoxFactory.name]: DiagnosticCategoryLabel.Error, }, }, }); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); }); }); describe('stability', () => { beforeEach(() => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '{{expr}}' }) export class TestCmp { expr = 'string'; } `, ); }); // This section tests various scenarios which have more complex ts.Program setups and thus // exercise edge cases of the template type-checker. it('should accept a program with a flat index', () => { // This test asserts that flat indices don't have any negative interactions with the // generation of template type-checking code in the program. env.tsconfig({fullTemplateTypeCheck: true, flatModuleOutFile: 'flat.js'}); expect(env.driveDiagnostics()).toEqual([]); }); it('should not leave referencedFiles in a tagged state', () => { env.enableMultipleCompilations(); env.driveMain(); const sf = getSourceFileOrError(env.getTsProgram(), _('/test.ts')); expect(sf.referencedFiles.map((ref) => ref.fileName)).toEqual([]); }); it('should allow for complete program reuse during incremental compilations', () => { env.enableMultipleCompilations(); env.write('other.ts', `export const VERSION = 1;`); env.driveMain(); const firstProgram = env.getReuseTsProgram(); env.write('other.ts', `export const VERSION = 2;`); env.driveMain(); expectCompleteReuse(env.getTsProgram()); expectCompleteReuse(env.getReuseTsProgram()); }); }); describe('host directive
{ "end_byte": 121866, "start_byte": 114810, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_121872_130618
=> { beforeEach(() => { env.tsconfig({strictTemplates: true}); }); it('should check bindings to host directive inputs', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Directive({ standalone: true, }) class HostDir { @Input() input: number; @Input() otherInput: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['input', 'otherInput: alias']}], standalone: false, }) class Dir {} @Component({ selector: 'test', template: '<div dir [input]="person.name" [alias]="person.age"></div>', standalone: false, }) class TestCmp { person: { name: string; age: number; }; } @NgModule({ declarations: [TestCmp, Dir], }) class Module {} `, ); const messages = env.driveDiagnostics().map((d) => d.messageText); expect(messages).toEqual([ `Type 'string' is not assignable to type 'number'.`, `Type 'number' is not assignable to type 'string'.`, ]); }); it('should check bindings to host directive outputs', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Output, EventEmitter} from '@angular/core'; @Directive({ standalone: true, }) class HostDir { @Output() stringEvent = new EventEmitter<string>(); @Output() numberEvent = new EventEmitter<number>(); } @Directive({ selector: '[dir]', hostDirectives: [ {directive: HostDir, outputs: ['stringEvent', 'numberEvent: numberAlias']} ], standalone: false, }) class Dir {} @Component({ selector: 'test', template: \` <div dir (numberAlias)="handleStringEvent($event)" (stringEvent)="handleNumberEvent($event)"></div> \`, standalone: false, }) class TestCmp { handleStringEvent(event: string): void {} handleNumberEvent(event: number): void {} } @NgModule({ declarations: [TestCmp, Dir], }) class Module {} `, ); const messages = env.driveDiagnostics().map((d) => d.messageText); expect(messages).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should not pick up host directive inputs/outputs that have not been exposed', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Input, Output} from '@angular/core'; @Directive({ standalone: true, }) class HostDir { @Input() input: number; @Output() output: string; } @Directive({ selector: '[dir]', hostDirectives: [HostDir], standalone: false, }) class Dir {} @Component({ selector: 'test', template: '<div dir [input]="person.name" (output)="handleStringEvent($event)"></div>', standalone: false, }) class TestCmp { person: { name: string; }; handleStringEvent(event: string): void {} } @NgModule({ declarations: [TestCmp, Dir], }) class Module {} `, ); const messages = env.driveDiagnostics().map((d) => d.messageText); // These messages are expected to refer to the native // typings since the inputs/outputs haven't been exposed. expect(messages).toEqual([ `Argument of type 'Event' is not assignable to parameter of type 'string'.`, `Can't bind to 'input' since it isn't a known property of 'div'.`, ]); }); it('should check references to host directives', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Output, EventEmitter} from '@angular/core'; @Directive({ standalone: true, exportAs: 'hostDir', }) class HostDir {} @Directive({ selector: '[dir]', hostDirectives: [HostDir], standalone: false, }) class Dir {} @Component({ selector: 'test', template: '<div dir #hostDir="hostDir">{{ render(hostDir) }}</div>', standalone: false, }) class TestCmp { render(input: string): string { return input; } } @NgModule({ declarations: [TestCmp, Dir], }) class Module {} `, ); const messages = env.driveDiagnostics().map((d) => d.messageText); expect(messages).toEqual([ `Argument of type 'HostDir' is not assignable to parameter of type 'string'.`, ]); }); it('should check bindings to inherited host directive inputs', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Directive({ standalone: true }) class HostDirParent { @Input() input: number; @Input() otherInput: string; } @Directive({ standalone: true, }) class HostDir extends HostDirParent {} @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['input', 'otherInput: alias']}], standalone: false, }) class Dir {} @Component({ selector: 'test', template: '<div dir [input]="person.name" [alias]="person.age"></div>', standalone: false, }) class TestCmp { person: { name: string; age: number; }; } @NgModule({ declarations: [TestCmp, Dir], }) class Module {} `, ); const messages = env.driveDiagnostics().map((d) => d.messageText); expect(messages).toEqual([ `Type 'string' is not assignable to type 'number'.`, `Type 'number' is not assignable to type 'string'.`, ]); }); it('should check bindings to inherited host directive outputs', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Output, EventEmitter} from '@angular/core'; @Directive({ standalone: true }) class HostDirParent { @Output() stringEvent = new EventEmitter<string>(); @Output() numberEvent = new EventEmitter<number>(); } @Directive({ standalone: true, }) class HostDir extends HostDirParent {} @Directive({ selector: '[dir]', hostDirectives: [ {directive: HostDir, outputs: ['stringEvent', 'numberEvent: numberAlias']} ], standalone: false, }) class Dir {} @Component({ selector: 'test', template: \` <div dir (numberAlias)="handleStringEvent($event)" (stringEvent)="handleNumberEvent($event)"></div> \`, standalone: false, }) class TestCmp { handleStringEvent(event: string): void {} handleNumberEvent(event: number): void {} } @NgModule({ declarations: [TestCmp, Dir], }) class Module {} `, ); const messages = env.driveDiagnostics().map((d) => d.messageText); expect(messages).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should check bindi
{ "end_byte": 130618, "start_byte": 121872, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_130626_138681
liased host directive inputs', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Directive({ standalone: true, }) class HostDir { @Input('ownInputAlias') input: number; @Input('ownOtherInputAlias') otherInput: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['ownInputAlias', 'ownOtherInputAlias: customAlias']}], standalone: false, }) class Dir {} @Component({ selector: 'test', template: '<div dir [ownInputAlias]="person.name" [customAlias]="person.age"></div>', standalone: false, }) class TestCmp { person: { name: string; age: number; }; } @NgModule({ declarations: [TestCmp, Dir], }) class Module {} `, ); const messages = env.driveDiagnostics().map((d) => d.messageText); expect(messages).toEqual([ `Type 'string' is not assignable to type 'number'.`, `Type 'number' is not assignable to type 'string'.`, ]); }); it('should check bindings to aliased host directive outputs', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Output, EventEmitter} from '@angular/core'; @Directive({ standalone: true, }) class HostDir { @Output('ownStringAlias') stringEvent = new EventEmitter<string>(); @Output('ownNumberAlias') numberEvent = new EventEmitter<number>(); } @Directive({ selector: '[dir]', hostDirectives: [ {directive: HostDir, outputs: ['ownStringAlias', 'ownNumberAlias: customNumberAlias']} ], standalone: false, }) class Dir {} @Component({ selector: 'test', template: \` <div dir (customNumberAlias)="handleStringEvent($event)" (ownStringAlias)="handleNumberEvent($event)"></div> \`, standalone: false, }) class TestCmp { handleStringEvent(event: string): void {} handleNumberEvent(event: number): void {} } @NgModule({ declarations: [TestCmp, Dir], }) class Module {} `, ); const messages = env.driveDiagnostics().map((d) => d.messageText); expect(messages).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('generates diagnostic when the library does not export the host directive', () => { env.tsconfig({ paths: {'post': ['dist/post']}, strictTemplates: true, _enableTemplateTypeChecker: true, }); // export post module and component but not the host directive. This is not valid. We won't // be able to import the host directive for template type checking. env.write( 'dist/post/index.d.ts', ` export { PostComponent, PostModule } from './lib/post.component'; `, ); env.write( 'dist/post/lib/post.component.d.ts', ` import * as i0 from "@angular/core"; export declare class HostBindDirective { static ɵdir: i0.ɵɵDirectiveDeclaration<HostBindDirective, never, never, {}, {}, never, never, true, never>; } export declare class PostComponent { static ɵcmp: i0.ɵɵComponentDeclaration<PostComponent, "lib-post", never, {}, {}, never, never, false, [{ directive: typeof HostBindDirective; inputs: {}; outputs: {}; }]>; } export declare class PostModule { static ɵmod: i0.ɵɵNgModuleDeclaration<PostModule, [typeof PostComponent], never, [typeof PostComponent]>; static ɵinj: i0.ɵɵInjectorDeclaration<PostModule>; } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {PostModule} from 'post'; @Component({ template: '<lib-post />', imports: [PostModule], standalone: true, }) export class Main { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '')).toContain( 'Unable to import symbol HostBindDirective', ); }); it('should check bindings to inherited host directive inputs', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Input} from '@angular/core'; @Directive({ standalone: true, }) class HostDir { @Input() input: number; @Input() otherInput: string; } @Directive({ hostDirectives: [{directive: HostDir, inputs: ['input', 'otherInput: alias']}], standalone: false, }) class Parent {} @Directive({ selector: '[dir]', standalone: false, }) class Dir extends Parent {} @Component({ selector: 'test', template: '<div dir [input]="person.name" [alias]="person.age"></div>', standalone: false, }) class TestCmp { person: { name: string; age: number; }; } @NgModule({ declarations: [TestCmp, Dir], }) class Module {} `, ); const messages = env.driveDiagnostics().map((d) => d.messageText); expect(messages).toEqual([ `Type 'string' is not assignable to type 'number'.`, `Type 'number' is not assignable to type 'string'.`, ]); }); it('should check bindings to inherited host directive outputs', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule, Output, EventEmitter} from '@angular/core'; @Directive({ standalone: true, }) class HostDir { @Output() stringEvent = new EventEmitter<string>(); @Output() numberEvent = new EventEmitter<number>(); } @Directive({ hostDirectives: [ {directive: HostDir, outputs: ['stringEvent', 'numberEvent: numberAlias']} ], standalone: false, }) class Parent {} @Directive({ selector: '[dir]', standalone: false, }) class Dir extends Parent {} @Component({ selector: 'test', template: \` <div dir (numberAlias)="handleStringEvent($event)" (stringEvent)="handleNumberEvent($event)"></div> \`, standalone: false, }) class TestCmp { handleStringEvent(event: string): void {} handleNumberEvent(event: number): void {} } @NgModule({ declarations: [TestCmp, Dir], }) class Module {} `, ); const messages = env.driveDiagnostics().map((d) => d.messageText); expect(messages).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); }); describe('deferred blocks', () => {
{ "end_byte": 138681, "start_byte": 130626, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_138687_143385
it('should check bindings inside deferred blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @defer { {{does_not_exist_main}} } @placeholder { {{does_not_exist_placeholder}} } @loading { {{does_not_exist_loading}} } @error { {{does_not_exist_error}} } \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist_main' does not exist on type 'Main'.`, `Property 'does_not_exist_placeholder' does not exist on type 'Main'.`, `Property 'does_not_exist_loading' does not exist on type 'Main'.`, `Property 'does_not_exist_error' does not exist on type 'Main'.`, ]); }); it('should check `when` trigger expression', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @defer (when isVisible() || does_not_exist) {Hello} \`, standalone: true, }) export class Main { isVisible() { return true; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist' does not exist on type 'Main'.`, ]); }); it('should check `prefetch when` trigger expression', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @defer (prefetch when isVisible() || does_not_exist) {Hello} \`, standalone: true, }) export class Main { isVisible() { return true; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist' does not exist on type 'Main'.`, ]); }); it('should check `hydrate when` trigger expression', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @defer (hydrate when isVisible() || does_not_exist) {Hello} \`, standalone: true, }) export class Main { isVisible() { return true; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist' does not exist on type 'Main'.`, ]); }); it('should report if a deferred trigger reference does not exist', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @defer (on viewport(does_not_exist)) {Hello} \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '')).toContain( 'Trigger cannot find reference "does_not_exist".', ); }); it('should report if a deferred trigger reference is in a different embedded view', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @defer (on viewport(trigger)) {Hello} <ng-template> <button #trigger></button> </ng-template> \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '')).toContain( 'Trigger cannot find reference "trigger".', ); }); }); describe('conditional blocks', () =>
{ "end_byte": 143385, "start_byte": 138687, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_143391_152260
it('should check bindings inside if blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (expr) { {{does_not_exist_main}} } @else if (expr1) { {{does_not_exist_one}} } @else if (expr2) { {{does_not_exist_two}} } @else { {{does_not_exist_else}} } \`, standalone: true, }) export class Main { expr = false; expr1 = false; expr2 = false; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist_main' does not exist on type 'Main'.`, `Property 'does_not_exist_one' does not exist on type 'Main'.`, `Property 'does_not_exist_two' does not exist on type 'Main'.`, `Property 'does_not_exist_else' does not exist on type 'Main'.`, ]); }); it('should check bindings of if block expressions', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (does_not_exist_main) { main } @else if (does_not_exist_one) { one } @else if (does_not_exist_two) { two } \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist_main' does not exist on type 'Main'.`, `Property 'does_not_exist_one' does not exist on type 'Main'.`, `Property 'does_not_exist_two' does not exist on type 'Main'.`, ]); }); it('should check aliased if block expression', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \`@if (value === 1; as alias) { {{acceptsNumber(alias)}} }\`, standalone: true, }) export class Main { value = 1; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'boolean' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type of the if alias', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \`@if (value; as alias) { {{acceptsNumber(alias)}} }\`, standalone: true, }) export class Main { value: 'one' | 0 = 0; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type of the if alias used in a listener', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \`@if (value; as alias) { <button (click)="acceptsNumber(alias)"></button> }\`, standalone: true, }) export class Main { value: 'one' | 0 = 0; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow types inside the expression, even if aliased', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \`@if (value; as alias) { {{ value.length }} }\`, standalone: true, }) export class Main { value!: string|undefined; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should narrow signal reads when aliased', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \`@if (value(); as alias) { {{ alias.length }} }\`, standalone: true, }) export class Main { value!: () => string|undefined; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not expose the aliased expression outside of the main block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (value === 0; as alias) { main block } @else { {{alias}} } \`, standalone: true, }) export class Main { value = 1; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'alias' does not exist on type 'Main'.`, ]); }); it('should expose alias to nested if blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (value === 1; as alias) { @if (alias) { {{acceptsNumber(alias)}} } } \`, standalone: true, }) export class Main { value = 1; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'boolean' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type inside if blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (expr === 1) { main block } @else { {{acceptsNumber(expr)}} } \`, standalone: true, }) export class Main { expr: 'hello' | 1 = 'hello'; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type in listeners inside if blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (expr === 'hello') { <button (click)="acceptsNumber(expr)"></button> } \`, standalone: true, }) export class Main { expr: 'hello' | 1 = 'hello'; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type in list
{ "end_byte": 152260, "start_byte": 143391, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_152268_161604
side else if blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (expr === 1) { One } @else if (expr === 'hello') { <button (click)="acceptsNumber(expr)"></button> } \`, standalone: true, }) export class Main { expr: 'hello' | 1 | 2 = 'hello'; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type in listeners inside else blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (expr === 1) { One } @else if (expr === 2) { Two } @else { <button (click)="acceptsNumber(expr)"></button> } \`, standalone: true, }) export class Main { expr: 'hello' | 1 | 2 = 'hello'; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should produce a single diagnostic for an invalid expression of an if block containing a event listener', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (does_not_exist) { <button (click)="test()"></button> } \`, standalone: true, }) export class Main { test() {} } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist' does not exist on type 'Main'.`, ]); }); it('should check bindings inside switch blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @switch (expr) { @case (1) { {{does_not_exist_one}} } @case (2) { {{does_not_exist_two}} } @default { {{does_not_exist_default}} } } \`, standalone: true, }) export class Main { expr: any; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist_one' does not exist on type 'Main'.`, `Property 'does_not_exist_two' does not exist on type 'Main'.`, `Property 'does_not_exist_default' does not exist on type 'Main'.`, ]); }); it('should check expressions of switch blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @switch (does_not_exist_main) { @case (does_not_exist_case) { One } } \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist_main' does not exist on type 'Main'.`, `Property 'does_not_exist_case' does not exist on type 'Main'.`, ]); }); it('should only produce one diagnostic if the switch expression has an error', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @switch (does_not_exist_main) { @case (1) { One } @case (2) { Two } } \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist_main' does not exist on type 'Main'.`, ]); }); it('should only produce one diagnostic if the case expression has an error and it contains an event listener', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @switch (value) { @case (does_not_exist) { <button (click)="test()"></button> } @default { <button (click)="test()"></button> } } \`, standalone: true, }) export class Main { value = 'zero'; test() {} } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist' does not exist on type 'Main'.`, ]); }); it('should check a switch block that only has a default case', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @switch (expr) { @default { {{acceptsNumber(expr)}} } } \`, standalone: true, }) export class Main { expr: 'hello' | 1 = 'hello'; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'.`, ]); }); it('should narrow the type inside switch cases', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @switch (expr) { @case (1) { One } @default { {{acceptsNumber(expr)}} } } \`, standalone: true, }) export class Main { expr: 'hello' | 1 = 'hello'; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the switch type based on a field', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; export interface Base { type: 'foo' | 'bar' } export interface Foo extends Base { type: 'foo'; foo: string; } export interface Bar extends Base { type: 'bar'; bar: number; } @Component({ template: \` @switch (value.type) { @case ('foo') { {{ acceptsNumber(value.foo) }} } } \`, standalone: true, }) export class Main { value: Foo | Bar = { type: 'foo', foo: 'foo' }; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should produce a diagnostic if
{ "end_byte": 161604, "start_byte": 152268, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_161612_164294
and @case have different types', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @switch (expr) { @case (1) { {{expr}} } } \`, standalone: true, }) export class Main { expr = true; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Type 'number' is not comparable to type 'boolean'.`, ]); }); it('should narrow the type in listener inside switch cases with expressions', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @switch (expr) { @case ('hello') { <button (click)="acceptsNumber(expr)"></button> } } \`, standalone: true, }) export class Main { expr: 'hello' | 1 = 'hello'; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type in listener inside switch default case', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @switch (expr) { @case (1) { One } @case (2) { Two } @default { <button (click)="acceptsNumber(expr)"></button> } } \`, standalone: true, }) export class Main { expr: 1 | 2 | 'hello' = 'hello'; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); }); describe('for loop blocks', () => {
{ "end_byte": 164294, "start_byte": 161612, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_164300_173074
beforeEach(() => { // `fullTemplateTypeCheck: true` is necessary so content inside `ng-template` is checked. env.tsconfig({fullTemplateTypeCheck: true}); }); it('should check bindings inside of for loop blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (item of items; track item) { {{does_not_exist_main}} } @empty { {{does_not_exist_empty}} } \`, }) export class Main { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist_main' does not exist on type 'Main'.`, `Property 'does_not_exist_empty' does not exist on type 'Main'.`, ]); }); it('should check the expression of a for loop block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '@for (item of does_not_exist; track item) {hello}', }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist' does not exist on type 'Main'.`, ]); }); it('should check the type of the item of a for loop block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '@for (item of items; track item) { {{acceptsString(item)}} }', }) export class Main { items = [1, 2, 3]; acceptsString(value: string) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should check the type of implicit variables for loop block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (item of items; track item) { {{acceptsString($index)}} {{acceptsString($first)}} {{acceptsString($last)}} {{acceptsString($even)}} {{acceptsString($odd)}} {{acceptsString($count)}} } \`, }) export class Main { items = []; acceptsString(value: string) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should check the type of aliased implicit variables for loop block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (item of items; track item; let i = $index, f = $first, l = $last, e = $even, o = $odd, c = $count) { {{acceptsString(i)}} {{acceptsString(f)}} {{acceptsString(l)}} {{acceptsString(e)}} {{acceptsString(o)}} {{acceptsString(c)}} } \`, }) export class Main { items = []; acceptsString(value: string) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should not expose variables from the main block to the empty block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (item of items; track item) { Hello } @empty { {{item}} {{$index}} } \`, }) export class Main { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'item' does not exist on type 'Main'. Did you mean 'items'?`, `Property '$index' does not exist on type 'Main'.`, ]); }); it('should continue exposing implicit loop variables under their old names when they are aliased', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '@for (item of items; track item; let alias = $index) { {{acceptsString($index)}} }', }) export class Main { items = []; acceptsString(str: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should not be able to write to loop template variables', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (item of items; track item) { <button (click)="$index = 1"></button> } \`, }) export class Main { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot use variable '$index' as the left-hand side of an assignment expression. Template variables are read-only.`, ]); }); it('should not be able to write to loop template variables in a two-way binding', () => { env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[twoWayDir]', standalone: true }) export class TwoWayDir { @Input() value: number = 0; @Output() valueChange: EventEmitter<number> = new EventEmitter(); } @Component({ template: \` @for (item of items; track item) { <button twoWayDir [(value)]="$index"></button> } \`, standalone: true, imports: [TwoWayDir] }) export class Main { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot use a non-signal variable '$index' in a two-way binding expression. Template variables are read-only.`, ]); }); it('should allow writes to signal-
{ "end_byte": 173074, "start_byte": 164300, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_173082_182303
mplate variables in two-way bindings', () => { env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter, signal} from '@angular/core'; @Directive({ selector: '[twoWayDir]', standalone: true }) export class TwoWayDir { @Input() value: number = 0; @Output() valueChange: EventEmitter<number> = new EventEmitter(); } @Component({ template: \` @for (current of signals; track current) { <button twoWayDir [(value)]="current"></button> } \`, standalone: true, imports: [TwoWayDir] }) export class Main { signals = [signal(1)]; } `, ); const diags = env.driveDiagnostics(); expect(diags).toEqual([]); }); it('should check the track expression of a for loop block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '@for (item of items; track does_not_exist) {}', }) export class Main { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist' does not exist on type 'Main'.`, ]); }); it('should check the item in the tracking expression', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '@for (item of items; track trackingFn(item)) {}', }) export class Main { items = [1, 2, 3]; trackingFn(value: string) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should check $index in the tracking expression', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '@for (item of items; track trackingFn($index)) {}', }) export class Main { items = []; trackingFn(value: string) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should check an aliased $index in the tracking expression', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '@for (item of items; let i = $index; track trackingFn(i)) {}', }) export class Main { items = []; trackingFn(value: string) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should not allow usages of loop context variables inside the tracking expression', () => { env.write( '/test.ts', ` import { Component } from '@angular/core'; @Component({ selector: 'test-cmp', standalone: true, template: '@for (item of items; track $index + $count) {}', }) export class TestCmp { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot access '$count' inside of a track expression. Only 'item', '$index' and ` + `properties on the containing component are available to this expression.`, ]); }); it('should not allow usages of aliased loop context variables inside the tracking expression', () => { env.write( '/test.ts', ` import { Component } from '@angular/core'; @Component({ selector: 'test-cmp', standalone: true, template: '@for (item of items; let c = $count; track $index + c) {}', }) export class TestCmp { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot access 'c' inside of a track expression. Only 'item', '$index' and ` + `properties on the containing component are available to this expression.`, ]); }); it('should not allow usages of local references within the same template inside the tracking expression', () => { env.write( '/test.ts', ` import { Component } from '@angular/core'; @Component({ selector: 'test-cmp', standalone: true, template: \` <input #ref/> @for (item of items; track $index + ref.value) {} \`, }) export class TestCmp { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot access 'ref' inside of a track expression. Only 'item', '$index' and ` + `properties on the containing component are available to this expression.`, ]); }); it('should not allow usages of local references outside of the template in the tracking expression', () => { env.write( '/test.ts', ` import { Component } from '@angular/core'; @Component({ selector: 'test-cmp', standalone: true, template: \` <input #ref/> <ng-template> @for (item of items; track $index + ref.value) {} </ng-template> \`, }) export class TestCmp { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot access 'ref' inside of a track expression. Only 'item', '$index' and ` + `properties on the containing component are available to this expression.`, ]); }); it('should not allow usages of parent template variables inside the tracking expression', () => { env.write( '/test.ts', ` import { Component } from '@angular/core'; @Component({ selector: 'test-cmp', standalone: true, template: \` <ng-template let-foo> @for (item of items; track $index + foo.value) {} </ng-template> \`, }) export class TestCmp { items: {value: number}[] = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot access 'foo' inside of a track expression. Only 'item', '$index' and ` + `properties on the containing component are available to this expression.`, ]); }); it('should not allow usages of parent loop variables inside the tracking expression', () => { env.write( '/test.ts', ` import { Component } from '@angular/core'; @Component({ selector: 'test-cmp', standalone: true, template: \` @for (parent of items; track $index) { @for (item of parent.items; track parent) {} } \`, }) export class TestCmp { items: {items: any[]}[] = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot access 'parent' inside of a track expression. Only 'item', '$index' and ` + `properties on the containing component are available to this expression.`, ]); }); it('should not allow usages of ali
{ "end_byte": 182303, "start_byte": 173082, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_182311_186888
` block variables inside the tracking expression', () => { env.write( '/test.ts', ` import { Component } from '@angular/core'; @Component({ selector: 'test-cmp', standalone: true, template: \` @if (expr; as alias) { @for (item of items; track $index + alias) {} } \`, }) export class TestCmp { expr = 1; items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot access 'alias' inside of a track expression. Only 'item', '$index' and ` + `properties on the containing component are available to this expression.`, ]); }); it('should not allow usages of pipes inside the tracking expression', () => { env.write( '/test.ts', ` import { Component, Pipe } from '@angular/core'; @Pipe({name: 'test', standalone: true}) export class TestPipe { transform(value: any) { return value; } } @Component({ selector: 'test-cmp', standalone: true, imports: [TestPipe], template: '@for (item of items; track item | test) {}', }) export class TestCmp { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Error: Illegal State: Pipes are not allowed in this context', ); }); it('should allow nullable values in loop expression', () => { env.write( 'test.ts', ` import {Component, Pipe} from '@angular/core'; @Pipe({name: 'fakeAsync', standalone: true}) export class FakeAsyncPipe { transform<T>(value: Iterable<T>): Iterable<T> | null | undefined { return null; } } @Component({ template: \` @for (item of items | fakeAsync; track item) { {{item}} } \`, standalone: true, imports: [FakeAsyncPipe] }) export class Main { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([]); }); it('should enforce that the loop expression is iterable', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (item of items; track item) { {{item}} } \`, }) export class Main { items = 123; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Type 'number' must have a '[Symbol.iterator]()' method that returns an iterator.`, ]); }); it('should check for loop variables with the same name as built-in globals', () => { // strictTemplates are necessary so the event listener is checked. env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component, Directive, Input} from '@angular/core'; @Directive({ standalone: true, selector: '[dir]' }) export class Dir { @Input('dir') value!: string; } @Component({ standalone: true, imports: [Dir], template: \` @for (document of documents; track document) { <button [dir]="document" (click)="$event.stopPropagation()"></button> } \`, }) export class Main { documents = [1, 2, 3]; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Type 'number' is not assignable to type 'string'.`, ]); }); }); describe('control flow content proje
{ "end_byte": 186888, "start_byte": 182311, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_186894_195552
diagnostics', () => { it('should report when an @if block prevents an element from being projected', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content/> <ng-content select="bar, [foo]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @if (true) { <div foo></div> breaks projection } </comp> \`, }) class TestCmp {} `, ); const diags = env .driveDiagnostics() .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '')); expect(diags.length).toBe(1); expect(diags[0]).toContain( `Node matches the "bar, [foo]" slot of the "Comp" component, but will ` + `not be projected into the specific slot because the surrounding @if has more than one node at its root.`, ); }); it('should report when an @if block prevents a template from being projected', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content/> <ng-content select="bar, [foo]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @if (true) { <ng-template foo></ng-template> breaks projection } </comp> \`, }) class TestCmp {} `, ); const diags = env .driveDiagnostics() .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '')); expect(diags.length).toBe(1); expect(diags[0]).toContain( `Node matches the "bar, [foo]" slot of the "Comp" component, but will ` + `not be projected into the specific slot because the surrounding @if has more than one node at its root.`, ); }); it('should report when an @else block prevents content projection', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content select="[foo]"/> <ng-content select="[bar]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @if (expr) { <div foo></div> } @else { <div bar></div> breaks projection } </comp> \`, }) class TestCmp { expr = 0; } `, ); const diags = env .driveDiagnostics() .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '')); expect(diags.length).toBe(1); expect(diags[0]).toContain( `Node matches the "[bar]" slot of the "Comp" component, but will ` + `not be projected into the specific slot because the surrounding @else has more than one node at its root.`, ); }); it('should report when an @else if block prevents content projection', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content select="[foo]"/> <ng-content select="[bar]"/> <ng-content select="[baz]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @if (expr === 1) { <div foo></div> } @else if (expr === 2) { <div bar></div> breaks projection } @else { <div baz></div> } </comp> \`, }) class TestCmp { expr = 0; } `, ); const diags = env .driveDiagnostics() .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '')); expect(diags.length).toBe(1); expect(diags[0]).toContain( `Node matches the "[bar]" slot of the "Comp" component, but will ` + `not be projected into the specific slot because the surrounding @else if has more than one node at its root.`, ); }); it('should report when an @for block prevents content from being projected', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content/> <ng-content select="bar, [foo]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @for (i of [1, 2, 3]; track i) { <div foo></div> breaks projection } </comp> \`, }) class TestCmp {} `, ); const diags = env .driveDiagnostics() .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '')); expect(diags.length).toBe(1); expect(diags[0]).toContain( `Node matches the "bar, [foo]" slot of the "Comp" component, but will ` + `not be projected into the specific slot because the surrounding @for has more than one node at its root.`, ); }); it('should report when an @empty block prevents content from being projected', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content/> <ng-content select="bar, [foo]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @for (i of [1, 2, 3]; track i) { } @empty { <div foo></div> breaks projection } </comp> \`, }) class TestCmp {} `, ); const diags = env .driveDiagnostics() .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '')); expect(diags.length).toBe(1); expect(diags[0]).toContain( `Node matches the "bar, [foo]" slot of the "Comp" component, but will ` + `not be projected into the specific slot because the surrounding @empty has more than one node at its root.`, ); }); it('should report nodes that are targeting different slots but cannot be projected', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content select="[foo]"/> <ng-content select="[bar]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @if (true) { <div foo></div> <div bar></div> } </comp> \`, }) class TestCmp {} `, ); const diags = env .driveDiagnostics() .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '')); expect(diags.length).toBe(2); expect(diags[0]).toContain( `Node matches the "[foo]" slot of the "Comp" component, but will not be projected`, ); expect(diags[1]).toContain( `Node matches the "[bar]" slot of the "Comp" component, but will not be projected`, ); }); it('should report nodes that are t
{ "end_byte": 195552, "start_byte": 186894, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_195560_205051
the same slot but cannot be projected', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content select="[foo]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @if (true) { <div foo></div> <span foo></span> } </comp> \`, }) class TestCmp {} `, ); const diags = env .driveDiagnostics() .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '')); expect(diags.length).toBe(2); expect(diags[0]).toContain( `Node matches the "[foo]" slot of the "Comp" component, but will not be projected`, ); expect(diags[1]).toContain( `Node matches the "[foo]" slot of the "Comp" component, but will not be projected`, ); }); it('should report when preserveWhitespaces may affect content projection', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content select="[foo]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], preserveWhitespaces: true, template: \` <comp> @if (true) { <div foo></div> } </comp> \`, }) class TestCmp {} `, ); const diags = env .driveDiagnostics() .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '')); expect(diags.length).toBe(1); expect(diags[0]).toContain(`Node matches the "[foo]" slot of the "Comp" component`); expect(diags[0]).toContain( `Note: the host component has \`preserveWhitespaces: true\` which may cause ` + `whitespace to affect content projection.`, ); }); it('should not report when there is only one root node', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content select="[foo]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @if (true) { <div foo></div> } </comp> \`, }) class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not report when there are comments at the root of the control flow node', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content select="[foo]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @if (true) { <!-- before --> <div foo></div> <!-- after --> } </comp> \`, }) class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not report when the component only has a catch-all slot', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @if (true) { <div foo></div> breaks projection } </comp> \`, }) class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should allow the content projection diagnostic to be disabled individually', () => { env.tsconfig({ extendedDiagnostics: { checks: { controlFlowPreventingContentProjection: DiagnosticCategoryLabel.Suppress, }, }, }); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content/> <ng-content select="bar, [foo]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @if (true) { <div foo></div> breaks projection } </comp> \`, }) class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should allow the content projection diagnostic to be disabled via `defaultCategory`', () => { env.tsconfig({ extendedDiagnostics: { defaultCategory: DiagnosticCategoryLabel.Suppress, }, }); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content/> <ng-content select="bar, [foo]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @if (true) { <div foo></div> breaks projection } </comp> \`, }) class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should report when an @case block prevents an element from being projected', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content/> <ng-content select="bar, [foo]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @switch (expr) { @case (1) { <div foo></div> breaks projection } } </comp> \`, }) class TestCmp { expr = 1; } `, ); const diags = env .driveDiagnostics() .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '')); expect(diags.length).toBe(1); expect(diags[0]).toContain( `Node matches the "bar, [foo]" slot of the "Comp" component, but will ` + `not be projected into the specific slot because the surrounding @case has more than one node at its root.`, ); }); it('should report when an @default block prevents an element from being projected', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp', template: '<ng-content select="[foo]"/> <ng-content select="[bar]"/>', standalone: true, }) class Comp {} @Component({ standalone: true, imports: [Comp], template: \` <comp> @switch (expr) { @case (1) { <div foo></div> } @default { <div bar></div> breaks projection } } </comp> \`, }) class TestCmp { expr = 2; } `, ); const diags = env .driveDiagnostics() .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '')); expect(diags.length).toBe(1); expect(diags[0]).toContain( `Node matches the "[bar]" slot of the "Comp" component, but will ` + `not be projected into the specific slot because the surrounding @default has more than one node at its root.`, ); }); }); describe('@let declarations', () =>
{ "end_byte": 205051, "start_byte": 195560, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_205057_214278
beforeEach(() => env.tsconfig({ strictTemplates: true, extendedDiagnostics: { checks: { // Suppress the diagnostic for unused @let since some of the error cases // we're checking for here also qualify as being unused which adds noise. unusedLetDeclaration: 'suppress', }, }, }), ); it('should infer the type of a let declaration', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let one = 1; {{acceptsString(one)}} \`, standalone: true, }) export class Main { acceptsString(value: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getSourceCodeForDiagnostic(diags[0])).toBe('one'); expect(diags[0].messageText).toBe( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); }); it('should infer the type of a nested let declaration', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` <div> @let one = 1; <span>{{acceptsString(one)}}</span> </div> \`, standalone: true, }) export class Main { acceptsString(value: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getSourceCodeForDiagnostic(diags[0])).toBe('one'); expect(diags[0].messageText).toBe( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); }); it('should check the expression of a let declaration', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = {} + 1; \`, standalone: true, }) export class Main { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getSourceCodeForDiagnostic(diags[0])).toBe('{} + 1'); expect(diags[0].messageText).toBe( `Operator '+' cannot be applied to types '{}' and 'number'.`, ); }); it('should narrow the type of a let declaration used directly in the template', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = cond ? 1 : 'one'; @if (value === 1) { {{expectsString(value)}} } \`, standalone: true, }) export class Main { cond: boolean = true; expectsString(value: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getSourceCodeForDiagnostic(diags[0])).toBe('value'); expect(diags[0].messageText).toBe( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); }); it('should narrow the type of a let declaration inside an event listener', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = cond ? 1 : 'one'; @if (value === 1) { <button (click)="expectsString(value)">Click me</button> } \`, standalone: true, }) export class Main { cond: boolean = true; expectsString(value: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getSourceCodeForDiagnostic(diags[0])).toBe('value'); expect(diags[0].messageText).toBe( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); }); it('should be able to access the let declaration from a parent embedded view', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` <ng-template> @let value = 1; <ng-template> @if (true) { @switch (1) { @case (1) { <ng-template>{{expectsString(value)}}</ng-template> } } } </ng-template> </ng-template> \`, standalone: true, }) export class Main { expectsString(value: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); }); it('should not be able to access a let declaration from a child embedded view', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (true) { @let value = 1; } {{value}} \`, standalone: true, }) export class Main { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Property 'value' does not exist on type 'Main'.`); }); it('should not be able to access a let declaration from a sibling embedded view', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (true) { @let value = 1; } @if (true) { {{value}} } \`, standalone: true, }) export class Main { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Property 'value' does not exist on type 'Main'.`); }); it('should give precedence to a local let declaration over a component property', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = 1; {{expectsString(value)}} \`, standalone: true, }) export class Main { value = 'one'; expectsString(value: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); }); it('should give precedence to a local let declaration over one from a parent view', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = 'one'; @if (true) { @let value = 1; {{expectsString(value)}} } \`, standalone: true, }) export class Main { expectsString(value: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); }); it('should not allow multiple @let declarations with the same name within a scope', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (true) { @let value = 1; @let value = 'one'; {{value}} } \`, standalone: true, }) export class Main { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot declare @let called 'value' as there is another symbol in the template with the same name.`, ); }); it('should not allow @let declarat
{ "end_byte": 214278, "start_byte": 205057, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_214286_223722
the same name as a local reference defined before it', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` <input #value> @let value = 1; {{value}} \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot declare @let called 'value' as there is another symbol in the template with the same name.`, ); }); it('should not allow @let declaration with the same name as a local reference defined after it', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = 1; <input #value> {{value}} \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot declare @let called 'value' as there is another symbol in the template with the same name.`, ); }); it('should not allow @let declaration with the same name as a template variable', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; import {CommonModule} from '@angular/common'; @Component({ template: \` <div *ngIf="x as value"> @let value = 1; {{value}} </div> \`, standalone: true, imports: [CommonModule], }) export class Main { x!: unknown; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot declare @let called 'value' as there is another symbol in the template with the same name.`, ); }); it('should allow @let declaration with the same name as a local reference defined in a parent view', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` <input #value> @if (true) { @let value = 1; {{value}} } \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not allow a let declaration to be referenced before it is defined', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` {{value}} @let value = 1; \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot read @let declaration 'value' before it has been defined.`, ); }); it('should not allow a let declaration to be referenced before it is defined inside a child view', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` <ng-template> {{value}} @let value = 1; </ng-template> \`, standalone: true, }) export class Main { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot read @let declaration 'value' before it has been defined.`, ); }); it('should not be able to access let declarations via `this`', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = 1; {{this.value}} \`, standalone: true, }) export class Main { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Property 'value' does not exist on type 'Main'.`); }); it('should not allow a let declaration to refer to itself', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = value; \`, standalone: true, }) export class Main { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot read @let declaration 'value' before it has been defined.`, ); }); it('should produce a single diagnostic if a @let declaration refers to properties on itself', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = value.a.b.c; \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot read @let declaration 'value' before it has been defined.`, ); }); it('should produce a single diagnostic if a @let declaration invokes itself', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = value(); \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot read @let declaration 'value' before it has been defined.`, ); }); it('should allow event listeners to refer to a declaration before it has been defined', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` <button (click)="expectsString(value)">Click me</button> @let value = 1; \`, standalone: true, }) export class Main { expectsString(value: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); }); it('should allow child views to refer to a declaration before it has been defined', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (true) { {{value}} } @let value = 1; \`, standalone: true, }) export class Main { expectsString(value: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not allow a let declaration value to be changed', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = 1; <button (click)="value = 2">Click me</button> \`, standalone: true, }) export class Main { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Cannot assign to @let declaration 'value'.`); }); it('should not allow a let declaration value to be changed through a `this` access', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @let value = 1; <button (click)="this.value = 2">Click me</button> \`, standalone: true, }) export class Main { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Property 'value' does not exist on type 'Main'.`); }); it('should not be able to write to
{ "end_byte": 223722, "start_byte": 214286, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_223730_227980
laration in a two-way binding', () => { env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[twoWayDir]', standalone: true }) export class TwoWayDir { @Input() value: number = 0; @Output() valueChange: EventEmitter<number> = new EventEmitter(); } @Component({ template: \` @let nonWritable = 1; <button twoWayDir [(value)]="nonWritable"></button> \`, standalone: true, imports: [TwoWayDir] }) export class Main { } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot use non-signal @let declaration 'nonWritable' in a two-way binding expression. @let declarations are read-only.`, ]); }); it('should allow two-way bindings to signal-based let declarations', () => { env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter, signal} from '@angular/core'; @Directive({ selector: '[twoWayDir]', standalone: true }) export class TwoWayDir { @Input() value: number = 0; @Output() valueChange: EventEmitter<number> = new EventEmitter(); } @Component({ template: \` @let writable = signalValue; <button twoWayDir [(value)]="writable"></button> \`, standalone: true, imports: [TwoWayDir] }) export class Main { signalValue = signal(1); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should report @let declaration used in the expression of a @if block before it is defined', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (value) { Hello } @let value = 123; \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot read @let declaration 'value' before it has been defined.`, ); }); it('should report @let declaration used in the expression of a @for block before it is defined', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (current of value; track $index) { {{current}} } @let value = [1, 2, 3]; \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot read @let declaration 'value' before it has been defined.`, ); }); it('should report @let declaration used in the expression of a @switch block before it is defined', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @switch (value) { @case (123) { Hello } } @let value = [1, 2, 3]; \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Cannot read @let declaration 'value' before it has been defined.`, ); }); }); describe('unused standalone imports'
{ "end_byte": 227980, "start_byte": 223730, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_227986_236814
> { it('should report when a directive is not used within a template', () => { env.write( 'used.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[used]', standalone: true}) export class UsedDir {} `, ); env.write( 'unused.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[unused]', standalone: true}) export class UnusedDir {} `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {UsedDir} from './used'; import {UnusedDir} from './unused'; @Component({ template: \` <section> <div></div> <span used></span> </section> \`, standalone: true, imports: [UsedDir, UnusedDir] }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe('Imports array contains unused imports'); expect(diags[0].relatedInformation?.length).toBe(1); expect(diags[0].relatedInformation![0].messageText).toBe( 'Directive "UnusedDir" is not used within the template', ); }); it('should report when a pipe is not used within a template', () => { env.write( 'used.ts', ` import {Pipe} from '@angular/core'; @Pipe({name: 'used', standalone: true}) export class UsedPipe { transform(value: number) { return value * 2; } } `, ); env.write( 'unused.ts', ` import {Pipe} from '@angular/core'; @Pipe({name: 'unused', standalone: true}) export class UnusedPipe { transform(value: number) { return value * 2; } } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {UsedPipe} from './used'; import {UnusedPipe} from './unused'; @Component({ template: \` <section> <div></div> <span [attr.id]="1 | used"></span> </section> \`, standalone: true, imports: [UsedPipe, UnusedPipe] }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe('Imports array contains unused imports'); expect(diags[0].relatedInformation?.length).toBe(1); expect(diags[0].relatedInformation?.[0].messageText).toBe( 'Pipe "UnusedPipe" is not used within the template', ); }); it('should not report imports only used inside @defer blocks', () => { env.write( 'test.ts', ` import {Component, Directive, Pipe} from '@angular/core'; @Directive({selector: '[used]', standalone: true}) export class UsedDir {} @Pipe({name: 'used', standalone: true}) export class UsedPipe { transform(value: number) { return value * 2; } } @Component({ template: \` <section> @defer (on idle) { <div used></div> <span [attr.id]="1 | used"></span> } </section> \`, standalone: true, imports: [UsedDir, UsedPipe] }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should report when all imports in an import array are not used', () => { env.write( 'test.ts', ` import {Component, Directive, Pipe} from '@angular/core'; @Directive({selector: '[unused]', standalone: true}) export class UnusedDir {} @Pipe({name: 'unused', standalone: true}) export class UnusedPipe { transform(value: number) { return value * 2; } } @Component({ template: '', standalone: true, imports: [UnusedDir, UnusedPipe] }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe('All imports are unused'); expect(diags[0].relatedInformation).toBeFalsy(); }); it('should not report unused imports coming from modules', () => { env.write( 'module.ts', ` import {Directive, NgModule} from '@angular/core'; @Directive({ selector: '[unused-from-module]', standalone: false, }) export class UnusedDirFromModule {} @NgModule({ declarations: [UnusedDirFromModule], exports: [UnusedDirFromModule] }) export class UnusedModule {} `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {UnusedModule} from './module'; @Component({ template: '', standalone: true, imports: [UnusedModule] }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should be able to opt out for checking for unused imports via the tsconfig', () => { env.tsconfig({ extendedDiagnostics: { checks: { unusedStandaloneImports: DiagnosticCategoryLabel.Suppress, }, }, }); env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Directive({selector: '[unused]', standalone: true}) export class UnusedDir {} @Component({ template: '', standalone: true, imports: [UnusedDir] }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should unused imports from external modules', () => { // Note: we don't use the existing fake `@angular/common`, // because all the declarations there are non-standalone. env.write( 'node_modules/fake-common/index.d.ts', ` import * as i0 from '@angular/core'; export declare class NgIf { static ɵdir: i0.ɵɵDirectiveDeclaration<NgIf<any, any>, "[ngIf]", never, {}, {}, never, never, true, never>; static ɵfac: i0.ɵɵFactoryDeclaration<NgIf<any, any>, never>; } export declare class NgFor { static ɵdir: i0.ɵɵDirectiveDeclaration<NgFor<any, any>, "[ngFor]", never, {}, {}, never, never, true, never>; static ɵfac: i0.ɵɵFactoryDeclaration<NgFor<any, any>, never>; } export class PercentPipe { static ɵfac: i0.ɵɵFactoryDeclaration<PercentPipe, never>; static ɵpipe: i0.ɵɵPipeDeclaration<PercentPipe, "percent", true>; } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {NgIf, NgFor, PercentPipe} from 'fake-common'; @Component({ template: \` <section> <div></div> <span *ngIf="true"></span> </section> \`, standalone: true, imports: [NgFor, NgIf, PercentPipe] }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe('Imports array contains unused imports'); expect(diags[0].relatedInformation?.length).toBe(2); expect(diags[0].relatedInformation![0].messageText).toBe( 'Directive "NgFor" is not used within the template', ); expect(diags[0].relatedInformation![1].messageText).toBe( 'Pipe "PercentPipe" is not used within the template', ); }); it('should report unused imports coming from a neste
{ "end_byte": 236814, "start_byte": 227986, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts_236822_245045
from the same file', () => { env.write( 'used.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[used]', standalone: true}) export class UsedDir {} `, ); env.write( 'other-used.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[other-used]', standalone: true}) export class OtherUsedDir {} `, ); env.write( 'unused.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[unused]', standalone: true}) export class UnusedDir {} `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {UsedDir} from './used'; import {OtherUsedDir} from './other-used'; import {UnusedDir} from './unused'; const COMMON = [OtherUsedDir, UnusedDir]; @Component({ template: \` <section> <div other-used></div> <span used></span> </section> \`, standalone: true, imports: [UsedDir, COMMON] }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe('Imports array contains unused imports'); expect(diags[0].relatedInformation?.length).toBe(1); expect(diags[0].relatedInformation![0].messageText).toBe( 'Directive "UnusedDir" is not used within the template', ); }); it('should report unused imports coming from an array used as the `imports` initializer', () => { env.write( 'used.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[used]', standalone: true}) export class UsedDir {} `, ); env.write( 'unused.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[unused]', standalone: true}) export class UnusedDir {} `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {UsedDir} from './used'; import {UnusedDir} from './unused'; const IMPORTS = [UsedDir, UnusedDir]; @Component({ template: \` <section> <div></div> <span used></span> </section> \`, standalone: true, imports: IMPORTS }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe('Imports array contains unused imports'); expect(diags[0].relatedInformation?.length).toBe(1); expect(diags[0].relatedInformation![0].messageText).toBe( 'Directive "UnusedDir" is not used within the template', ); }); it('should not report unused imports coming from an array through a spread expression from a different file', () => { env.write( 'used.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[used]', standalone: true}) export class UsedDir {} `, ); env.write( 'other-used.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[other-used]', standalone: true}) export class OtherUsedDir {} `, ); env.write( 'unused.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[unused]', standalone: true}) export class UnusedDir {} `, ); env.write( 'common.ts', ` import {OtherUsedDir} from './other-used'; import {UnusedDir} from './unused'; export const COMMON = [OtherUsedDir, UnusedDir]; `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {UsedDir} from './used'; import {COMMON} from './common'; @Component({ template: \` <section> <div other-used></div> <span used></span> </section> \`, standalone: true, imports: [UsedDir, ...COMMON] }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not report unused imports coming from a nested array from a different file', () => { env.write( 'used.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[used]', standalone: true}) export class UsedDir {} `, ); env.write( 'other-used.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[other-used]', standalone: true}) export class OtherUsedDir {} `, ); env.write( 'unused.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[unused]', standalone: true}) export class UnusedDir {} `, ); env.write( 'common.ts', ` import {OtherUsedDir} from './other-used'; import {UnusedDir} from './unused'; export const COMMON = [OtherUsedDir, UnusedDir]; `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {UsedDir} from './used'; import {COMMON} from './common'; @Component({ template: \` <section> <div other-used></div> <span used></span> </section> \`, standalone: true, imports: [UsedDir, COMMON] }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not report unused imports coming from an exported array in the same file', () => { env.write( 'used.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[used]', standalone: true}) export class UsedDir {} `, ); env.write( 'other-used.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[other-used]', standalone: true}) export class OtherUsedDir {} `, ); env.write( 'unused.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[unused]', standalone: true}) export class UnusedDir {} `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {UsedDir} from './used'; import {OtherUsedDir} from './other-used'; import {UnusedDir} from './unused'; export const COMMON = [OtherUsedDir, UnusedDir]; @Component({ template: \` <section> <div other-used></div> <span used></span> </section> \`, standalone: true, imports: [UsedDir, COMMON] }) export class MyComp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); }); }); });
{ "end_byte": 245045, "start_byte": 236822, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts_0_9625
/** * @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 ts from 'typescript'; import {absoluteFrom} from '../../src/ngtsc/file_system'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {expectCompleteReuse, loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('ngtsc incremental compilation (template typecheck)', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.enableMultipleCompilations(); env.tsconfig({strictTemplates: true}); }); describe('type-check api surface', () => { it('should type-check correctly when a backing input field is renamed', () => { // This test verifies that renaming the class field of an input is correctly reflected into // the TCB. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input('dir') dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Now rename the backing field of the input; the TCB should be updated such that the `dir` // input binding is still valid. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input('dir') dirRenamed!: string; } `, ); env.driveMain(); }); it('should type-check correctly when a backing signal input field is renamed', () => { // This test verifies that renaming the class field of an input is correctly reflected into // the TCB. env.write( 'dir.ts', ` import {Directive, input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { dir = input.required<string>(); } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Now rename the backing field of the input; the TCB should be updated such that the `dir` // input binding is still valid. env.write( 'dir.ts', ` import {Directive, input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { dirRenamed = input.required<string>({alias: 'dir'}); } `, ); env.driveMain(); }); it('should type-check correctly when an decorator-input is changed to a signal input', () => { env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Now, the input is changed to a signal input. The template should still be valid. // If this `isSignal` change would not be detected, `string` would never be assignable // to `InputSignal` because the TCB would not unwrap it. env.write( 'dir.ts', ` import {Directive, input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { dir = input<string>(); } `, ); env.driveMain(); }); it('should type-check correctly when signal input transform is added', () => { env.write( 'dir.ts', ` import {Directive, input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { dir = input.required<string>(); } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Transform is added and the input no longer accepts `string`, but only a boolean. // This should result in diagnostics now, assuming the TCB is checked again. env.write( 'dir.ts', ` import {Directive, input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { dir = input.required<string, boolean>({ transform: v => v.toString(), }); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics[0].messageText).toBe( `Type 'string' is not assignable to type 'boolean'.`, ); }); it('should type-check correctly when a backing output field is renamed', () => { // This test verifies that renaming the class field of an output is correctly reflected into // the TCB. env.write( 'dir.ts', ` import {Directive, EventEmitter, Output} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Output('dir') dir = new EventEmitter<string>(); } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div (dir)="foo($event)"></div>', standalone: false, }) export class Cmp { foo(bar: string) {} } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Now rename the backing field of the output; the TCB should be updated such that the `dir` // input binding is still valid. env.write( 'dir.ts', ` import {Directive, EventEmitter, Output} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Output('dir') dirRenamed = new EventEmitter<string>(); } `, ); env.driveMain(); });
{ "end_byte": 9625, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts_9633_18242
it('should type-check correctly when the backing field of an input is removed', () => { // For inputs that are only declared in the decorator but for which no backing field is // declared in the TypeScript class, the TCB should not contain a write to the field as it // would be an error. This test verifies that the TCB is regenerated when a backing field // is removed. env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', inputs: ['dir'], standalone: false, }) export class Dir { dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = true; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( `Type 'boolean' is not assignable to type 'string'.`, ); // Now remove the backing field for the `dir` input. The compilation should now succeed // as there are no type-check errors. env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', inputs: ['dir'], standalone: false, }) export class Dir {} `, ); env.driveMain(); }); it('should type-check correctly when the backing field of an input is made readonly', () => { // When an input is declared as readonly and if `strictInputAccessModifiers` is disabled, // the TCB contains an indirect write to the property to silence the error that a value // cannot be assigned to a readonly property. This test verifies that changing a field to // become readonly does result in the TCB being updated to use such an indirect write, as // otherwise an error would incorrectly be reported. env.tsconfig({strictTemplates: true, strictInputAccessModifiers: false}); env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', inputs: ['dir'], standalone: false, }) export class Dir { dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Now change the `dir` input to be readonly. Because `strictInputAccessModifiers` is // disabled this should be allowed. env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', inputs: ['dir'], standalone: false, }) export class Dir { readonly dir!: string; } `, ); env.driveMain(); }); it('should type-check correctly when an ngAcceptInputType field is declared', () => { // Declaring a static `ngAcceptInputType` member requires that the TCB is regenerated, as // writes to an input property should then be targeted against this static member instead // of the input field itself. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = true; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( `Type 'boolean' is not assignable to type 'string'.`, ); // Now add an `ngAcceptInputType` static member to the directive such that its `dir` input // also accepts `boolean`, unlike the type of `dir`'s class field. This should therefore // allow the compilation to succeed. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dir!: string; static ngAcceptInputType_dir: string | boolean; } `, ); env.driveMain(); }); it('should type-check correctly when an ngTemplateContextGuard field is declared', () => { // This test adds an `ngTemplateContextGuard` static member to verify that the TCB is // regenerated for the template context to take effect. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div *dir="let bar">{{ foo(bar) }}</div>', standalone: false, }) export class Cmp { foo(bar: string) {} } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Now add the template context to declare the `$implicit` variable to be of type `number`. // Doing so should report an error for `Cmp`, as the type of `bar` which binds to // `$implicit` is no longer compatible with the method signature which requires a `string`. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; export interface TemplateContext { $implicit: number; } @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dir!: string; static ngTemplateContextGuard(dir: Dir, ctx: any): ctx is TemplateContext { return true; } } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( `Argument of type 'number' is not assignable to parameter of type 'string'.`, ); });
{ "end_byte": 18242, "start_byte": 9633, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts_18250_25589
it('should type-check correctly when an ngTemplateGuard field is declared', () => { // This test verifies that adding an `ngTemplateGuard` static member has the desired effect // of type-narrowing the bound input expression within the template. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dir!: boolean; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div *dir="foo !== null">{{ test(foo) }}</div>', standalone: false, }) export class Cmp { foo!: string | null; test(foo: string) {} } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toContain( `Argument of type 'string | null' is not assignable to parameter of type 'string'.`, ); // Now resolve the compilation error by adding the `ngTemplateGuard_dir` static member to // specify that the bound expression for `dir` should be used as template guard. This // should allow the compilation to succeed. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; export interface TemplateContext { $implicit: number; } @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dir!: boolean; static ngTemplateGuard_dir: 'binding'; } `, ); env.driveMain(); }); it('should type-check correctly when the type of an ngTemplateGuard field changes', () => { // This test verifies that changing the type of an `ngTemplateGuard` static member has the // desired effect of type-narrowing the bound input expression within the template according // to the new type of the `ngTemplateGuard` static member. Initially, an "invocation" type // context guard is used, but it's ineffective at narrowing an expression that explicitly // compares against null. An incremental step changes the type of the guard to be of type // `binding`. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T> { @Input() dir!: T; static ngTemplateGuard_dir<T>(dir: Dir<T>, expr: any): expr is NonNullable<T> { return true; }; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div *dir="foo !== null">{{ test(foo) }}</div>', standalone: false, }) export class Cmp { foo!: string | null; test(foo: string) {} } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toContain( `Argument of type 'string | null' is not assignable to parameter of type 'string'.`, ); // Now change the type of the template guard into "binding" to achieve the desired narrowing // of `foo`, allowing the compilation to succeed. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; export interface TemplateContext { $implicit: number; } @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T> { @Input() dir!: T; static ngTemplateGuard_dir: 'binding'; } `, ); env.driveMain(); }); it('should type-check correctly when the name of an ngTemplateGuard field changes', () => { // This test verifies that changing the name of the field to which an `ngTemplateGuard` // static member applies correctly removes its narrowing effect on the original input // binding expression. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T> { @Input() dir!: T; static ngTemplateGuard_dir: 'binding'; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div *dir="foo !== null">{{ test(foo) }}</div>', standalone: false, }) export class Cmp { foo!: string | null; test(foo: string) {} } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Now change the `ngTemplateGuard` to target a different field. The `dir` binding should // no longer be narrowed, causing the template of `Cmp` to become invalid. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; export interface TemplateContext { $implicit: number; } @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T> { @Input() dir!: T; static ngTemplateGuard_dir_renamed: 'binding'; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toContain( `Argument of type 'string | null' is not assignable to parameter of type 'string'.`, ); }); });
{ "end_byte": 25589, "start_byte": 18250, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts_25595_33279
describe('type parameters', () => { it('should type-check correctly when directive becomes generic', () => { // This test verifies that changing a non-generic directive `Dir` into a generic directive // correctly type-checks component `Cmp` that uses `Dir` in its template. The introduction // of the generic type requires that `Cmp`'s local declaration of `Dir` is also updated, // otherwise the prior declaration without generic type argument would be invalid. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Adding a generic type should still allow the compilation to succeed. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T> { @Input() dir!: string; } `, ); env.driveMain(); }); it('should type-check correctly when a type parameter is added to a directive', () => { // This test verifies that adding an additional generic type to directive `Dir` correctly // type-checks component `Cmp` that uses `Dir` in its template. The addition of a generic // type requires that `Cmp`'s local declaration of `Dir` is also updated, otherwise the // prior declaration with fewer generic type argument would be invalid. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T> { @Input() dir!: T; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Add generic type parameter `U` should continue to allow the compilation to succeed. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T, U> { @Input() dir!: T; } `, ); env.driveMain(); }); it('should type-check correctly when directive removes its generic type parameter', () => { // This test verifies that removing a type parameter from generic directive `Dir` such that // it becomes non-generic correctly type-checks component `Cmp` that uses `Dir` in its // template. The removal of the generic type requires that `Cmp`'s local declaration of // `Dir` is also updated, as otherwise the prior declaration with a generic type argument // would be invalid. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T> { @Input() dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Changing `Dir` to become non-generic should allow the compilation to succeed. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dir!: string; } `, ); env.driveMain(); }); it('should type-check correctly when a type parameter is removed from a directive', () => { // This test verifies that removing a type parameter from generic directive `Dir` correctly // type-checks component `Cmp` that uses `Dir` in its template. The removal of the generic // type requires that `Cmp`'s local declaration of `Dir` is also updated, as otherwise the // prior declaration with the initial number of generic type arguments would be invalid. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T, U> { @Input() dir!: T; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Removing type parameter `U` should allow the compilation to succeed. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T> { @Input() dir!: T; } `, ); env.driveMain(); });
{ "end_byte": 33279, "start_byte": 25595, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts_33287_40138
it('should type-check correctly when a generic type bound is added', () => { // This test verifies that changing an unbound generic type parameter of directive `Dir` // to have a type constraint properly applies the newly added type constraint during // type-checking of `Cmp` that uses `Dir` in its template. env.write( 'node_modules/foo/index.ts', ` export interface Foo { a: boolean; } `, ); env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T> { @Input() dir!: T; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo: string; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Update `Dir` such that its generic type parameter `T` is constrained to type `Foo`. The // template of `Cmp` should now fail to type-check, as its bound value for `T` does not // conform to the `Foo` constraint. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; import {Foo} from 'foo'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T extends Foo> { @Input() dir!: T; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain(`Type 'string' is not assignable to type 'Foo'.`); // Now update `Dir` again to remove the constraint of `T`, which should allow the template // of `Cmp` to succeed type-checking. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T> { @Input() dir!: T; } `, ); env.driveMain(); }); it('should type-check correctly when a generic type bound indirectly changes', () => { // This test verifies the scenario where a generic type constraint is updated indirectly, // i.e. without the type parameter itself changing. The setup of this test is as follows: // // - Have two external modules `foo-a` and `foo-b` that both export a type named `Foo`, // each having an incompatible shape. // - Have a directive `Dir` that has a type parameter constrained to `Foo` from `foo-a`. // - Have a component `Cmp` that uses `Dir` in its template and binds a `Foo` from `foo-a` // to an input of `Dir` of generic type `T`. This should succeed as it conforms to the // constraint of `T`. // - Perform an incremental compilation where the import of `Foo` is changed into `foo-b`. // The binding in `Cmp` should now report an error, as its value of `Foo` from `foo-a` // no longer conforms to the new type constraint of `Foo` from 'foo-b'. env.write( 'node_modules/foo-a/index.ts', ` export interface Foo { a: boolean; } `, ); env.write( 'node_modules/foo-b/index.ts', ` export interface Foo { b: boolean; } `, ); env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; import {Foo} from 'foo-a'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T extends Foo> { @Input() dir!: T; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; import {Foo} from 'foo-a'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo: Foo = {a: true}; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Now switch the import of `Foo` from `foo-a` to `foo-b`. This should cause a type-check // failure in `Cmp`, as its binding into `Dir` still provides an incompatible `Foo` // from `foo-a`. env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; import {Foo} from 'foo-b'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T extends Foo> { @Input() dir!: T; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( `Property 'b' is missing in type 'import("${absoluteFrom( '/node_modules/foo-a/index', )}").Foo' but required in type 'import("${absoluteFrom( '/node_modules/foo-b/index', )}").Foo'.`, ); // For completeness, update `Cmp` to address the previous template type-check error by // changing the type of the binding into `Dir` to also be the `Foo` from `foo-b`. This // should result in a successful compilation. env.write( 'cmp.ts', ` import {Component} from '@angular/core'; import {Foo} from 'foo-b'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo: Foo = {b: true}; } `, ); env.driveMain(); }); });
{ "end_byte": 40138, "start_byte": 33287, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts_40144_48595
describe('inheritance', () => { it('should type-check derived directives when the public API of the parent class is affected', () => { // This test verifies that an indirect change to the public API of `Dir` as caused by a // change to `Dir`'s base class `Parent` causes the type-check result of component `Cmp` // that uses `Dir` to be updated accordingly. env.write( 'parent.ts', ` import {Directive, Input} from '@angular/core'; @Directive() export class Parent { @Input() parent!: string; } `, ); env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; import {Parent} from './parent'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir extends Parent { @Input() dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo" [parent]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Now remove an input from `Parent`. This invalidates the binding in `Cmp`'s template, // so an error diagnostic should be reported. env.write( 'parent.ts', ` import {Directive, Input} from '@angular/core'; @Directive() export class Parent { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( `Can't bind to 'parent' since it isn't a known property of 'div'.`, ); }); it('should type-check derived directives when the public API of the grandparent class is affected', () => { // This test verifies that an indirect change to the public API of `Dir` as caused by a // change to `Dir`'s transitive base class `Grandparent` causes the type-check result of // component `Cmp` that uses `Dir` to be updated accordingly. env.write( 'grandparent.ts', ` import {Directive, Input} from '@angular/core'; @Directive() export class Grandparent { @Input() grandparent!: string; } `, ); env.write( 'parent.ts', ` import {Directive, Input} from '@angular/core'; import {Grandparent} from './grandparent'; @Directive() export class Parent extends Grandparent { @Input() parent!: string; } `, ); env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; import {Parent} from './parent'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir extends Parent { @Input() dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo" [parent]="foo" [grandparent]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Now remove an input from `Grandparent`. This invalidates the binding in `Cmp`'s // template, so an error diagnostic should be reported. env.write( 'grandparent.ts', ` import {Directive, Input} from '@angular/core'; @Directive() export class Grandparent { } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( `Can't bind to 'grandparent' since it isn't a known property of 'div'.`, ); }); it('should type-check derived directives when a base class is added to a grandparent', () => { // This test verifies that an indirect change to the public API of `Dir` as caused by // adding a base class `Grandgrandparent` to `Dir`'s transitive base class `Grandparent` // causes the type-check result of component `Cmp` that uses `Dir` to be // updated accordingly. env.write( 'grandgrandparent.ts', ` import {Directive, Input} from '@angular/core'; @Directive() export class Grandgrandparent { @Input() grandgrandparent!: string; } `, ); env.write( 'grandparent.ts', ` import {Directive, Input} from '@angular/core'; @Directive() export class Grandparent { @Input() grandparent!: string; } `, ); env.write( 'parent.ts', ` import {Directive, Input} from '@angular/core'; import {Grandparent} from './grandparent'; @Directive() export class Parent extends Grandparent { @Input() parent!: string; } `, ); env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; import {Parent} from './parent'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir extends Parent { @Input() dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo" [parent]="foo" [grandgrandparent]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); // `Cmp` already binds to the `grandgrandparent` input but it's not available, as // `Granparent` does not yet extend from `Grandgrandparent`. const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( `Can't bind to 'grandgrandparent' since it isn't a known property of 'div'.`, ); // Now fix the issue by adding the base class to `Grandparent`; this should allow // type-checking to succeed. env.write( 'grandparent.ts', ` import {Directive, Input} from '@angular/core'; import {Grandgrandparent} from './grandgrandparent'; @Directive() export class Grandparent extends Grandgrandparent { @Input() grandparent!: string; } `, ); env.driveMain(); });
{ "end_byte": 48595, "start_byte": 40144, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts_48603_55707
it('should type-check derived directives when a base class is removed from a grandparent', () => { // This test verifies that an indirect change to the public API of `Dir` as caused by // removing a base class `Grandgrandparent` from `Dir`'s transitive base class // `Grandparent` causes the type-check result of component `Cmp` that uses `Dir` to be // updated accordingly. env.write( 'grandgrandparent.ts', ` import {Directive, Input} from '@angular/core'; @Directive() export class Grandgrandparent { @Input() grandgrandparent!: string; } `, ); env.write( 'grandparent.ts', ` import {Directive, Input} from '@angular/core'; import {Grandgrandparent} from './grandgrandparent'; @Directive() export class Grandparent extends Grandgrandparent { @Input() grandparent!: string; } `, ); env.write( 'parent.ts', ` import {Directive, Input} from '@angular/core'; import {Grandparent} from './grandparent'; @Directive() export class Parent extends Grandparent { @Input() parent!: string; } `, ); env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; import {Parent} from './parent'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir extends Parent { @Input() dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo" [parent]="foo" [grandgrandparent]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Removing the base class from `Grandparent` should start to report a type-check // error in `Cmp`'s template, as its binding to the `grandgrandparent` input is no // longer valid. env.write( 'grandparent.ts', ` import {Directive, Input} from '@angular/core'; @Directive() export class Grandparent { @Input() grandparent!: string; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( `Can't bind to 'grandgrandparent' since it isn't a known property of 'div'.`, ); }); it('should type-check derived directives when the base class of a grandparent changes', () => { // This test verifies that an indirect change to the public API of `Dir` as caused by // changing the base class of `Dir`'s transitive base class `Grandparent` causes the // type-check result of component `Cmp` that uses `Dir` to be updated accordingly. env.write( 'grandgrandparent-a.ts', ` import {Directive, Input} from '@angular/core'; @Directive() export class GrandgrandparentA { @Input() grandgrandparentA!: string; } `, ); env.write( 'grandgrandparent-b.ts', ` import {Directive, Input} from '@angular/core'; @Directive() export class GrandgrandparentB { @Input() grandgrandparentB!: string; } `, ); env.write( 'grandparent.ts', ` import {Directive, Input} from '@angular/core'; import {GrandgrandparentA} from './grandgrandparent-a'; @Directive() export class Grandparent extends GrandgrandparentA { @Input() grandparent!: string; } `, ); env.write( 'parent.ts', ` import {Directive, Input} from '@angular/core'; import {Grandparent} from './grandparent'; @Directive() export class Parent extends Grandparent { @Input() parent!: string; } `, ); env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; import {Parent} from './parent'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir extends Parent { @Input() dir!: string; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo" [parent]="foo" [grandgrandparentA]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // Now switch the base class of `Grandparent` from `GrandgrandparentA` to // `GrandgrandparentB` causes the input binding to `grandgrandparentA` to be reported as // an error, as it's no longer available. env.write( 'grandparent.ts', ` import {Directive, Input} from '@angular/core'; import {GrandgrandparentB} from './grandgrandparent-b'; @Directive() export class Grandparent extends GrandgrandparentB { @Input() grandparent!: string; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( `Can't bind to 'grandgrandparentA' since it isn't a known property of 'div'.`, ); }); });
{ "end_byte": 55707, "start_byte": 48603, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts_55713_59273
describe('program re-use', () => { it('should completely re-use structure when the first signal input is introduced', () => { env.tsconfig({strictTemplates: true}); env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { @Input() dir: string = ''; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // introduce the signal input. env.write( 'dir.ts', ` import {Directive, input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir { dir = input.required<string>(); } `, ); env.driveMain(); expectCompleteReuse(env.getTsProgram()); expectCompleteReuse(env.getReuseTsProgram()); }); it('should completely re-use structure when an inline constructor generic directive starts using input signals', () => { env.tsconfig({strictTemplates: true}); env.write( 'dir.ts', ` import {Directive, Input} from '@angular/core'; class SomeNonExportedClass {} @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T extends SomeNonExportedClass> { @Input() dir: T|undefined; } `, ); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [dir]="foo"></div>', standalone: false, }) export class Cmp { foo = 'foo'; } `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dir} from './dir'; @NgModule({ declarations: [Cmp, Dir], }) export class Mod {} `, ); env.driveMain(); // turn the input into a signal input- causing a new import. env.write( 'dir.ts', ` import {Directive, input} from '@angular/core'; class SomeNonExportedClass {} @Directive({ selector: '[dir]', standalone: false, }) export class Dir<T extends SomeNonExportedClass> { dir = input.required<T>(); } `, ); env.driveMain(); expectCompleteReuse(env.getTsProgram()); expectCompleteReuse(env.getReuseTsProgram()); }); }); }); });
{ "end_byte": 59273, "start_byte": 55713, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_typecheck_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/util.ts_0_660
/** * @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 { ClassDeclaration, isNamedClassDeclaration, } from '@angular/compiler-cli/src/ngtsc/reflection'; import ts from 'typescript'; export function getClass(sf: ts.SourceFile, name: string): ClassDeclaration<ts.ClassDeclaration> { for (const stmt of sf.statements) { if (isNamedClassDeclaration(stmt) && stmt.name.text === name) { return stmt; } } throw new Error(`Class ${name} not found in file: ${sf.fileName}: ${sf.text}`); }
{ "end_byte": 660, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/util.ts" }
angular/packages/compiler-cli/test/ngtsc/authoring_queries_spec.ts_0_5442
/** * @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 ts from 'typescript'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('signal-based queries', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({strictTemplates: true}); }); it('should handle a basic viewChild', () => { env.write( 'test.ts', ` import {Component, viewChild} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { el = viewChild('myLocator'); } `, ); env.driveMain(); const js = env.getContents('test.js'); expect(js).toContain(`i0.ɵɵviewQuerySignal(ctx.el, _c0, 5);`); expect(js).toContain(`i0.ɵɵqueryAdvance();`); }); it('should support viewChild with `read` options', () => { env.write('other-file.ts', `export class X {}`); env.write( 'test.ts', ` import {Component, viewChild} from '@angular/core'; import * as fromOtherFile from './other-file'; class X {} @Component({selector: 'test', template: ''}) export class TestDir { el = viewChild('myLocator', {read: X}); el2 = viewChild('myLocator', {read: fromOtherFile.X}); } `, ); env.driveMain(); const js = env.getContents('test.js'); expect(js).toContain(`i0.ɵɵviewQuerySignal(ctx.el, _c0, 5, X);`); expect(js).toContain(`i0.ɵɵviewQuerySignal(ctx.el2, _c0, 5, fromOtherFile.X);`); expect(js).toContain(`i0.ɵɵqueryAdvance(2);`); }); it('should support viewChild with `read` pointing to an expression with a generic', () => { env.write( 'test.ts', ` import {Component, viewChild, ElementRef} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { el = viewChild('myLocator', {read: ElementRef<HTMLElement>}); } `, ); env.driveMain(); const js = env.getContents('test.js'); expect(js).toContain(`i0.ɵɵviewQuerySignal(ctx.el, _c0, 5, ElementRef);`); expect(js).toContain(`i0.ɵɵqueryAdvance();`); }); it('should support viewChild with `read` pointing to a parenthesized expression', () => { env.write( 'test.ts', ` import {Component, viewChild, ElementRef} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { el = viewChild('myLocator', {read: ((((ElementRef))))}); } `, ); env.driveMain(); const js = env.getContents('test.js'); expect(js).toContain(`i0.ɵɵviewQuerySignal(ctx.el, _c0, 5, ElementRef);`); expect(js).toContain(`i0.ɵɵqueryAdvance();`); }); it('should support viewChild with `read` pointing to an `as` expression', () => { env.write( 'test.ts', ` import {Component, viewChild, ElementRef} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { el = viewChild('myLocator', {read: ElementRef as any}); } `, ); env.driveMain(); const js = env.getContents('test.js'); expect(js).toContain(`i0.ɵɵviewQuerySignal(ctx.el, _c0, 5, ElementRef);`); expect(js).toContain(`i0.ɵɵqueryAdvance();`); }); it('should handle a basic viewChildren', () => { env.write( 'test.ts', ` import {Component, viewChildren} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { el = viewChildren('myLocator'); } `, ); env.driveMain(); const js = env.getContents('test.js'); expect(js).toContain(`i0.ɵɵviewQuerySignal(ctx.el, _c0, 5);`); expect(js).toContain(`i0.ɵɵqueryAdvance();`); }); it('should handle a basic contentChild', () => { env.write( 'test.ts', ` import {Component, contentChild} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { el = contentChild('myLocator'); } `, ); env.driveMain(); const js = env.getContents('test.js'); expect(js).toContain(`i0.ɵɵcontentQuerySignal(dirIndex, ctx.el, _c0, 5);`); expect(js).toContain(`i0.ɵɵqueryAdvance();`); }); it('should handle a basic contentChildren', () => { env.write( 'test.ts', ` import {Component, contentChildren} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { el = contentChildren('myLocator'); } `, ); env.driveMain(); const js = env.getContents('test.js'); expect(js).toContain(`i0.ɵɵcontentQuerySignal(dirIndex, ctx.el, _c0, 4);`); expect(js).toContain(`i0.ɵɵqueryAdvance();`); }); describe('diagnostics', () =
{ "end_byte": 5442, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/authoring_queries_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/authoring_queries_spec.ts_5448_11589
it('should report an error when used with query decorator', () => { env.write( 'test.ts', ` import {Component, viewChild, ViewChild} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { @ViewChild('myLocator') el = viewChild('myLocator'); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: `Using @ViewChild with a signal-based query is not allowed.`, }), ]); }); it('should report an error when used on a static field', () => { env.write( 'test.ts', ` import {Component, viewChild} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { static el = viewChild('myLocator'); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: `Query is incorrectly declared on a static class member.`, }), ]); }); it('should report an error when declared in @Directive metadata', () => { env.write( 'test.ts', ` import {Directive, ViewChild, viewChild} from '@angular/core'; @Directive({ selector: 'test', queries: { el: new ViewChild('myLocator'), }, }) export class TestDir { el = viewChild('myLocator'); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: `Query is declared multiple times. "@Directive" declares a query for the same property.`, }), ]); }); it('should report an error when declared in @Component metadata', () => { env.write( 'test.ts', ` import {Component, ViewChild, viewChild} from '@angular/core'; @Component({ selector: 'test', template: '', queries: { el: new ViewChild('myLocator'), }, }) export class TestComp { el = viewChild('myLocator'); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: `Query is declared multiple times. "@Component" declares a query for the same property.`, }), ]); }); it('should report an error when a signal-based query function is used in metadata', () => { env.write( 'test.ts', ` import {Component, viewChild} from '@angular/core'; @Component({ selector: 'test', template: '', queries: { // @ts-ignore el: new viewChild('myLocator'), }, }) export class TestComp {} `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: `Decorator query metadata must be an instance of a query type`, }), ]); }); it('should report an error when `read` option is complex', () => { env.write( 'test.ts', ` import {Directive, viewChild} from '@angular/core'; @Directive({ selector: 'test', }) export class TestDir { something = null!; el = viewChild('myLocator', {read: this.something}); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: `Query "read" option expected a literal class reference.`, }), ]); }); it('should error when a query is declared using an ES private field', () => { env.write( 'test.ts', ` import {Directive, viewChild} from '@angular/core'; @Directive({ selector: 'test', }) export class TestDir { #el = viewChild('myLocator'); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining<ts.Diagnostic>({ messageText: jasmine.objectContaining<ts.DiagnosticMessageChain>({ messageText: `Cannot use "viewChild" on a class member that is declared as ES private.`, }), }), ]); }); it('should allow query is declared on a `private` field', () => { env.write( 'test.ts', ` import {Directive, viewChild} from '@angular/core'; @Directive({ selector: 'test', }) export class TestDir { private el = viewChild('myLocator'); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(0); }); it('should allow query is declared on a `protected` field', () => { env.write( 'test.ts', ` import {Directive, viewChild} from '@angular/core'; @Directive({ selector: 'test', }) export class TestDir { protected el = viewChild('myLocator'); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(0); }); }); }); });
{ "end_byte": 11589, "start_byte": 5448, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/authoring_queries_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/BUILD.bazel_0_1333
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "ngtsc_lib", testonly = True, srcs = glob(["**/*.ts"]), deps = [ "//packages/compiler", "//packages/compiler-cli", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/docs", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/indexer", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/testing", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/invalid_banana_in_box", "//packages/compiler-cli/src/ngtsc/util", "//packages/compiler-cli/test:test_utils", "@npm//source-map", "@npm//typescript", ], ) jasmine_node_test( name = "ngtsc", timeout = "long", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/compiler-cli/src/ngtsc/testing/fake_common:npm_package", "//packages/core:npm_package", ], shard_count = 4, deps = [ ":ngtsc_lib", "@npm//yargs", ], )
{ "end_byte": 1333, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/BUILD.bazel" }
angular/packages/compiler-cli/test/ngtsc/sourcemap_utils.ts_0_3578
/** * @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 {MappingItem, RawSourceMap, SourceMapConsumer} from 'source-map'; import {NgtscTestEnvironment} from './env'; class TestSourceFile { private lineStarts: number[]; constructor( public url: string, public contents: string, ) { this.lineStarts = this.getLineStarts(); } getSegment( key: 'generated' | 'original', start: MappingItem | any, end: MappingItem | any, ): string { const startLine = start[key + 'Line']; const startCol = start[key + 'Column']; const endLine = end[key + 'Line']; const endCol = end[key + 'Column']; return this.contents.substring( this.lineStarts[startLine - 1] + startCol, this.lineStarts[endLine - 1] + endCol, ); } getSourceMapFileName(generatedContents: string): string { const match = /\/\/# sourceMappingURL=(.+)/.exec(generatedContents); if (!match) { throw new Error('Generated contents does not contain a sourceMappingURL'); } return match[1]; } private getLineStarts(): number[] { const lineStarts = [0]; let currentPos = 0; const lines = this.contents.split('\n'); lines.forEach((line) => { currentPos += line.length + 1; lineStarts.push(currentPos); }); return lineStarts; } } /** * A mapping of a segment of generated text to a segment of source text. */ export interface SegmentMapping { /** The generated text in this segment. */ generated: string; /** The source text in this segment. */ source: string; /** The URL of the source file for this segment. */ sourceUrl: string; } /** * Process a generated file to extract human understandable segment mappings. * These mappings are easier to compare in unit tests that the raw SourceMap mappings. * @param env the environment that holds the source and generated files. * @param generatedFileName The name of the generated file to process. * @returns An array of segment mappings for each mapped segment in the given generated file. */ export async function getMappedSegments( env: NgtscTestEnvironment, generatedFileName: string, ): Promise<SegmentMapping[]> { const generated = new TestSourceFile(generatedFileName, env.getContents(generatedFileName)); const sourceMapFileName = generated.getSourceMapFileName(generated.contents); const sources = new Map<string, TestSourceFile>(); const mappings: MappingItem[] = []; const mapContents = env.getContents(sourceMapFileName); const sourceMapConsumer = await new SourceMapConsumer(JSON.parse(mapContents) as RawSourceMap); sourceMapConsumer.eachMapping((item) => { if (!sources.has(item.source)) { sources.set(item.source, new TestSourceFile(item.source, env.getContents(item.source))); } mappings.push(item); }); const segments: SegmentMapping[] = []; let currentMapping = mappings.shift(); while (currentMapping) { const nextMapping = mappings.shift(); if (nextMapping) { const source = sources.get(currentMapping.source)!; const segment = { generated: generated.getSegment('generated', currentMapping, nextMapping), source: source.getSegment('original', currentMapping, nextMapping), sourceUrl: source.url, }; if (segment.generated !== segment.source) { segments.push(segment); } } currentMapping = nextMapping; } return segments; }
{ "end_byte": 3578, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/sourcemap_utils.ts" }
angular/packages/compiler-cli/test/ngtsc/env.ts_0_1589
/** * @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 {CustomTransformers, defaultGatherDiagnostics, Program} from '@angular/compiler-cli'; import {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs'; import * as api from '@angular/compiler-cli/src/transformers/api'; import ts from 'typescript'; import {createCompilerHost, createProgram} from '../../index'; import {mainXi18n} from '../../src/extract_i18n'; import {main, mainDiagnosticsForTest, readNgcCommandLineAndConfiguration} from '../../src/main'; import { absoluteFrom, AbsoluteFsPath, FileSystem, getFileSystem, relativeFrom, } from '../../src/ngtsc/file_system'; import {Folder, MockFileSystem} from '../../src/ngtsc/file_system/testing'; import {IndexedComponent} from '../../src/ngtsc/indexer'; import {NgtscProgram} from '../../src/ngtsc/program'; import {DeclarationNode} from '../../src/ngtsc/reflection'; import {NgtscTestCompilerHost} from '../../src/ngtsc/testing'; import {TemplateTypeChecker} from '../../src/ngtsc/typecheck/api'; import {setWrapHostForTest} from '../../src/transformers/compiler_host'; type TsConfigOptionsValue = | string | boolean | number | null | TsConfigOptionsValue[] | {[key: string]: TsConfigOptionsValue}; export type TsConfigOptions = { [key: string]: TsConfigOptionsValue; }; /** * Manages a temporary testing directory structure and environment for testing ngtsc by feeding it * TypeScript code. */
{ "end_byte": 1589, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/env.ts" }
angular/packages/compiler-cli/test/ngtsc/env.ts_1590_9747
export class NgtscTestEnvironment { private multiCompileHostExt: MultiCompileHostExt | null = null; private oldProgram: Program | null = null; private changedResources: Set<string> | null = null; private commandLineArgs: string[]; private constructor( private fs: FileSystem, readonly outDir: AbsoluteFsPath, readonly basePath: AbsoluteFsPath, ) { this.commandLineArgs = ['-p', this.basePath]; } /** * Set up a new testing environment. */ static setup(files: Folder = {}, workingDir?: AbsoluteFsPath): NgtscTestEnvironment { const fs = getFileSystem(); if (fs instanceof MockFileSystem) { fs.init(files); } const host = new AugmentedCompilerHost(fs); setWrapHostForTest(makeWrapHost(host)); workingDir = workingDir ?? absoluteFrom('/'); const env = new NgtscTestEnvironment(fs, fs.resolve('/built'), workingDir); fs.chdir(workingDir); env.write( absoluteFrom('/tsconfig-base.json'), `{ "compilerOptions": { "emitDecoratorMetadata": false, "experimentalDecorators": true, "skipLibCheck": true, "noImplicitAny": true, "noEmitOnError": true, "strictNullChecks": true, "outDir": "built", "rootDir": ".", "baseUrl": ".", "allowJs": true, "declaration": true, "target": "es2015", "newLine": "lf", "module": "es2015", "moduleResolution": "node", "lib": ["es2015", "dom"], "typeRoots": ["node_modules/@types"] }, "exclude": [ "built" ] }`, ); return env; } assertExists(fileName: string) { if (!this.fs.exists(this.fs.resolve(this.outDir, fileName))) { throw new Error(`Expected ${fileName} to be emitted (outDir: ${this.outDir})`); } } assertDoesNotExist(fileName: string) { if (this.fs.exists(this.fs.resolve(this.outDir, fileName))) { throw new Error(`Did not expect ${fileName} to be emitted (outDir: ${this.outDir})`); } } getContents(fileName: string): string { this.assertExists(fileName); const modulePath = this.fs.resolve(this.outDir, fileName); return this.fs.readFile(modulePath); } enableMultipleCompilations(): void { this.changedResources = new Set(); this.multiCompileHostExt = new MultiCompileHostExt(this.fs); setWrapHostForTest(makeWrapHost(this.multiCompileHostExt)); } /** * Installs a compiler host that allows for asynchronous reading of resources by implementing the * `CompilerHost.readResource` method. Note that only asynchronous compilations are affected, as * synchronous compilations do not use the asynchronous resource loader. */ enablePreloading(): void { setWrapHostForTest(makeWrapHost(new ResourceLoadingCompileHost(this.fs))); } addCommandLineArgs(...args: string[]): void { this.commandLineArgs.push(...args); } flushWrittenFileTracking(): void { if (this.multiCompileHostExt === null) { throw new Error(`Not tracking written files - call enableMultipleCompilations()`); } this.changedResources!.clear(); this.multiCompileHostExt.flushWrittenFileTracking(); } getTsProgram(): ts.Program { if (this.oldProgram === null) { throw new Error('No ts.Program has been created yet.'); } return this.oldProgram.getTsProgram(); } getReuseTsProgram(): ts.Program { if (this.oldProgram === null) { throw new Error('No ts.Program has been created yet.'); } return (this.oldProgram as NgtscProgram).getReuseTsProgram(); } /** * Older versions of the CLI do not provide the `CompilerHost.getModifiedResourceFiles()` method. * This results in the `changedResources` set being `null`. */ simulateLegacyCLICompilerHost() { this.changedResources = null; } getFilesWrittenSinceLastFlush(): Set<string> { if (this.multiCompileHostExt === null) { throw new Error(`Not tracking written files - call enableMultipleCompilations()`); } const writtenFiles = new Set<string>(); this.multiCompileHostExt.getFilesWrittenSinceLastFlush().forEach((rawFile) => { if (rawFile.startsWith(this.outDir)) { writtenFiles.add(rawFile.slice(this.outDir.length)); } }); return writtenFiles; } write(fileName: string, content: string) { const absFilePath = this.fs.resolve(this.basePath, fileName); if (this.multiCompileHostExt !== null) { this.multiCompileHostExt.invalidate(absFilePath); if (!fileName.endsWith('.ts')) { this.changedResources!.add(absFilePath); } } this.fs.ensureDir(this.fs.dirname(absFilePath)); this.fs.writeFile(absFilePath, content); } invalidateCachedFile(fileName: string): void { const absFilePath = this.fs.resolve(this.basePath, fileName); if (this.multiCompileHostExt === null) { throw new Error(`Not caching files - call enableMultipleCompilations()`); } this.multiCompileHostExt.invalidate(absFilePath); if (!fileName.endsWith('.ts')) { this.changedResources!.add(absFilePath); } } tsconfig(extraOpts: TsConfigOptions = {}, extraRootDirs?: string[], files?: string[]): void { const tsconfig: {[key: string]: any} = { extends: './tsconfig-base.json', angularCompilerOptions: extraOpts, }; if (files !== undefined) { tsconfig['files'] = files; } if (extraRootDirs !== undefined) { tsconfig['compilerOptions'] = { rootDirs: ['.', ...extraRootDirs], }; } this.write('tsconfig.json', JSON.stringify(tsconfig, null, 2)); if ( extraOpts['_useHostForImportGeneration'] || extraOpts['_useHostForImportAndAliasGeneration'] ) { setWrapHostForTest(makeWrapHost(new FileNameToModuleNameHost(this.fs))); } } /** * Run the compiler to completion, and assert that no errors occurred. */ driveMain(customTransformers?: CustomTransformers): void { const errorSpy = jasmine.createSpy('consoleError').and.callFake(console.error); let reuseProgram: {program: Program | undefined} | undefined = undefined; if (this.multiCompileHostExt !== null) { reuseProgram = { program: this.oldProgram || undefined, }; } const exitCode = main( this.commandLineArgs, errorSpy, undefined, customTransformers, reuseProgram, this.changedResources, ); expect(errorSpy).not.toHaveBeenCalled(); expect(exitCode).toBe(0); if (this.multiCompileHostExt !== null) { this.oldProgram = reuseProgram!.program!; } } /** * Run the compiler to completion, and return any `ts.Diagnostic` errors that may have occurred. */ driveDiagnostics(expectedExitCode?: number): ReadonlyArray<ts.Diagnostic> { // ngtsc only produces ts.Diagnostic messages. let reuseProgram: {program: Program | undefined} | undefined = undefined; if (this.multiCompileHostExt !== null) { reuseProgram = { program: this.oldProgram || undefined, }; } const {exitCode, diagnostics} = mainDiagnosticsForTest( this.commandLineArgs, undefined, reuseProgram, this.changedResources, ); if (expectedExitCode !== undefined) { expect(exitCode) .withContext( `Expected program to exit with code ${expectedExitCode}, but it actually exited with code ${exitCode}.`, ) .toBe(expectedExitCode); } if (this.multiCompileHostExt !== null) { this.oldProgram = reuseProgram!.program!; } // In ngtsc, only `ts.Diagnostic`s are produced. return diagnostics as ReadonlyArray<ts.Diagnostic>; } async driveDiagnosticsAsync(): Promise<ReadonlyArray<ts.Diagnostic>> { const {rootNames, options} = readNgcCommandLineAndConfiguration(this.commandLineArgs); const host = createCompilerHost({options}); const program = createProgram({rootNames, host, options}); await program.loadNgStructureAsync(); // ngtsc only produces ts.Diagnostic messages. return defaultGatherDiagnostics(program as api.Program) as ts.Diagnostic[]; }
{ "end_byte": 9747, "start_byte": 1590, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/env.ts" }
angular/packages/compiler-cli/test/ngtsc/env.ts_9751_15608
driveTemplateTypeChecker(): {program: ts.Program; checker: TemplateTypeChecker} { const {rootNames, options} = readNgcCommandLineAndConfiguration(this.commandLineArgs); const host = createCompilerHost({options}); const program = createProgram({rootNames, host, options}); const checker = (program as NgtscProgram).compiler.getTemplateTypeChecker(); return { program: program.getTsProgram(), checker, }; } driveIndexer(): Map<DeclarationNode, IndexedComponent> { const {rootNames, options} = readNgcCommandLineAndConfiguration(this.commandLineArgs); const host = createCompilerHost({options}); const program = createProgram({rootNames, host, options}); return (program as NgtscProgram).getIndexedComponents(); } driveDocsExtraction(entryPoint: string): DocEntry[] { const {rootNames, options} = readNgcCommandLineAndConfiguration(this.commandLineArgs); const host = createCompilerHost({options}); const program = createProgram({rootNames, host, options}); return (program as NgtscProgram).getApiDocumentation(entryPoint, new Set()).entries; } driveDocsExtractionForSymbols(entryPoint: string): Map<string, string> { const {rootNames, options} = readNgcCommandLineAndConfiguration(this.commandLineArgs); const host = createCompilerHost({options}); const program = createProgram({rootNames, host, options}); return (program as NgtscProgram).getApiDocumentation(entryPoint, new Set()).symbols; } driveXi18n(format: string, outputFileName: string, locale: string | null = null): void { const errorSpy = jasmine.createSpy('consoleError').and.callFake(console.error); const args = [...this.commandLineArgs, `--i18nFormat=${format}`, `--outFile=${outputFileName}`]; if (locale !== null) { args.push(`--locale=${locale}`); } const exitCode = mainXi18n(args, errorSpy); expect(errorSpy).not.toHaveBeenCalled(); expect(exitCode).toEqual(0); } driveHmr(fileName: string, className: string): string | null { const {rootNames, options} = readNgcCommandLineAndConfiguration(this.commandLineArgs); const host = createCompilerHost({options}); const program = createProgram({rootNames, host, options}); const sourceFile = program.getTsProgram().getSourceFile(fileName); if (sourceFile == null) { throw new Error(`Cannot find file at "${fileName}"`); } for (const node of sourceFile.statements) { if (ts.isClassDeclaration(node) && node.name != null && node.name.text === className) { return (program as NgtscProgram).compiler.emitHmrUpdateModule(node); } } throw new Error(`Cannot find class with name "${className}" in "${fileName}"`); } } class AugmentedCompilerHost extends NgtscTestCompilerHost { delegate!: ts.CompilerHost; } const ROOT_PREFIX = 'root/'; class FileNameToModuleNameHost extends AugmentedCompilerHost { fileNameToModuleName(importedFilePath: string): string { const relativeFilePath = relativeFrom( this.fs.relative(this.fs.pwd(), this.fs.resolve(importedFilePath)), ); const rootedPath = this.fs.join('root', relativeFilePath); return rootedPath.replace(/(\.d)?.ts$/, ''); } resolveModuleNames( moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ts.ResolvedProjectReference | undefined, options: ts.CompilerOptions, ): (ts.ResolvedModule | undefined)[] { return moduleNames.map((moduleName) => { if (moduleName.startsWith(ROOT_PREFIX)) { // Strip the artificially added root prefix. moduleName = '/' + moduleName.slice(ROOT_PREFIX.length); } return ts.resolveModuleName( moduleName, containingFile, options, this, /* cache */ undefined, redirectedReference, ).resolvedModule; }); } } class MultiCompileHostExt extends AugmentedCompilerHost implements Partial<ts.CompilerHost> { private cache = new Map<string, ts.SourceFile>(); private writtenFiles = new Set<string>(); override getSourceFile( fileName: string, languageVersion: ts.ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean, ): ts.SourceFile | undefined { if (this.cache.has(fileName)) { return this.cache.get(fileName)!; } const sf = super.getSourceFile(fileName, languageVersion); if (sf !== undefined) { this.cache.set(sf.fileName, sf); } return sf; } flushWrittenFileTracking(): void { this.writtenFiles.clear(); } override writeFile( fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray<ts.SourceFile>, ): void { super.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); this.writtenFiles.add(fileName); } getFilesWrittenSinceLastFlush(): Set<string> { return this.writtenFiles; } invalidate(fileName: string): void { this.cache.delete(fileName); } } class ResourceLoadingCompileHost extends AugmentedCompilerHost implements api.CompilerHost { readResource(fileName: string): Promise<string> | string { const resource = this.readFile(fileName); if (resource === undefined) { throw new Error(`Resource ${fileName} not found`); } return resource; } } function makeWrapHost(wrapped: AugmentedCompilerHost): (host: ts.CompilerHost) => ts.CompilerHost { return (delegate) => { wrapped.delegate = delegate; return new Proxy(delegate, { get: (target: ts.CompilerHost, name: string): any => { if ((wrapped as any)[name] !== undefined) { return (wrapped as any)[name]!.bind(wrapped); } return (target as any)[name]; }, }); }; }
{ "end_byte": 15608, "start_byte": 9751, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/env.ts" }
angular/packages/compiler-cli/test/ngtsc/authoring_outputs_spec.ts_0_9367
/** * @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 ts from 'typescript'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('initializer-based output() API', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({strictTemplates: true}); }); it('should handle a basic output()', () => { env.write( 'test.ts', ` import {Component, output} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { click = output(); } `, ); env.driveMain(); const js = env.getContents('test.js'); const dts = env.getContents('test.d.ts'); expect(js).toContain(`outputs: { click: "click" }`); expect(dts).toContain('{ "click": "click"; '); }); it('should handle outputFromObservable()', () => { env.write( 'test.ts', ` import {Component, EventEmitter} from '@angular/core'; import {outputFromObservable} from '@angular/core/rxjs-interop'; @Component({selector: 'test', template: ''}) export class TestDir { click = outputFromObservable(new EventEmitter<void>()); } `, ); env.driveMain(); const js = env.getContents('test.js'); const dts = env.getContents('test.d.ts'); expect(js).toContain(`outputs: { click: "click" }`); expect(dts).toContain('{ "click": "click"; '); }); it('should handle an aliased output()', () => { env.write( 'test.ts', ` import {Component, output} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { click = output({alias: 'publicClick'}); } `, ); env.driveMain(); const js = env.getContents('test.js'); const dts = env.getContents('test.d.ts'); expect(js).toContain(`outputs: { click: "publicClick" }`); expect(dts).toContain('{ "click": "publicClick"; '); }); it('should handle an aliased outputFromObservable()', () => { env.write( 'test.ts', ` import {Component, EventEmitter} from '@angular/core'; import {outputFromObservable} from '@angular/core/rxjs-interop'; @Component({selector: 'test', template: ''}) export class TestDir { source$ = new EventEmitter<void>(); click = outputFromObservable(this.source$, {alias: 'publicClick'}); } `, ); env.driveMain(); const js = env.getContents('test.js'); const dts = env.getContents('test.d.ts'); expect(js).toContain(`outputs: { click: "publicClick" }`); expect(dts).toContain('{ "click": "publicClick"; '); }); describe('diagnostics', () => { it('should fail when output() is used with @Output decorator', () => { env.write( 'test.ts', ` import {Component, Output, output} from '@angular/core'; @Component({selector: 'test', template: ''}) export class TestDir { @Output() click = output({alias: 'publicClick'}); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: 'Using "@Output" with "output()" is not allowed.', }), ]); }); it('should fail when outputFromObservable() is used with @Output decorator', () => { env.write( 'test.ts', ` import {Component, Output, EventEmitter} from '@angular/core'; import {outputFromObservable} from '@angular/core/rxjs-interop'; @Component({selector: 'test', template: ''}) export class TestDir { @Output() click = outputFromObservable(new EventEmitter()); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: 'Using "@Output" with "output()" is not allowed.', }), ]); }); it('should fail if used with output declared in @Directive metadata', () => { env.write( 'test.ts', ` import {Directive, Output, output} from '@angular/core'; @Directive({ selector: 'test', outputs: ['click'], }) export class TestDir { click = output({alias: 'publicClick'}); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: 'Output "click" is unexpectedly declared in @Directive as well.', }), ]); }); it('should fail if used with output declared in @Component metadata', () => { env.write( 'test.ts', ` import {Component, Output, output} from '@angular/core'; @Component({ selector: 'test', template: '', outputs: ['click'], }) export class TestDir { click = output({alias: 'publicClick'}); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: 'Output "click" is unexpectedly declared in @Component as well.', }), ]); }); it('should fail if declared on a static member', () => { env.write( 'test.ts', ` import {Component, output} from '@angular/core'; @Component({ selector: 'test', template: '', }) export class TestDir { static click = output({alias: 'publicClick'}); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: 'Output is incorrectly declared on a static class member.', }), ]); }); it('should fail if `.required` method is used (even though not supported via types)', () => { env.write( 'test.ts', ` import {Component, output} from '@angular/core'; @Component({ selector: 'test', template: '', }) export class TestDir { // @ts-ignore click = output.required({alias: 'publicClick'}); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({messageText: 'Output does not support ".required()".'}), ]); }); it('should report an error when using an ES private field', () => { env.write( 'test.ts', ` import {Component, output} from '@angular/core'; @Component({ selector: 'test', template: '', }) export class TestDir { #click = output(); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining<ts.Diagnostic>({ messageText: jasmine.objectContaining<ts.DiagnosticMessageChain>({ messageText: `Cannot use "output" on a class member that is declared as ES private.`, }), }), ]); }); it('should report an error when using a `private` field', () => { env.write( 'test.ts', ` import {Component, output} from '@angular/core'; @Component({ selector: 'test', template: '', }) export class TestDir { private click = output(); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining<ts.Diagnostic>({ messageText: jasmine.objectContaining<ts.DiagnosticMessageChain>({ messageText: `Cannot use "output" on a class member that is declared as private.`, }), }), ]); }); it('should allow an output using a `protected` field', () => { env.write( 'test.ts', ` import {Component, output} from '@angular/core'; @Component({ selector: 'test', template: '', }) export class TestDir { protected click = output(); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(0); }); }); }); });
{ "end_byte": 9367, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/authoring_outputs_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_error_spec.ts_0_7161
/** * @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 {absoluteFrom as _} from '../../src/ngtsc/file_system'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('ngtsc incremental compilation with errors', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.enableMultipleCompilations(); env.tsconfig(); // This file is part of the program, but not referenced by anything else. It can be used by // each test to verify that it isn't re-emitted after incremental builds. env.write( 'unrelated.ts', ` export class Unrelated {} `, ); }); function expectToHaveWritten(files: string[]): void { const set = env.getFilesWrittenSinceLastFlush(); const expectedSet = new Set<string>(); for (const file of files) { expectedSet.add(file); expectedSet.add(file.replace(/\.js$/, '.d.ts')); } expect(set).toEqual(expectedSet); // Reset for the next compilation. env.flushWrittenFileTracking(); } it('should handle an error in an unrelated file', () => { env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...', standalone: false, }) export class TestCmp {} `, ); env.write( 'other.ts', ` export class Other {} `, ); // Start with a clean compilation. env.driveMain(); env.flushWrittenFileTracking(); // Introduce the error. env.write( 'other.ts', ` export class Other // missing braces `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].file!.fileName).toBe(_('/other.ts')); expectToHaveWritten([]); // Remove the error. /other.js should now be emitted again. env.write( 'other.ts', ` export class Other {} `, ); env.driveMain(); expectToHaveWritten(['/other.js']); }); it('should emit all files after an error on the initial build', () => { // Intentionally start with a broken compilation. env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...', standalone: false, }) export class TestCmp {} `, ); env.write( 'other.ts', ` export class Other // missing braces `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].file!.fileName).toBe(_('/other.ts')); expectToHaveWritten([]); // Remove the error. All files should be emitted. env.write( 'other.ts', ` export class Other {} `, ); env.driveMain(); expectToHaveWritten(['/cmp.js', '/other.js', '/unrelated.js']); }); it('should emit files introduced at the same time as an unrelated error', () => { env.write( 'other.ts', ` // Needed so that the initial program contains @angular/core's .d.ts file. import '@angular/core'; export class Other {} `, ); // Clean compile. env.driveMain(); env.flushWrittenFileTracking(); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({selector: 'test-cmp', template: '...'}) export class TestCmp {} `, ); env.write( 'other.ts', ` export class Other // missing braces `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].file!.fileName).toBe(_('/other.ts')); expectToHaveWritten([]); // Remove the error. All files should be emitted. env.write( 'other.ts', ` export class Other {} `, ); env.driveMain(); expectToHaveWritten(['/cmp.js', '/other.js']); }); it('should emit dependent files even in the face of an error', () => { env.write( 'cmp.ts', ` import {Component} from '@angular/core'; import {SELECTOR} from './selector'; @Component({selector: SELECTOR, template: '...'}) export class TestCmp {} `, ); env.write( 'selector.ts', ` export const SELECTOR = 'test-cmp'; `, ); env.write( 'other.ts', ` // Needed so that the initial program contains @angular/core's .d.ts file. import '@angular/core'; export class Other {} `, ); // Clean compile. env.driveMain(); env.flushWrittenFileTracking(); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({selector: 'test-cmp', template: '...'}) export class TestCmp {} `, ); env.write( 'other.ts', ` export class Other // missing braces `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].file!.fileName).toBe(_('/other.ts')); expectToHaveWritten([]); // Remove the error. All files should be emitted. env.write( 'other.ts', ` export class Other {} `, ); env.driveMain(); expectToHaveWritten(['/cmp.js', '/other.js']); }); it("should recover from an error in a component's metadata", () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({selector: 'test-cmp', template: '...'}) export class TestCmp {} `, ); // Start with a clean compilation. env.driveMain(); env.flushWrittenFileTracking(); // Introduce the error. env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({selector: 'test-cmp', template: ...}) // invalid template export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBeGreaterThan(0); expectToHaveWritten([]); // Clear the error and verify that the compiler now emits test.js again. env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({selector: 'test-cmp', template: '...'}) export class TestCmp {} `, ); env.driveMain(); expectToHaveWritten(['/test.js']); });
{ "end_byte": 7161, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_error_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/incremental_error_spec.ts_7167_14466
it('should recover from an error in a component that is part of a module', () => { // In this test, there are two components, TestCmp and TargetCmp, that are part of the same // NgModule. TestCmp is broken in an incremental build and then fixed, and the test verifies // that TargetCmp is re-emitted. env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...', standalone: false, }) export class TestCmp {} `, ); env.write( 'target.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'target-cmp', template: '<test-cmp></test-cmp>', standalone: false, }) export class TargetCmp {} `, ); env.write( 'module.ts', ` import {NgModule, NO_ERRORS_SCHEMA} from '@angular/core'; import {TargetCmp} from './target'; import {TestCmp} from './test'; @NgModule({ declarations: [TestCmp, TargetCmp], schemas: [NO_ERRORS_SCHEMA], }) export class Module {} `, ); // Start with a clean compilation. env.driveMain(); env.flushWrittenFileTracking(); // Introduce the syntactic error. env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: ..., template: '...', standalone: false, }) // ... is not valid syntax export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBeGreaterThan(0); expectToHaveWritten([]); // Clear the error and trigger the rebuild. env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp-fixed', template: '...', standalone: false, }) export class TestCmp {} `, ); env.driveMain(); expectToHaveWritten([ // The file which had the error should have been emitted, of course. '/test.js', // Because TestCmp belongs to a module, the module's file should also have been // re-emitted. '/module.js', // Because TargetCmp also belongs to the same module, it should be re-emitted since // TestCmp's selector was changed. '/target.js', ]); }); it('should recover from an error in an external template', () => { env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; @NgModule({ declarations: [Cmp], }) export class Mod {} `, ); env.write('cmp.html', '{{ error = "true" }} '); env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './cmp.html', selector: 'some-cmp', standalone: false, }) export class Cmp { error = 'false'; } `, ); // Diagnostics should show for the broken component template. expect(env.driveDiagnostics().length).toBeGreaterThan(0); env.write('cmp.html', '{{ error }} '); // There should be no diagnostics. env.driveMain(); }); it('should recover from an error even across multiple NgModules', () => { // This test is a variation on the above. Two components (CmpA and CmpB) exist in an NgModule, // which indirectly imports a LibModule (via another NgModule in the middle). The test is // designed to verify that CmpA and CmpB are re-emitted if somewhere upstream in the NgModule // graph, an error is fixed. To check this, LibModule is broken and then fixed in incremental // build steps. env.write( 'a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: false, }) export class CmpA {} `, ); env.write( 'b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'target-cmp', template: '...', standalone: false, }) export class CmpB {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {LibModule} from './lib'; import {CmpA} from './a'; import {CmpB} from './b'; @NgModule({ imports: [LibModule], exports: [LibModule], }) export class IndirectModule {} @NgModule({ declarations: [CmpA, CmpB], imports: [IndirectModule], }) export class Module {} `, ); env.write( 'lib.ts', ` import {Directive, NgModule} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class LibDir {} @NgModule({ declarations: [LibDir], exports: [LibDir], }) export class LibModule {} `, ); // Start with a clean compilation. env.driveMain(); env.flushWrittenFileTracking(); // Introduce the error in LibModule env.write( 'lib.ts', ` import {Directive, NgModule} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class LibDir {} @Directive({ selector: '[dir]', standalone: false, }) export class NewDir {} @NgModule({ declarations: [NewDir], }) export class NewModule {} @NgModule({ declarations: [LibDir], imports: [NewModule], exports: [LibDir, NewModule], }) export class LibModule // missing braces `, ); // env.driveMain(); const diags = env.driveDiagnostics(); expect(diags.length).toBeGreaterThan(0); expectToHaveWritten([]); // Clear the error and recompile. env.write( 'lib.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'lib-cmp', template: '...', standalone: false, }) export class LibCmp {} @NgModule({}) export class NewModule {} @NgModule({ declarations: [LibCmp], imports: [NewModule], exports: [LibCmp, NewModule], }) export class LibModule {} `, ); env.driveMain(); expectToHaveWritten([ // CmpA should be re-emitted as `NewModule` was added since the successful emit, which added // `NewDir` as a matching directive to CmpA. Alternatively, CmpB should not be re-emitted // as it does not use the newly added directive. '/a.js', // So should the module itself. '/module.js', // And of course, the file with the error. '/lib.js', ]); });
{ "end_byte": 14466, "start_byte": 7167, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_error_spec.ts" }