ngx-sortablejs icon indicating copy to clipboard operation
ngx-sortablejs copied to clipboard

Use of trackBy with ngFor causes problems

Open cca-developer opened this issue 6 years ago • 8 comments

I have tried to make use of the trackBy function to increase performance as discussed here. When I add the trackBy function, though, my onUpdate function runs properly, but the items are always moved back to their original position. How can I get the benefits of both trackBy and sortableJS?

cca-developer avatar Mar 07 '18 19:03 cca-developer

Hi @cca-developer ,

I don't think this is currently possible. Marking for possible v3 improvements

smnbbrv avatar Mar 08 '18 10:03 smnbbrv

I managed to use trackBy with a nested array without any problems. Is this some special case?

<div [sortablejs]="chartArray" class="area">
    <div *ngFor="let chart of chartArray; trackBy: chartTracker">
      <app-line-chart 
        [name]="chart[0].label"
        [suggestedMin]="chart[2].data[0]"
        [suggestedMax]="chart[1].data[0]"
        [chartData]="chart"></app-line-chart>
    </div>
  </div> 

arno-le avatar Mar 09 '18 12:03 arno-le

@ygerg hem. Interesting. Probably I should start closing the issues without a plunkr / stackblitz samples :D

@cca-developer does it solve your problem?

smnbbrv avatar Mar 09 '18 14:03 smnbbrv

I didn't think mine was a special case:

<div [sortablejs]="itemsControl" [sortablejsOptions]="sortEventOptions" formArrayName="itemsControl">
        <proposal-item *ngFor="let item of itemsControl.controls; trackBy: trackItemByFn;  let i=index" [formGroupName]="i"
            [proposalItemForm]="item" 
            (removeItem)="removeItem($event)">
        </proposal-item>
</div>

Then the track by function is just:

trackItemByFn(index, item) {
    return index+","+item.proposalRevisionItemID;
}

Could mine be a problem because of the use of a form??

cca-developer avatar Mar 09 '18 15:03 cca-developer

@cca-developer If you already haven't, simplify the trackBy and try returning only item.proposalRevisionItemID. Or remove it completely, and then call (removeItem)="removeItem($event, index, item.proposalRevisionItemID), if that's what you need.

arno-le avatar Mar 12 '18 07:03 arno-le

@ygerg I did try all of those suggestions. The only way I can produce consistent and correct behavior of the sorting is by not having trackBy at all.

cca-developer avatar Mar 13 '18 14:03 cca-developer

Honestly I would be surprised if it worked out, because the current system does not even logically support it as is. That's why I think it should be covered / targeted in a newer version because it requires changes of the library engine

smnbbrv avatar Mar 14 '18 05:03 smnbbrv

Any updates on whether this support will be added anytime soon?

robtong21 avatar Nov 18 '21 16:11 robtong21