fix(migrations): Fixes issue with multiple if elses with same template (#52863)

This should fix the issue where if the same ng-template is used with multiple if / else statements, it replaces all usages properly.
fixes: #52854

PR Close #52863
This commit is contained in:
Jessica Janiuk 2023-11-13 12:10:13 -05:00
parent 9135dbaab2
commit 0e7b1daa8d
2 changed files with 51 additions and 6 deletions

View file

@ -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, '');
}
}

View file

@ -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', [
`<div>`,
` <div *ngIf="hasPermission; else noPermission">presentation</div>`,
` <div *ngIf="someOtherPermission; else noPermission">presentation</div>`,
`</div>`,
`<ng-template #noPermission>`,
` <p>No Permissions</p>`,
`</ng-template>`,
].join('\n'));
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<div>`,
` @if (hasPermission) {`,
`<div>presentation</div>`,
`} @else {\n`,
` <p>No Permissions</p>\n`,
`}`,
` @if (someOtherPermission) {`,
`<div>presentation</div>`,
`} @else {\n`,
` <p>No Permissions</p>\n`,
`}`,
`</div>\n`,
].join('\n');
expect(actual).toBe(expected);
});
});
describe('imports', () => {