angularprimengprimeng-table

In Primeng Table how to get the reordered rows/list after reordering the rows?


      <p-table [value]="playlistTracks" [rows]="10" [showCurrentPageReport]="true"   [rowsPerPageOptions]="[10,25,50]"
    [totalRecords]="playlistTracks.length" [paginator]="true"
    currentPageReportTemplate="Showing {first} to {last} of {totalRecords} entries"
    [tableStyle]="{'min-width': '60rem'}" (onRowReorder)="tableReordered($event)"  (onSort)="tableSorted($event)">
    <ng-template pTemplate="caption">



  tableReordered(event: any) {
       this.reOrderedTracks = [];
       this.showDetailedGraph = false;
       this.showSummaryGraph = false;

       console.log('dragIndex :',event.dragIndex,'dropIndex :',event.dropIndex);
       
       // Remove the item from the drag index and insert it at the drop index
       const movedItem = this.playlistTracks.splice(event.dragIndex, 1)[0];  // Remove the item at dragIndex
       this.playlistTracks.splice(event.dropIndex, 0, movedItem);  // Insert the moved item at dropIndex

       console.log('reordered :',this.playlistTracks)
  }

but this way, the reordering of rows in table is being affected. For example, when i place item from 0 index to 1 it does not reorder, then if I remove:

const movedItem = this.playlistTracks.splice(event.dragIndex, 1)[0];  // Remove the item at dragIndex
this.playlistTracks.splice(event.dropIndex, 0, movedItem);  // Insert the moved item at dropIndex

from the method the reordering works fine.


Solution

  • this.playlistTracks.splice(event.dragIndex, 1)
    

    This removes the item at event.dragIndex in place. If you have the array [0,1,2,3], and the event.dragIndex is 1, the resulting array is [0,2,3].

    const movedItem = this.playlistTracks.splice(event.dragIndex, 1)[0]
    

    This assigns the first element of the changed array to movedItem, so in the example movedItem would be the element 0. Here is a short code example: Stackblitz

    When you want to reorder, you need to assign the correct item before you change playlistTrack using the correct index.

    You may also want to take a look at this, maybe what you want to do is already built-in: Reorder Table in Primeng