angular18

Track by multiple parameters with @for in Angular 18


Angular introduced a new notation for for loops with @for(x of y; track x).

I am looping through a list of objects that will have some properties modified over time. I want to track those properties. This is what I tried, which seems to work but I'm not 100% sure it does what I think it does :

@for (device of devices(); track device.foo && device.bar) {
    // ...
}

If device.foo or device.bar gets updated in one of the objects in the list, I want my angular to re-render the item in the list.

From what I found, the docs does not give any multi-properties examples : https://angular.dev/guide/templates/control-flow#track-for-calculating-difference-of-two-collections


Solution

  • track syntax is similar to *ngFor directive. You can define your custom track function like this:

    myCustomTrackBy(index: number, item: DeviceModel): string {
        return `${index}-${item.foo}-${item.bar}`;
    }
    @for (device of devices(); track myCustomTrackBy($index, device)) {
        // ...
    }

    And also keep in mind that using devices() function to retrieve items will negatively affect performance, because function/getters calls inside the template will be recalculated on every angular change detection tick. You'd better work with stream and use it with async pipe: @for (devices$ | async; track myCustomTrackBy(...)).