Skip to content

Commit

Permalink
fix(migrations): Fixes issue with multiple if elses with same template (
Browse files Browse the repository at this point in the history
angular#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: angular#52854

PR Close angular#52863
  • Loading branch information
thePunderWoman authored and rlmestre committed Jan 26, 2024
1 parent 054e8d2 commit 2be3733
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 6 deletions.
Expand Up @@ -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, '');
}
}
Expand Down
43 changes: 43 additions & 0 deletions packages/core/schematics/test/control_flow_migration_spec.ts
Expand Up @@ -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', () => {
Expand Down

0 comments on commit 2be3733

Please sign in to comment.