Skip to content

Commit

Permalink
fix(migrations): cf migration fix migrating empty switch default (#53237
Browse files Browse the repository at this point in the history
)

This should address cases when using ng-containers with ngSwitchCase / ngSwitchDefault
and migrating them safely when they are empty.

fixes: #53235

PR Close #53237
  • Loading branch information
thePunderWoman authored and pkozlowski-opensource committed Nov 29, 2023
1 parent c9f8e75 commit fadfee4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
Expand Up @@ -432,8 +432,12 @@ export function getMainBlock(etm: ElementToMigrate, tmpl: string, offset: number
// removable containers are ng-templates or ng-containers that no longer need to exist
// post migration
if (isRemovableContainer(etm)) {
const {childStart, childEnd} = etm.getChildSpan(offset);
return {start: '', middle: tmpl.slice(childStart, childEnd), end: ''};
let middle = '';
if (etm.hasChildren()) {
const {childStart, childEnd} = etm.getChildSpan(offset);
middle = tmpl.slice(childStart, childEnd);
}
return {start: '', middle, end: ''};
} else if (isI18nTemplate(etm, i18nAttr)) {
// here we're removing an ng-template used for control flow and i18n and
// converting it to an ng-container with i18n
Expand Down
39 changes: 39 additions & 0 deletions packages/core/schematics/test/control_flow_migration_spec.ts
Expand Up @@ -2391,6 +2391,45 @@ describe('control flow migration', () => {
'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> } @default { <p>Option 3</p> }}</div>');
});

it('should handle empty default cases', async () => {
writeFile('/comp.ts', `
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
testOpts = "1";
}
`);

writeFile('/comp.html', [
`<ng-container [ngSwitch]="type">`,
`<ng-container *ngSwitchCase="'foo'"> Foo </ng-container>`,
`<ng-container *ngSwitchCase="'bar'"> Bar </ng-container>`,
`<ng-container *ngSwitchDefault></ng-container>`,
`</ng-container>`,
].join('\n'));

await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`\n@switch (type) {`,
` @case ('foo') {`,
` Foo`,
` }`,
` @case ('bar') {`,
` Bar`,
` }`,
` @default {`,
` }`,
`}\n`,
].join('\n');

expect(actual).toBe(expected);
});

it('should migrate a nested class', async () => {
writeFile(
'/comp.ts',
Expand Down

0 comments on commit fadfee4

Please sign in to comment.