PrimeNG列表框:如何通过拖放来重新排序项目?

时间:2020-10-12 13:43:16

标签: angular drag-and-drop listbox primeng

标题说明了一切。我有一个listbox,并且希望能够对显示的项目进行重新排序 通过拖放。当然也应该更新模型。我了解我需要使用 pDraggablepDroppable指令,但到目前为止,我只能使列表项“可拖动”,而不能将其“拖放”到其他列表项的上方或下方。

我也不知道用户放下项目后如何使用提供的事件更新我的模型。 最后,我想在每个项目的左侧都有一个图标,该图标应该是列表项目中唯一可拖动的部分(光标变为手形)。

我不附加任何代码,因为列表框非常简单。最后,我使用的是PrimeNG v9.0。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

好,所以我找到了。首先,已经有一个PrimeNG组件可以完成这项工作:OrderList。 但是,此组件将按钮添加到列表的左侧或右侧,并且这些按钮无法隐藏(这是愚蠢的)。因此,这是使用简单的Listbox的方法:

  1. let-index="index"中添加ng-template代码。您需要索引,因为您必须以编程方式更新模型。
  2. 在ng-template下方的pDraggable中声明pDroppable<div>指令(使用相同的名称:在我的情况下为 gens ) 。
  3. 在同一div中添加方法(onDragStart)(onDrop)。将索引传递给这两种方法。
  4. 最后定义一个dragHandle(可选)。就我而言,拖动手柄是条形图标

HTML:

<p-listbox [options]="generals" [(ngModel)]="selectedGeneral" (onChange)="onChange($event.value)"
    [listStyle]="{'height':'282px'}" [style]="{ width: '235px', height: '100%' }">
    <ng-template let-general let-index="index" pTemplate="item">
        <div class="ui-helper-clearfix" pDraggable="gens" pDroppable="gens" dragHandle=".barsHandle" (onDragStart)="onDragStart(index)" (onDrop)="onDrop(index)">
            <i class="fa fa-bars barsHandle"></i>
            <img [src]="getGenIcon(general.value)" style="margin-right: 5px;">
            <span style="vertical-align: middle;">{{general.label}}</span>
        </div>
    </ng-template>
</p-listbox>

TS:

onDragStart(index: number) {
    this.startIndex = index;
}

onDrop(dropIndex: number) {
    const general = this.generals[this.startIndex]; // get element
    this.generals.splice(this.startIndex, 1);       // delete from old position
    this.generals.splice(dropIndex, 0, general);    // add to new position
}
相关问题