From 20e7e21679f43cba74d4eaaa801c1d2e935517c6 Mon Sep 17 00:00:00 2001 From: cexbrayat Date: Thu, 12 Oct 2023 16:29:35 +0200 Subject: [PATCH] fix(core): do not remove used ng-template nodes in control flow migration (#52186) This fixes an issue where `ng-template` nodes were removed even when used in other places than control flow directives. Template to migrate: ```html
Block
``` Before: ```html ``` After: ```html
Block
``` PR Close #52186 --- .../control-flow-migration/util.ts | 9 ++++++- .../test/control_flow_migration_spec.ts | 27 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) 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 02c6bd0c652..ee41df93313 100644 --- a/packages/core/schematics/ng-generate/control-flow-migration/util.ts +++ b/packages/core/schematics/ng-generate/control-flow-migration/util.ts @@ -175,7 +175,7 @@ export function migrateTemplate(template: string): {migrated: string|null, error } for (const [_, t] of visitor.templates) { - if (t.count === 2) { + if (t.count < 2) { result = result.replace(t.contents, ''); } } @@ -282,6 +282,9 @@ function buildIfElseBlock( offset = offset + etm.preOffset(startBlock.length) + etm.postOffset(mainBlock.length + postBlock.length); + // decrease usage count of elseTmpl + elseTmpl.count--; + return {tmpl: updatedTmpl, offset}; } @@ -306,6 +309,10 @@ function buildIfThenElseBlock( offset = offset + etm.preOffset(startBlock.length) + etm.postOffset(postBlock.length); + // decrease usage count of thenTmpl and elseTmpl + thenTmpl.count--; + elseTmpl.count--; + return {tmpl: updatedTmpl, offset}; } diff --git a/packages/core/schematics/test/control_flow_migration_spec.ts b/packages/core/schematics/test/control_flow_migration_spec.ts index 1573fa5c639..c473786e272 100644 --- a/packages/core/schematics/test/control_flow_migration_spec.ts +++ b/packages/core/schematics/test/control_flow_migration_spec.ts @@ -336,6 +336,33 @@ describe('control flow migration', () => { ``, ].join('\n')); }); + + it('should not remove ng-templates used by other directives', async () => { + writeFile('/comp.ts', ` + import {Component} from '@angular/core'; + import {NgIf} from '@angular/common'; + + @Component({ + templateUrl: './comp.html' + }) + class Comp { + show = false; + } + `); + + writeFile('/comp.html', [ + `
Block
`, + ``, + ].join('\n')); + + await runMigration(); + const content = tree.readContent('/comp.html'); + + expect(content).toBe([ + `
Block
`, + ``, + ].join('\n')); + }); }); describe('ngFor', () => {