I want the ngFor
not to re-render when the id change the index/position on the array.
The trackBy
method not working as I expected in this situation.
Consider code below, In the TS File
users: User[];
constructor() {
this.change1();
}
change1(): void {
this.users = [
{ id: 1, name: "one" },
{ id: 2, name: "two" },
{ id: 3, name: "three" },
{ id: 4, name: "four" },
{ id: 5, name: "five" },
];
}
change2(): void {
this.users = [
{ id: 3, name: "three" },
{ id: 5, name: "five" },
{ id: 1, name: "one" },
{ id: 2, name: "two" },
{ id: 6, name: "six" },
];
}
identify(index: number, item: User) {
return item.id;
}
and html
<ul>
<li *ngFor="let user of users; trackBy: identify">
{{user.name}}
</li>
</ul>
<button (click)="change1()">change 1</button>
<button (click)="change2()">change 2</button>
Clicking on the buttons changes the view yet the value of each of the id is still the same Here is an example on Stackblitz Demo