From c64fe2739470ba014dd157bc4edf11a8731908ae Mon Sep 17 00:00:00 2001 From: Jessica Janiuk Date: Wed, 29 Nov 2023 10:44:01 -0500 Subject: [PATCH] fix(migrations): fix off by one issue with template removal in CF migration When ng-templates are removed, an extra space was being added when it was unnecessary. This resulted in malformed html if there was no space afterwards. fixes: #53248 --- .../control-flow-migration/types.ts | 2 +- .../test/control_flow_migration_spec.ts | 56 ++++++++++++++++++- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/packages/core/schematics/ng-generate/control-flow-migration/types.ts b/packages/core/schematics/ng-generate/control-flow-migration/types.ts index d22900d40a1b4..4819197a068bd 100644 --- a/packages/core/schematics/ng-generate/control-flow-migration/types.ts +++ b/packages/core/schematics/ng-generate/control-flow-migration/types.ts @@ -218,7 +218,7 @@ export class Template { } generateContents(tmpl: string) { - this.contents = tmpl.slice(this.el.sourceSpan.start.offset, this.el.sourceSpan.end.offset + 1); + this.contents = tmpl.slice(this.el.sourceSpan.start.offset, this.el.sourceSpan.end.offset); this.children = ''; if (this.el.children.length > 0) { this.children = tmpl.slice( diff --git a/packages/core/schematics/test/control_flow_migration_spec.ts b/packages/core/schematics/test/control_flow_migration_spec.ts index 9051853233ed3..120332e26b8ba 100644 --- a/packages/core/schematics/test/control_flow_migration_spec.ts +++ b/packages/core/schematics/test/control_flow_migration_spec.ts @@ -3685,7 +3685,59 @@ describe('control flow migration', () => { expect(actual).toBe(expected); }); + + it('should remove a template with no overlap with following elements', 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', [ + ``, + `
`, + `
    `, + `
  • `, + ` `, + ` `, + `

    Hmm

    `, + `
    `, + ` 0
    `, + `
  • `, + `
`, + `
`, + `
`, + ].join('\n')); + + await runMigration(); + const content = tree.readContent('/comp.html'); + + expect(content).toBe([ + `@if (stuff) {`, + `
`, + ` `, + `
`, + `}`, + ].join('\n')); + }); }); + describe('formatting', () => { it('should reformat else if', async () => { writeFile('/comp.ts', ` @@ -4052,7 +4104,7 @@ describe('control flow migration', () => { `Content here`, `} @else {`, `Else Content`, - `}`, + `}\n`, ``, ].join('\n')); }); @@ -4396,7 +4448,7 @@ describe('control flow migration', () => { await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( - 'template: `@if (isLoggedIn$ | async; as logIn) {\n Log In\n} @else {\n Log Out\n}`'); + 'template: `@if (isLoggedIn$ | async; as logIn) {\n Log In\n} @else {\n Log Out\n}\n`'); }); }); });