i'm having trouble sorting and array that has a trackBy function. The use case is as follows:
I have an item array. All these items have a z-index property. I also have a layer manager that can edit the z-index of each item. When I want to save my items, I want to sort my array according to the z-index property of each item. I also have a trackBy on my ngFor to limit the amount of change detection on the *ngFor.
With a trackBy function on my *ngFor, the items switch places when I sort the array (which is bad). If I remove the trackBy function this doesn't happen, and the items are sorted according to z-index.
The *ngFor:
<div class="item" *ngFor="let item of items; let i = index;trackBy:getUniqueIdentifier">
The trackBy function:
getUniqueIdentifier(index, item) {
return this.items.length + ', ' + this.languages._previewLanguage;
}
As you can see, the *ngFor is changed when the length of the items changes or if I switch my language settings. I've tried adding + ', ' + item.zIndex
but this doesn't work.
The sorting function:
sortItemsArrayByZIndex() {
this.items.sort((i1, i2) => {
return (i1.zIndex - i2.zIndex);
});
}
So it seems that trackBy and this sort function are in conflict for some reason. The result now is that when i use the sort function the the items array gets sorted according to z-index but the items also switch places, which means that their dimensions properties are switched for some reason.
What i want is that the items array is sorted according to z-index but that the items keep their dimensions.
How do i need to change my trackBy function or my sort function so that i get the result that i want?