Angular ngFor rerender trackBy 改变阵列位置时

问题描述

我希望 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,{ id: 1,{ 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

上的示例

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)