From 3b2f88cd905e5db7e6fa8982cc63ff2fd32a7599 Mon Sep 17 00:00:00 2001 From: naaajii Date: Mon, 27 May 2024 22:19:06 +0500 Subject: [PATCH] fix(migrations): handle empty ngSwitchCase (#56105) empty ngSwitchCase generate `case ()` which isn't valid syntax therefore adding quotes will help prevent us migrate empty case if no condition was provided fix angular#56030 PR Close #56105 --- .../control-flow-migration/cases.ts | 4 ++- .../test/control_flow_migration_spec.ts | 26 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/core/schematics/ng-generate/control-flow-migration/cases.ts b/packages/core/schematics/ng-generate/control-flow-migration/cases.ts index 0674c398091..9a8ea550324 100644 --- a/packages/core/schematics/ng-generate/control-flow-migration/cases.ts +++ b/packages/core/schematics/ng-generate/control-flow-migration/cases.ts @@ -94,7 +94,9 @@ function migrateNgSwitchCase(etm: ElementToMigrate, tmpl: string, offset: number // includes the mandatory semicolon before as const lbString = etm.hasLineBreaks ? '\n' : ''; const leadingSpace = etm.hasLineBreaks ? '' : ' '; - const condition = etm.attr.value; + // ngSwitchCases with no values results into `case ()` which isn't valid, based off empty + // value we add quotes instead of generating empty case + const condition = etm.attr.value.length === 0 ? `''` : etm.attr.value; const originals = getOriginals(etm, tmpl, offset); diff --git a/packages/core/schematics/test/control_flow_migration_spec.ts b/packages/core/schematics/test/control_flow_migration_spec.ts index 0fcc104d37b..09a2316a8dc 100644 --- a/packages/core/schematics/test/control_flow_migration_spec.ts +++ b/packages/core/schematics/test/control_flow_migration_spec.ts @@ -187,6 +187,32 @@ describe('control flow migration', () => { ); }); + it('should migrate an empty case', async () => { + writeFile( + '/comp.ts', + ` + import {Component} from '@angular/core'; + import {ngSwitch, ngSwitchCase} from '@angular/common'; + @Component({ + template: \`
` + + `

Option 1

` + + `

Option 2

` + + `
\` + }) + class Comp { + testOpts = "1"; + } + `, + ); + + await runMigration(); + const content = tree.readContent('/comp.ts'); + + expect(content).toContain( + `template: \`
@switch (testOpts) { @case ('') {

Option 1

} @case (2) {

Option 2

}}
`, + ); + }); + it('should migrate multiple inline templates in the same file', async () => { writeFile( '/comp.ts',