I am using PrimeNG table and group reorder.
Currently, it is possible to drag and drop items within the same group, but dragging and dropping items from one group to another is not accurate yet. How can I identify which group I am dropping into?
MY CODE
Data
this.data = [
{
id: 1,
groupOrder: 1,
group_by: { name: 'Manager', id: 1 },
name: 'Manager 1',
title: '1.1 Manager 1',
},
{
id: 2,
code: 1.2,
groupOrder: 1,
group_by: { name: 'Manager', id: 1 },
name: 'Manager 2 ',
title: '1.2 Manager 2',
},
{
id: 3,
groupOrder: 2,
group_by: { name: 'Support', id: 2 },
name: 'Support tel',
title: '2.1 Support',
},
{
id: 4,
groupOrder: 2,
group_by: { name: 'Support', id: 2 },
name: 'Support app',
title: '2.2 Support',
},
];
TS:
function array_move(arr, old_index, new_index) {
if (new_index >= arr.length) {
var k = new_index - arr.length + 1;
while (k--) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
return arr; // for testing
}
rowTrackBy(_, item: any) {
return item.id;
}
onRowReorder(data: any) {
array_move(this.data, data.dragIndex, data.dropIndex);
}
HTML:
<div class="card">
<p-table
[value]="data"
sortMode="single"
[scrollable]="true"
[rowTrackBy]="rowTrackBy"
rowGroupMode="subheader"
groupRowsBy="group_by.id"
(onRowReorder)="onRowReorder($event)"
>
<ng-template pTemplate="header">
<tr>
<th>#</th>
<th>item</th>
</tr>
</ng-template>
<ng-template pTemplate="groupheader" let-item>
<tr pRowGroupHeader>
<td colspan="100" class="font-weight-bold">{{ item.group_by.name }}</td>
</tr>
</ng-template>
<ng-template pTemplate="body" let-item let-rowIndex="rowIndex">
<tr pDraggable="item" [pReorderableRow]="rowIndex">
<td>
<span class="pi pi-bars" pReorderableRowHandle></span>
</td>
<td>{{ item.code }} {{ item.name }}</td>
</tr>
</ng-template>
</p-table>
</div>
<pre>{{data | json}}</pre>
and this full code
To accurately identify which group an item is dropped into, you can determine the target group based on the dropIndex in the onRowReorder event.
Here's how you can try handling it:
onRowReorder(data: any) {
const draggedItem = this.data[data.dragIndex];
const dropTarget = this.data[data.dropIndex];
if (draggedItem.group_by.id !== dropTarget.group_by.id) {
draggedItem.group_by = { ...dropTarget.group_by };
draggedItem.groupOrder = dropTarget.groupOrder;
}
array_move(this.data, data.dragIndex, data.dropIndex);
}