Skip to content

Commit b96afb4

Browse files
aparzithePunderWoman
authored andcommitted
fix(migrations): handle reused templates in control flow migration (#63996)
The control flow migration was incorrectly removing `ng-template` elements in scenarios where they were referenced by multiple `*ngIf` directives' `else` clauses and also used independently via `ngTemplateOutlet`. PR Close #63996
1 parent 7e8e310 commit b96afb4

2 files changed

Lines changed: 128 additions & 40 deletions

File tree

‎packages/core/schematics/migrations/control-flow-migration/util.ts‎

Lines changed: 90 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,12 @@ const endMarkerRegex = new RegExp(endMarker, 'gm');
3232
const startI18nMarkerRegex = new RegExp(startI18nMarker, 'gm');
3333
const endI18nMarkerRegex = new RegExp(endI18nMarker, 'gm');
3434
const replaceMarkerRegex = new RegExp(`${startMarker}|${endMarker}`, 'gm');
35+
const PRIORITY_WEIGHT_TEMPLATE_REFERENCE_BY_OUTLET = 2;
36+
37+
interface TemplateUsageResult {
38+
isReferencedInTemplateOutlet: boolean;
39+
totalCount: number;
40+
}
3541

3642
/**
3743
* Analyzes a source file to find file that need to be migrated and the text ranges within them.
@@ -399,39 +405,6 @@ export function getTemplates(template: string): Map<string, Template> {
399405
return new Map<string, Template>();
400406
}
401407

402-
function countTemplateUsage(nodes: any[], templateName: string): number {
403-
let count = 0;
404-
let isReferencedInTemplateOutlet = false;
405-
406-
for (const node of nodes) {
407-
if (node.attrs) {
408-
for (const attr of node.attrs) {
409-
if (attr.name === '*ngTemplateOutlet' && attr.value === templateName.slice(1)) {
410-
isReferencedInTemplateOutlet = true;
411-
break;
412-
}
413-
414-
if (attr.name.trim() === templateName) {
415-
count++;
416-
}
417-
}
418-
}
419-
420-
if (node.children) {
421-
if (node.name === 'for') {
422-
for (const child of node.children) {
423-
if (child.value?.includes(templateName.slice(1))) {
424-
count++;
425-
}
426-
}
427-
}
428-
count += countTemplateUsage(node.children, templateName);
429-
}
430-
}
431-
432-
return isReferencedInTemplateOutlet ? count + 2 : count;
433-
}
434-
435408
export function updateTemplates(
436409
template: string,
437410
templates: Map<string, Template>,
@@ -468,9 +441,13 @@ export function processNgTemplates(
468441
const templates = getTemplates(template);
469442

470443
// swap placeholders and remove
471-
for (const [name, t] of templates) {
472-
const replaceRegex = new RegExp(getPlaceholder(name.slice(1)), 'g');
473-
const forRegex = new RegExp(getPlaceholder(name.slice(1), PlaceholderKind.Alternate), 'g');
444+
for (const [nameWithHash, t] of templates) {
445+
const name = nameWithHash.slice(1);
446+
const replaceRegex = new RegExp(getPlaceholder(name), 'g');
447+
const forRegex = new RegExp(
448+
getPlaceholder(nameWithHash.slice(1), PlaceholderKind.Alternate),
449+
'g',
450+
);
474451
const forMatches = [...template.matchAll(forRegex)];
475452
const matches = [...forMatches, ...template.matchAll(replaceRegex)];
476453
let safeToRemove = true;
@@ -495,7 +472,15 @@ export function processNgTemplates(
495472
(obj, index, self) => index === self.findIndex((t) => t.input === obj.input),
496473
);
497474

498-
if ((t.count === dist.length || t.count - matches.length === 1) && safeToRemove) {
475+
// Check if template is used by ngTemplateOutlet in addition to control flow
476+
const hasTemplateOutletUsage = checkForTemplateOutletUsage(template, nameWithHash.slice(1));
477+
478+
// Only remove template if it's safe to do so AND not used by ngTemplateOutlet
479+
if (
480+
(t.count === dist.length || t.count - matches.length === 1) &&
481+
safeToRemove &&
482+
!hasTemplateOutletUsage
483+
) {
499484
const refsInComponentFile = getViewChildOrViewChildrenNames(sourceFile);
500485
if (refsInComponentFile?.length > 0) {
501486
const templateRefs = getTemplateReferences(template);
@@ -524,6 +509,71 @@ export function processNgTemplates(
524509
}
525510
}
526511

512+
function analyzeTemplateUsage(nodes: any[], templateName: string): TemplateUsageResult {
513+
let count = 0;
514+
let isReferencedInTemplateOutlet = false;
515+
const templateNameWithHash = `#${templateName}`;
516+
517+
function traverseNodes(nodeList: any[]): void {
518+
for (const node of nodeList) {
519+
if (node.attrs) {
520+
for (const attr of node.attrs) {
521+
if (
522+
(attr.name === '*ngTemplateOutlet' || attr.name === '[ngTemplateOutlet]') &&
523+
attr.value === templateName
524+
) {
525+
isReferencedInTemplateOutlet = true;
526+
}
527+
528+
if (attr.name.trim() === templateNameWithHash) {
529+
count++;
530+
}
531+
}
532+
}
533+
534+
if (node.children) {
535+
if (node.name === 'for') {
536+
for (const child of node.children) {
537+
if (child.value?.includes(templateName)) {
538+
count++;
539+
}
540+
}
541+
}
542+
543+
traverseNodes(node.children);
544+
}
545+
}
546+
}
547+
548+
traverseNodes(nodes);
549+
550+
return {
551+
isReferencedInTemplateOutlet,
552+
totalCount: isReferencedInTemplateOutlet
553+
? count + PRIORITY_WEIGHT_TEMPLATE_REFERENCE_BY_OUTLET
554+
: count,
555+
};
556+
}
557+
558+
/**
559+
* Checks if a template is used by ngTemplateOutlet directive
560+
*/
561+
function checkForTemplateOutletUsage(template: string, templateName: string): boolean {
562+
const parsed = parseTemplate(template);
563+
if (parsed.tree === undefined) {
564+
return false;
565+
}
566+
567+
const result = analyzeTemplateUsage(parsed.tree.rootNodes, templateName);
568+
return result.isReferencedInTemplateOutlet;
569+
}
570+
571+
function countTemplateUsage(nodes: any[], templateNameWithHash: string): number {
572+
const templateName = templateNameWithHash.slice(1);
573+
const result = analyzeTemplateUsage(nodes, templateName);
574+
return result.totalCount;
575+
}
576+
527577
function getViewChildOrViewChildrenNames(sourceFile: ts.SourceFile): Array<string> {
528578
const names: Array<string> = [];
529579

@@ -554,12 +604,12 @@ function getTemplateReferences(template: string): string[] {
554604
return [];
555605
}
556606

557-
const references: string[] = [];
607+
const templateNameRefWithoutHash: string[] = [];
558608

559609
function visitNodes(nodes: any) {
560610
for (const node of nodes) {
561611
if (node?.name === 'ng-template') {
562-
references.push(...node.attrs?.map((ref: any) => ref?.name?.slice(1)));
612+
templateNameRefWithoutHash.push(...node.attrs?.map((ref: any) => ref?.name?.slice(1)));
563613
}
564614
if (node.children) {
565615
visitNodes(node.children);
@@ -568,7 +618,7 @@ function getTemplateReferences(template: string): string[] {
568618
}
569619

570620
visitNodes(parsed.tree.rootNodes);
571-
return references;
621+
return templateNameRefWithoutHash;
572622
}
573623

574624
function replaceRemainingPlaceholders(template: string): string {

‎packages/core/schematics/test/control_flow_migration_spec.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5074,6 +5074,44 @@ describe('control flow migration (ng update)', () => {
50745074
'@if (show) {<div>Some greek characters: θδ!</div>}',
50755075
);
50765076
});
5077+
5078+
it('should migrate multiple ngIf directives with same else template and preserve template outlet', async () => {
5079+
writeFile(
5080+
'/comp.ts',
5081+
`
5082+
import {Component} from '@angular/core';
5083+
import {NgIf} from '@angular/common';
5084+
5085+
@Component({
5086+
imports: [NgIf],
5087+
template: \`
5088+
<div *ngIf="1 == 1; else elseTemplate">
5089+
<h1>TEST</h1>
5090+
</div>
5091+
<div *ngIf="1 == 1; else elseTemplate">
5092+
<h1>TEST</h1>
5093+
</div>
5094+
5095+
<ng-container [ngTemplateOutlet]="elseTemplate"></ng-container>
5096+
<ng-template #elseTemplate>
5097+
<h1>Test</h1>
5098+
<div>Test</div>
5099+
</ng-template>
5100+
\`
5101+
})
5102+
class Comp {
5103+
}
5104+
`,
5105+
);
5106+
5107+
await runMigration();
5108+
const content = tree.readContent('/comp.ts');
5109+
5110+
expect(content.replace(/\s+/g, ' ')).toContain(
5111+
`<ng-container [ngTemplateOutlet]="elseTemplate"></ng-container>`,
5112+
);
5113+
expect(content.replace(/\s+/g, ' ')).toContain(`<ng-template #elseTemplate>`);
5114+
});
50775115
});
50785116

50795117
describe('formatting', () => {

0 commit comments

Comments
 (0)