Skip to content

Commit ba38178

Browse files
crisbetodylhunn
authored andcommitted
fix(migrations): generate forwardRef for same file imports (#48898)
Adds some logic that will generate a `forwardRef` if necessary when adding imports. PR Close #48898
1 parent d014503 commit ba38178

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

packages/core/schematics/ng-generate/standalone-migration/to-standalone.ts

+12-1
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,18 @@ function getComponentImportExpressions(
119119
ref.node.getSourceFile(), importLocation.symbolName, importLocation.moduleSpecifier);
120120
imports.push(identifier);
121121
} else {
122-
imports.push(ts.factory.createIdentifier(importLocation.symbolName));
122+
const identifier = ts.factory.createIdentifier(importLocation.symbolName);
123+
124+
if (importLocation.isForwardReference) {
125+
const forwardRefExpression =
126+
tracker.addImport(ref.node.getSourceFile(), 'forwardRef', '@angular/core');
127+
const arrowFunction = ts.factory.createArrowFunction(
128+
undefined, undefined, [], undefined, undefined, identifier);
129+
imports.push(
130+
ts.factory.createCallExpression(forwardRefExpression, undefined, [arrowFunction]));
131+
} else {
132+
imports.push(identifier);
133+
}
123134
}
124135

125136
seenImports.add(importLocation.symbolName);

packages/core/schematics/test/standalone_migration_spec.ts

+40
Original file line numberDiff line numberDiff line change
@@ -1254,6 +1254,46 @@ describe('standalone migration', () => {
12541254
`));
12551255
});
12561256

1257+
it('should generate a forwardRef for forward reference within the same file', async () => {
1258+
writeFile('decls.ts', `
1259+
import {Component, Directive} from '@angular/core';
1260+
1261+
@Component({
1262+
selector: 'comp',
1263+
template: '<div my-dir></div>'
1264+
})
1265+
export class MyComp {}
1266+
1267+
@Directive({selector: '[my-dir]'})
1268+
export class MyDir {}
1269+
`);
1270+
1271+
writeFile('module.ts', `
1272+
import {NgModule} from '@angular/core';
1273+
import {MyComp, MyDir} from './decls';
1274+
1275+
@NgModule({declarations: [MyComp, MyDir]})
1276+
export class Mod {}
1277+
`);
1278+
1279+
await runMigration('convert-to-standalone');
1280+
1281+
expect(stripWhitespace(tree.readContent('decls.ts'))).toEqual(stripWhitespace(`
1282+
import {Component, Directive, forwardRef} from '@angular/core';
1283+
1284+
@Component({
1285+
selector: 'comp',
1286+
template: '<div my-dir></div>',
1287+
standalone: true,
1288+
imports: [forwardRef(() => MyDir)]
1289+
})
1290+
export class MyComp {}
1291+
1292+
@Directive({selector: '[my-dir]', standalone: true})
1293+
export class MyDir {}
1294+
`));
1295+
});
1296+
12571297
it('should remove a module that only has imports and exports', async () => {
12581298
writeFile('app.module.ts', `
12591299
import {NgModule} from '@angular/core';

0 commit comments

Comments
 (0)