Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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