Angular

Last Updated: 8/24/2023

ngFor track by

  • courses field is reset to new array whenever method is called
  • When the data is reset, angular reconstructs the ul element.
  • For small list there is no performance overhead
  • If you are working with large list or list with complex markup and if you reloading the data, Angular reconstructing the entire DOM object tree, this can be costly when dealing with large complex list
  • Angular by default tracks objects by their object identity (reference of the object in memory) default.
  • Objects in the array have different references in the memory
  • When we reset the data, even though the content is same, the object will be different from the previous one in the memory, angular sees this has new content thats why it reconstruct the DOM tree
  • You can instruct angular to track them by their id. If we redownload the data and if none of the properties change, angular will not re-render that dom element
  • Use trackBy and pass the name of the method as reference
  • For simple list no need for trackby
  • For large list with complex markup if performance is affected use trackby
courses;

loadCourses(){
	this.courses = [
		{id: 1, name: 'course1'},
		{id: 2, name: 'course2'}
	]
}
trackCourse(index, course) {
	return course ? course.id: undefined;
}
<button (click)="loadCourses()">Load Courses</button>
<ul>
	<li *ngFor="let course of courses;  trackBy: trackCourse">
		{{course.name}}
	</li>
</ul>