IgxGrid のドラッグアンドドロップ機能を用いて、行の位置を移動することができます。
rowDraggable オプションを有効化することで、行のドラッグができるようになります。igxDrop ディレクティブを有効化することで、行のドロップを受け取ることができるようになります。igxDrop ディレクティブのイベント名(Output 名)は、バージョンによって異なります。次に、バージョン毎の実装方法を紹介します。
製品バージョン 8.2.0 以前での実装方法
igxDrop ディレクティブの onDrop イベントをハンドルし、行の入れ替え処理を実装します。
<!--app.component.html-->
<igx-grid #grid1
[data]="data"
[primaryKey]="'ID'"
[width]="'700px'" [height]="'300px'"
[displayDensity]="'compact'"
[rowDraggable]="true"
igxDrop (onDrop)="onDropAllowed($event)">
<igx-column *ngFor="let c of columns"
[field]="c.field"
[header]="c.headerText"
[width]="c.width"
[resizable]="c.resizable"
[pinned]="c.pinned"
[sortable]="true"
[movable]="true">
</igx-column>
</igx-grid>
製品バージョン 8.2.0 以降での実装方法
8.2.0 以降では、onDrop イベントではなく dropped イベントを利用します。仕様変更に関する情報は GitHub を参照下さい。
<igx-grid #grid1
[data]="data"
[primaryKey]="'ID'"
[width]="'700px'" [height]="'300px'"
[displayDensity]="'compact'"
[rowDraggable]="true"
igxDrop (dropped)="onDropAllowed($event)">
<igx-column *ngFor="let c of columns"
[field]="c.field"
[header]="c.headerText"
[width]="c.width"
[resizable]="c.resizable"
[pinned]="c.pinned"
[sortable]="true"
[movable]="true">
</igx-column>
</igx-grid>
バージョン毎の実装はここまでです。
製品バージョン共通の実装
以降、製品バージョン共通の実装です。
igxDrop ディレクティブの onDrop イベントや dropped イベント発生時に、行の入れ替えを行います。
// app.component.ts
onDropAllowed(args) {
args.cancel = true;
const event = args.originalEvent;
const currRowIndex = this.getCurrentRowIndex(this.grid1.rowList.toArray(),
{ x: event.pageX, y: event.pageY });
// ドラッグで移動した行をグリッドから削除
this.grid1.deleteRow(args.dragData.rowID);
// ドラッグで移動した行を、新しいインデックスに挿入
this.data.splice(currRowIndex, 0, args.dragData.rowData);
}
private getCurrentRowIndex(rowList, cursorPosition) {
for (const row of rowList) {
const rowRect = row.nativeElement.getBoundingClientRect();
if (cursorPosition.y > rowRect.top && cursorPosition.y < rowRect.bottom &&
cursorPosition.x > rowRect.left && cursorPosition.x < rowRect.right) {
// ドロップ位置の行インデックスをリターン
return this.data.indexOf(this.data.find((r) => r.ID === row.rowData.ID));
}
}
throw new Error('行インデックスの取得に失敗しました。');
}
実行結果
