Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*ngFor trackBy multiple properties

Tags:

angular

I have an *ngFor directive used on an array of objects, which have quite a lot of properties.

I would like this *ngFor to be updated only when three of these properties are changed, but according to the documentation on TrackByFunction, there isn't a valid example of how to achieve that.

I tried to return an object with the properties in it, but it doesn't seem to work, as the template still gets rendered again when any other property is changed.

like image 664
Supamiu Avatar asked Dec 02 '17 09:12

Supamiu


Video Answer


2 Answers

Try add [ngForTrackBy]="trackSelectionsBy" to your element and your trackSelectionsBy method should look something like this:

public trackSelectionsBy(index: number, myObject: MyObject): any {
    return myObject.id + myObject.count + myObject.startTime;
}

And add your own properties to track by.

like image 129
Kungen Avatar answered Sep 25 '22 02:09

Kungen


I know this is old but the issue I think is how you handle the response to the tracking comparator. In your example you reply with another object which when compared to another object will always return as different.

So every time you make the object {a: "ehhhh", b:"bee", c:"cee"} because it has your limited set of properties, then compare it to another object even though the property values are the same they are not the same object.

If you returned JSON.stringify(trackedObj) then the two strings compared could return the boolean value needed to trigger change detection properly. But at that point I wonder what level of improvement the string conversion is over the standard, except it would allow items that didn't change to not be removed from the dom.. Interesting idea...

A Bit more detail in another SO: https://stackoverflow.com/a/1144249/1251604

like image 36
Dennis Smolek Avatar answered Sep 22 '22 02:09

Dennis Smolek