Skip to content

Commit

Permalink
fix(migrations): handle ngIf else condition with no whitespaces (#52504)
Browse files Browse the repository at this point in the history
Fixes that the control flow migration wasn't migrating an `*ngIf` with an `else` condition that doesn't have spaces before the `else`.

Fixes #52502.

PR Close #52504
  • Loading branch information
crisbeto authored and atscott committed Nov 3, 2023
1 parent 236b448 commit 6988a00
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
Expand Up @@ -214,8 +214,8 @@ export function migrateTemplate(template: string): {migrated: string|null, error
function migrateNgIf(
etm: ElementToMigrate, ngTemplates: Map<string, Template>, tmpl: string,
offset: number): Result {
const matchThen = etm.attr.value.match(/;\s+then/gm);
const matchElse = etm.attr.value.match(/;\s+else/gm);
const matchThen = etm.attr.value.match(/;\s*then/gm);
const matchElse = etm.attr.value.match(/;\s*else/gm);

if (matchThen && matchThen.length > 0) {
return buildIfThenElseBlock(etm, ngTemplates, tmpl, matchThen[0], matchElse![0], offset);
Expand Down
69 changes: 69 additions & 0 deletions packages/core/schematics/test/control_flow_migration_spec.ts
Expand Up @@ -391,6 +391,75 @@ describe('control flow migration', () => {
].join('\n'));
});

it('should migrate an if else case with no space after ;', 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', [
`<div>`,
`<span *ngIf="show;else elseBlock">Content here</span>`,
`<ng-template #elseBlock>Else Content</ng-template>`,
`</div>`,
].join('\n'));

await runMigration();
const content = tree.readContent('/comp.html');

expect(content).toBe([
`<div>`,
`@if (show) {`,
`<span>Content here</span>`,
`} @else {`,
`Else Content`,
`}`,
`</div>`,
].join('\n'));
});

it('should migrate an if then else case with no spaces before ;', 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', [
`<div>`,
`<span *ngIf="show;then thenBlock;else elseBlock">Ignored</span>`,
`<ng-template #thenBlock><div>THEN Stuff</div></ng-template>`,
`<ng-template #elseBlock>Else Content</ng-template>`,
`</div>`,
].join('\n'));

await runMigration();
const content = tree.readContent('/comp.html');

expect(content).toBe([
`<div>`,
`@if (show) {`,
`<div>THEN Stuff</div>`,
`} @else {`,
`Else Content`,
`}`,
`</div>`,
].join('\n'));
});

it('should migrate an if else case when the template is above the block', async () => {
writeFile('/comp.ts', `
import {Component} from '@angular/core';
Expand Down

0 comments on commit 6988a00

Please sign in to comment.