我猜您面临的问题是拖放时数据源(
this.data
)未更新。我们需要使用表行重新排序事件以编程方式执行此操作。
拖放时,您可以监听 prime-ng table 事件
drag
,而不是监听 onRowReorder
事件。
<div class="card">
<!-- remove groupRowsBy="group_by.id" will corrcet data afert drop ??? -->
<p-table
[value]="data"
sortMode="single"
[scrollable]="true"
rowGroupMode="subheader"
groupRowsBy="group_by.id"
(onRowReorder)="onRowReorder($event)"
>
...
这为您提供了两个细节
dragIndex
和dropIndex
。我们可以使用这两个细节并交换数组元素,我在下面的数组答案中使用了将元素移动到另一个位置:
onRowReorder(data: any) {
console.log(data);
array_move(this.data, data.dragIndex, data.dropIndex);
}
import { Component, OnInit } from '@angular/core';
import { ImportsModule } from './imports';
import { CommonModule } from '@angular/common';
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
}
@Component({
selector: 'table-subheader-grouping-demo',
templateUrl: 'table-subheader-grouping-demo.html',
standalone: true,
imports: [ImportsModule, CommonModule],
})
export class TableSubheaderGroupingDemo implements OnInit {
data: any[] = [];
constructor() {}
ngOnInit() {
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: 7,
groupOrder: 2,
group_by: { name: 'Support', id: 2 },
name: 'Support',
title: '2.1 Support',
},
];
}
rowTrackBy(_, item: any) {
return item.id;
}
onRowReorder(data: any) {
array_move(this.data, data.dragIndex, data.dropIndex);
}
}
<div class="card">
<!-- remove groupRowsBy="group_by.id" will corrcet data afert drop ??? -->
<p-table
[value]="data"
sortMode="single"
[scrollable]="true"
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>