Skip to content

Commit 9269be6

Browse files
wKozamgechev
authored andcommitted
should fail when we have two ngFor and the second trackBy function is not present (#721)
1 parent 9eb3327 commit 9269be6

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/trackByFunctionRule.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ import { SourceFile } from 'typescript/lib/typescript';
44
import { NgWalker } from './angular/ngWalker';
55
import { BasicTemplateAstVisitor } from './angular/templates/basicTemplateAstVisitor';
66

7+
//current offSet into the template
8+
export let curOffSet = 0;
9+
710
export class Rule extends Rules.AbstractRule {
811
static readonly metadata: IRuleMetadata = {
912
description: 'Ensures a trackBy function is used.',
@@ -18,6 +21,7 @@ export class Rule extends Rules.AbstractRule {
1821
static readonly FAILURE_STRING = 'Missing trackBy function in ngFor directive';
1922

2023
apply(sourceFile: SourceFile): RuleFailure[] {
24+
curOffSet = 0;
2125
return this.applyWithWalker(new NgWalker(sourceFile, this.getOptions(), { templateVisitorCtrl: TrackByTemplateVisitor }));
2226
}
2327
}
@@ -39,9 +43,10 @@ class TrackByFunctionTemplateVisitor extends BasicTemplateAstVisitor {
3943
return;
4044
}
4145

42-
const pattern = /trackBy\s*:|\[ngForTrackBy\]\s*=\s*['"].*['"]/;
46+
const pattern = /\s*ngFor.*\s*trackBy\s*:|\[ngForTrackBy\]\s*=\s*['"].*['"]/;
4347

44-
if (pattern.test(context.codeWithMap.source!)) {
48+
if (pattern.test(context.codeWithMap.source!.substr(curOffSet))) {
49+
curOffSet = prop.sourceSpan.end.offset;
4550
return;
4651
}
4752

@@ -51,6 +56,7 @@ class TrackByFunctionTemplateVisitor extends BasicTemplateAstVisitor {
5156
start: { offset: startOffset }
5257
}
5358
} = prop;
59+
5460
context.addFailureFromStartToEnd(startOffset, endOffset, getFailureMessage());
5561
}
5662
}

test/trackByFunctionRule.spec.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,26 @@ describe(ruleName, () => {
5454
assertAnnotated({ message: getFailureMessage(), ruleName, source });
5555
});
5656

57+
it('should fail when we have two ngFor and the second trackBy function is not present', () => {
58+
const source = `
59+
@Component({
60+
template: \`
61+
<div *ngFor="let item of [1, 2, 3]; trackBy: trackByFn">
62+
{{ item }}
63+
</div>
64+
<ul>
65+
<li *ngFor="let item of [1, 2, 3];">
66+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
67+
{{ item }}
68+
</li>
69+
</ul>
70+
\`
71+
})
72+
class Bar {}
73+
`;
74+
assertAnnotated({ message: getFailureMessage(), ruleName, source });
75+
});
76+
5777
it('should fail when trackBy function is missing in multiple *ngFor', () => {
5878
const source = `
5979
@Component({

0 commit comments

Comments
 (0)