diff --git a/packages/core/schematics/ng-generate/control-flow-migration/util.ts b/packages/core/schematics/ng-generate/control-flow-migration/util.ts index d022b73f7a610..fc87547c7aeb1 100644 --- a/packages/core/schematics/ng-generate/control-flow-migration/util.ts +++ b/packages/core/schematics/ng-generate/control-flow-migration/util.ts @@ -283,16 +283,18 @@ export function processNgTemplates(template: string): string { // swap placeholders and remove for (const [name, t] of templates) { - const placeholder = `${name}|`; - - if (template.indexOf(placeholder) > -1) { + const replaceRegex = new RegExp(`${name}\\|`, 'g'); + const matches = [...template.matchAll(replaceRegex)]; + if (matches.length > 0) { if (t.i18n !== null) { const container = wrapIntoI18nContainer(t.i18n, t.children); - template = template.replace(placeholder, container); + template = template.replace(replaceRegex, container); } else { - template = template.replace(placeholder, t.children); + template = template.replace(replaceRegex, t.children); } - if (t.count <= 2) { + + // the +1 accounts for the t.count's counting of the original template + if (t.count === matches.length + 1) { template = template.replace(t.contents, ''); } } diff --git a/packages/core/schematics/test/control_flow_migration_spec.ts b/packages/core/schematics/test/control_flow_migration_spec.ts index 124de02f69f23..df9d853f50148 100644 --- a/packages/core/schematics/test/control_flow_migration_spec.ts +++ b/packages/core/schematics/test/control_flow_migration_spec.ts @@ -2730,6 +2730,49 @@ describe('control flow migration', () => { expect(actual).toBe(expected); }); + + it('should migrate multiple if/else using the same ng-template', async () => { + writeFile('/comp.ts', ` + import {Component} from '@angular/core'; + import {NgIf} from '@angular/common'; + + @Component({ + selector: 'declare-comp', + templateUrl: 'comp.html', + }) + class DeclareComp {} + `); + + writeFile('/comp.html', [ + `
`, + `
presentation
`, + `
presentation
`, + `
`, + ``, + `

No Permissions

`, + `
`, + ].join('\n')); + + await runMigration(); + const actual = tree.readContent('/comp.html'); + + const expected = [ + `
`, + ` @if (hasPermission) {`, + `
presentation
`, + `} @else {\n`, + `

No Permissions

\n`, + `}`, + ` @if (someOtherPermission) {`, + `
presentation
`, + `} @else {\n`, + `

No Permissions

\n`, + `}`, + `
\n`, + ].join('\n'); + + expect(actual).toBe(expected); + }); }); describe('imports', () => {