Created
September 21, 2017 03:37
Example of trackBy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
isn't that supposed to be a ';' instead of colon after
instructorList
(instructor-list.component.html line 9)?