我希望在ngFor
id 更改数组上的索引/位置时不重新渲染。在这种情况下,该trackBy
方法无法正常工作。
考虑下面的代码,在 TS 文件中
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;
}
和 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>
单击按钮会更改视图,但每个 id 的值仍然相同 这是Stackblitz Demo上的示例