Skip to content

Commit fadfee4

Browse files
fix(migrations): cf migration fix migrating empty switch default (#53237)
This should address cases when using ng-containers with ngSwitchCase / ngSwitchDefault and migrating them safely when they are empty. fixes: #53235 PR Close #53237
1 parent c9f8e75 commit fadfee4

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

packages/core/schematics/ng-generate/control-flow-migration/util.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -432,8 +432,12 @@ export function getMainBlock(etm: ElementToMigrate, tmpl: string, offset: number
432432
// removable containers are ng-templates or ng-containers that no longer need to exist
433433
// post migration
434434
if (isRemovableContainer(etm)) {
435-
const {childStart, childEnd} = etm.getChildSpan(offset);
436-
return {start: '', middle: tmpl.slice(childStart, childEnd), end: ''};
435+
let middle = '';
436+
if (etm.hasChildren()) {
437+
const {childStart, childEnd} = etm.getChildSpan(offset);
438+
middle = tmpl.slice(childStart, childEnd);
439+
}
440+
return {start: '', middle, end: ''};
437441
} else if (isI18nTemplate(etm, i18nAttr)) {
438442
// here we're removing an ng-template used for control flow and i18n and
439443
// converting it to an ng-container with i18n

packages/core/schematics/test/control_flow_migration_spec.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2391,6 +2391,45 @@ describe('control flow migration', () => {
23912391
'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> } @default { <p>Option 3</p> }}</div>');
23922392
});
23932393

2394+
it('should handle empty default cases', async () => {
2395+
writeFile('/comp.ts', `
2396+
import {Component} from '@angular/core';
2397+
import {ngSwitch, ngSwitchCase} from '@angular/common';
2398+
2399+
@Component({
2400+
templateUrl: './comp.html'
2401+
})
2402+
class Comp {
2403+
testOpts = "1";
2404+
}
2405+
`);
2406+
2407+
writeFile('/comp.html', [
2408+
`<ng-container [ngSwitch]="type">`,
2409+
`<ng-container *ngSwitchCase="'foo'"> Foo </ng-container>`,
2410+
`<ng-container *ngSwitchCase="'bar'"> Bar </ng-container>`,
2411+
`<ng-container *ngSwitchDefault></ng-container>`,
2412+
`</ng-container>`,
2413+
].join('\n'));
2414+
2415+
await runMigration();
2416+
const actual = tree.readContent('/comp.html');
2417+
const expected = [
2418+
`\n@switch (type) {`,
2419+
` @case ('foo') {`,
2420+
` Foo`,
2421+
` }`,
2422+
` @case ('bar') {`,
2423+
` Bar`,
2424+
` }`,
2425+
` @default {`,
2426+
` }`,
2427+
`}\n`,
2428+
].join('\n');
2429+
2430+
expect(actual).toBe(expected);
2431+
});
2432+
23942433
it('should migrate a nested class', async () => {
23952434
writeFile(
23962435
'/comp.ts',

0 commit comments

Comments
 (0)