angular ngFor trackBy does not work as I expected

Discussão em 'Angular' iniciado por user1663023, Novembro 15, 2024.

  1. user1663023

    user1663023 Guest

    When I read the doc (https://angular.io/api/common/NgForOf) for ngFor and trackBy, I thought I understood that Angular would only redo the DOM if the value returned by the trackBy function is changed, but when I played with it here (https://stackblitz.com/edit/angular-playground-bveczb), I found I actually don't understand it at all. Here's the essential part of my code:

    export class AppComponent {
    data = [
    { id: 1, text: 'one' },
    { id: 2, text: 'two' },
    { id: 3, text: 'three' },
    ];

    toUpper() {
    this.data.map(d => d.text = d.text.toUpperCase());
    }

    trackByIds (index: number, item: any) {
    return item.id;
    };
    }


    And:

    <div *ngFor="let d of data; trackBy: trackByIds">
    {{ d.text }}
    </div>
    <button (click)=toUpper()>To Upper Case</button>


    What I expected was clicking the button should NOT change the list from lower case to upper, but it did. I thought I used the trackByIds function for the trackBy in the *ngFor, and since the trackByIds only checks the id property of the items, so the change of anything other than id should not cause the DOM to be redone. I guess my understanding is wrong.

    Continue reading...

Compartilhe esta Página