0

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

oz1985oz
  • 397
  • 1
  • 8
  • 1
    Awesome for the stackblitz. Wouldn't returning the `index` over `item.id` work? – Clark Jan 16 '21 at 02:23
  • Thanks :) returning the `index` not working good, it counts the length of the array. I've changed the stackblitz to show it. You can switch the comment there. – oz1985oz Jan 16 '21 at 09:42
  • If you want the order to remain same work with the same object. Do not reassign a new object to the existing reference in the change methods. – Nicholas K Jan 16 '21 at 10:16
  • Also, once you make this change in the identify function `identify(index: number, item: User) { return item.id; }` the order does change but if you open the developer tools and navigate to the **Elements** tab you will see that the object with id two never gets re-rendered implying that the *trackBy* works as expected. – Nicholas K Jan 16 '21 at 10:35
  • 1
    @Nicholas k that is obvious, that’s not the question. trackby doesn’t rerender all the items if you added or deleted one here and there.. it does that when you change the entire order of the array. Change1() works but change2() doesn’t. – Itay Jan 16 '21 at 11:23

0 Answers0