why track $index works fine for dynamic array?

Discussão em 'Angular' iniciado por Robert, Dezembro 1, 2024.

  1. Robert

    Robert Guest

    I'm experimenting with this code since I saw many people using track $index

    @Component({
    selector: 'app-root',
    template: `
    <ul>
    @for (item of array; track $index) {
    <li>{{$index}}: {{item.value}}</li>
    }
    </ul>

    <button (click)="removeSecond()">remove second</button>
    `,
    })
    export class App {
    array = [{ value: 'A' }, { value: 'B' }, { value: 'C' }, { value: 'D' }];

    removeSecond() {
    this.array.splice(1, 1);
    }
    }


    I expected that if the array changed by splice for example, it will show incorrect items but it doesn't and keep showing the proper ones, I thought it'd show A, B, C not A, C, D

    now I don't really understand how track work

    Continue reading...

Compartilhe esta Página