From 0f3cea4d575e9cf08b1f89e2ed5ac6d427f3ee1e 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 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
``` --- .../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 cd708491e2ea..b450efdad357 100644 --- a/packages/core/schematics/ng-generate/control-flow-migration/util.ts +++ b/packages/core/schematics/ng-generate/control-flow-migration/util.ts @@ -159,7 +159,7 @@ export function migrateTemplate(template: string): string|null { } for (const [_, t] of visitor.templates) { - if (t.count === 2) { + if (t.count < 2) { result = result.replace(t.contents, ''); } } @@ -255,6 +255,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}; } @@ -279,6 +282,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 e6f59566a34f..dab46943ee00 100644 --- a/packages/core/schematics/test/control_flow_migration_spec.ts +++ b/packages/core/schematics/test/control_flow_migration_spec.ts @@ -324,6 +324,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', () => {