Rule Definition
Ensure your web application interactivity by accessing/manipulating the DOM tree with high performance queries/enumerators.
Remediation
Ensure you have added "track by" syntax into your ngFor block
Violation Code Sample
@Component({
selector: 'my-app',
template: `
<ul>
<li *ngFor="let item of collection;">{{item.id}}</li>
</ul>
<button (click)="getItems()">Refresh items</button>
`,
})
export class App {
constructor() {
this.collection = [{id: 1}, {id: 2}, {id: 3}];
}
getItems() {
this.collection = this.getItemsFromServer();
}
getItemsFromServer() {
return [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
}
}
Fixed Code Sample
@Component({
selector: 'my-app',
template: `
<ul>
<li *ngFor="let item of collection;trackBy: trackByFn">{{item.id}}</li>
</ul>
<button (click)="getItems()">Refresh items</button>
`,
})
export class App {
constructor() {
this.collection = [{id: 1}, {id: 2}, {id: 3}];
}
getItems() {
this.collection = this.getItemsFromServer();
}
getItemsFromServer() {
return [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
}
trackByFn(index, item) {
return item.id;
}
}
Reference
https://v2.angular.io/docs/ts/latest/api/common/index/NgFor-directive.html
https://blog.angular-university.io/angular-2-ngfor/
OMG CISQ
Related Technologies
Technical Criterion
CWE-1050 - Excessive Platform Resource Consumption within a Loop
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.