import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
<h3>Lists with trackBy</h3>
<ul>
<li *ngFor="let item of items; index as i; trackBy: trackById">{{ i + 1 }}. {{ item.name }} (id: {{ item.id }})</li>
</ul>
<button (click)="renameFirst()">Rename first</button>
<button (click)="shuffle()">Shuffle</button>
<button (click)="add()">Add item</button>
`
})
export class App {
items = [
{ id: 1, name: 'Angular' },
{ id: 2, name: 'React' },
{ id: 3, name: 'Vue' }
];
nextId = 4;
trackById(index, item) { return item.id; }
renameFirst() {
this.items = this.items.map((it, i) => i === 0 ? { ...it, name: it.name + ' *' } : it);
}
shuffle() {
const arr = [...this.items];
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
this.items = arr;
}
add() {
this.items = [...this.items, { id: this.nextId++, name: 'New ' + Date.now() }];
}
}
bootstrapApplication(App);
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Angular Lists - trackBy</title>
</head>
<body>
<app-root></app-root>
</body>
</html>