Skip to content

Instantly share code, notes, and snippets.

@dpsthree
Created September 21, 2017 03:37
Example of trackBy
<!--
As the references change ngFor will continuously regenerate the DOM
However, the presence of trackBy provides ngFor some help.
It modifies the behavior so that it compares new data to old based on
the return value of the supplied trackBy method.
This allows Angular to reduce the amount of DOM update needed
-->
<ul>
<li *ngFor="let instructor of instructorList: trackBy: trackByName" >
<span>Instructor Name {{ instructor.name }}</span>
</li>
</ul>
import { Component } from '@angular/core';
import { ListService } from '../list.service';
@Component({
selector: 'app-instructor-list',
templateUrl: './instructor-list.component.html'
})
export class InstructorListComponent {
instructorList = {name: string}[];
constructor(private ls: ListService){
// In this example let's assume the list service provides the
// instructors as a realtime list of filtered instructors.
// New updates are sent at regular intervals regardless of content change.
// As a result the object references change with each update.
ls.getList()
.subscribe(list => this.instructorList = list);
}
// Treat the instructor name as the unique identifier for the object
trackByName(index, instructor) {
return instructor.name;
}
}
@extrawurst
Copy link

extrawurst commented Nov 8, 2017

isn't that supposed to be a ';' instead of colon after instructorList (instructor-list.component.html line 9)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment