I am trying to understand trackBy
in angular ngFor
but I am not able to find any difference whether I use it or not.
Below is my code
.ts
export class AppComponent {
users = [
{id: 1, name: 'Test User 1', role: 'ADMIN'},
{id: 2, name: 'Test User 2', role: 'DEV'},
{id: 3, name: 'Test User 3', role: 'DEV'},
]
add(){
const id = this.users.length+1
let user = {
id: id,
name : `Test User ${id}`,
role: 'Dev'
}
// this.users.push(user)
this.users = [...this.users , user]
}
delete(i){
this.users.splice(i,1)
}
fnc(index, user){
return index
}
}
.html
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Role</th>
<th>Action</th>
</tr>
<tbody>
<tr *ngFor="let user of users;let i = index;trackBy:fnc">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.role}}</td>
<td>
<button (click)="add()">Add</button>
<button (click)="delete(i)">Delete</button>
</td>
</tr>
</tbody>
</table>
Working link https://stackblitz.com/edit/angular-ivy-3gnjr2
I am checking in developer tools inside the inspect tab. If I use trackBy or not whenever I add an Item or delete icon nodes are being rendered in same way