끄는 글자와 끌기 규칙 정하기Customize the drag label and rules
rowDrag의 label로 고스트 글자를, canDrag·canDrop으로 끌 수 있는 행과 놓을 수 있는 자리를, beforeRowDrop 훅으로 놓기 직전 확인을 정해요.Use the rowDrag label for the ghost text, canDrag and canDrop for which rows can be dragged and where they can be dropped, and the beforeRowDrop hook for a last check before the drop.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="selectFour">행 4개 선택</button>
</div>
<div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('selectFour').addEventListener('click', () => actions.selectFour(api));const rows = [
{ id: 1, name: '공지(고정)', locked: true },
{ id: 2, name: '업무 보고', locked: false },
{ id: 3, name: '회의록', locked: false },
{ id: 4, name: '예산안', locked: false },
{ id: 5, name: '계약서(잠금)', locked: true },
{ id: 6, name: '교육 자료', locked: false },
];
// label: 끄는 동안 고스트에 보일 글자를 돌려줘요(선택한 행의 이름을 이어 보여 줘요).
// canDrag: false를 돌려주면 그 행은 끌 수 없어요. canDrop: false를 돌려주면 그 자리에는 놓을 수 없어요(표시선도 안 나와요).
// hooks.beforeRowDrop: 놓기 직전에 false를 돌려주면 놓지 않아요(rowDragCancelled의 reason은 'hook').
export const options = {
columns: [
{ id: 'name', title: '문서', width: 200 },
{ id: 'locked', title: '잠금', kind: 'boolean', width: 70 },
],
selection: 'multiple',
rowDrag: {
label: ({ rows: dragged }) => dragged.map((r) => r.name).join(' · '),
canDrag: (row) => !row.locked,
canDrop: ({ targetKey }) => targetKey !== 1, // 맨 위 공지 앞·뒤에는 놓을 수 없어요
},
hooks: {
beforeRowDrop: ({ keys }) => keys.length <= 3, // 한 번에 3개까지만
},
rows,
rowKey: 'id',
};
export function setup(api, log) {
log({
ko: '잠긴 행은 끌 수 없고, 맨 위 공지 앞뒤에는 놓을 수 없어요. 고스트에는 끄는 행의 이름이 나와요.',
en: 'Locked rows cannot be dragged, and nothing can be dropped next to the top notice. The ghost shows the names of the dragged rows.',
});
const offs = [
api.on('rowDragCancelled', (e) => log({ ko: `취소했어요 (${e.reason})`, en: `Cancelled (${e.reason})` })),
api.on('rowDropped', (e) => log({ ko: `놓았어요: ${e.keys.join(', ')}`, en: `Dropped: ${e.keys.join(', ')}` })),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectFour: (api) => api.setSelectedKeys([2, 3, 4, 6]),
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>끄는 글자와 끌기 규칙 정하기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="selectFour">행 4개 선택</button>
</div>
<div id="grid" style="height: 360px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, name: '공지(고정)', locked: true },
{ id: 2, name: '업무 보고', locked: false },
{ id: 3, name: '회의록', locked: false },
{ id: 4, name: '예산안', locked: false },
{ id: 5, name: '계약서(잠금)', locked: true },
{ id: 6, name: '교육 자료', locked: false },
];
// label: 끄는 동안 고스트에 보일 글자를 돌려줘요(선택한 행의 이름을 이어 보여 줘요).
// canDrag: false를 돌려주면 그 행은 끌 수 없어요. canDrop: false를 돌려주면 그 자리에는 놓을 수 없어요(표시선도 안 나와요).
// hooks.beforeRowDrop: 놓기 직전에 false를 돌려주면 놓지 않아요(rowDragCancelled의 reason은 'hook').
const options = {
columns: [
{ id: 'name', title: '문서', width: 200 },
{ id: 'locked', title: '잠금', kind: 'boolean', width: 70 },
],
selection: 'multiple',
rowDrag: {
label: ({ rows: dragged }) => dragged.map((r) => r.name).join(' · '),
canDrag: (row) => !row.locked,
canDrop: ({ targetKey }) => targetKey !== 1, // 맨 위 공지 앞·뒤에는 놓을 수 없어요
},
hooks: {
beforeRowDrop: ({ keys }) => keys.length <= 3, // 한 번에 3개까지만
},
rows,
rowKey: 'id',
};
function setup(api, log) {
log({
ko: '잠긴 행은 끌 수 없고, 맨 위 공지 앞뒤에는 놓을 수 없어요. 고스트에는 끄는 행의 이름이 나와요.',
en: 'Locked rows cannot be dragged, and nothing can be dropped next to the top notice. The ghost shows the names of the dragged rows.',
});
const offs = [
api.on('rowDragCancelled', (e) => log({ ko: `취소했어요 (${e.reason})`, en: `Cancelled (${e.reason})` })),
api.on('rowDropped', (e) => log({ ko: `놓았어요: ${e.keys.join(', ')}`, en: `Dropped: ${e.keys.join(', ')}` })),
];
return () => offs.forEach((off) => off());
}
const actions = {
selectFour: (api) => api.setSelectedKeys([2, 3, 4, 6]),
};
options.ariaLabel = "끄는 글자와 끌기 규칙 정하기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('selectFour').addEventListener('click', () => actions.selectFour(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.selectFour(api)}
>행 4개 선택</button>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
locked: boolean;
}
const rows: Row[] = [
{ id: 1, name: '공지(고정)', locked: true },
{ id: 2, name: '업무 보고', locked: false },
{ id: 3, name: '회의록', locked: false },
{ id: 4, name: '예산안', locked: false },
{ id: 5, name: '계약서(잠금)', locked: true },
{ id: 6, name: '교육 자료', locked: false },
];
// label: 끄는 동안 고스트에 보일 글자를 돌려줘요(선택한 행의 이름을 이어 보여 줘요).
// canDrag: false를 돌려주면 그 행은 끌 수 없어요. canDrop: false를 돌려주면 그 자리에는 놓을 수 없어요(표시선도 안 나와요).
// hooks.beforeRowDrop: 놓기 직전에 false를 돌려주면 놓지 않아요(rowDragCancelled의 reason은 'hook').
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '문서', width: 200 },
{ id: 'locked', title: '잠금', kind: 'boolean', width: 70 },
],
selection: 'multiple',
rowDrag: {
label: ({ rows: dragged }) => dragged.map((r) => r.name).join(' · '),
canDrag: (row) => !row.locked,
canDrop: ({ targetKey }) => targetKey !== 1, // 맨 위 공지 앞·뒤에는 놓을 수 없어요
},
hooks: {
beforeRowDrop: ({ keys }) => keys.length <= 3, // 한 번에 3개까지만
},
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '잠긴 행은 끌 수 없고, 맨 위 공지 앞뒤에는 놓을 수 없어요. 고스트에는 끄는 행의 이름이 나와요.',
en: 'Locked rows cannot be dragged, and nothing can be dropped next to the top notice. The ghost shows the names of the dragged rows.',
});
const offs = [
api.on('rowDragCancelled', (e) =>
log({ ko: `취소했어요 (${e.reason})`, en: `Cancelled (${e.reason})` }),
),
api.on('rowDropped', (e) =>
log({ ko: `놓았어요: ${e.keys.join(', ')}`, en: `Dropped: ${e.keys.join(', ')}` }),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectFour: (api: GridApi<Row>) => api.setSelectedKeys([2, 3, 4, 6]),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.selectFour(api)"
>행 4개 선택</button>
</div>
<Grid style="height: 360px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
locked: boolean;
}
const rows: Row[] = [
{ id: 1, name: '공지(고정)', locked: true },
{ id: 2, name: '업무 보고', locked: false },
{ id: 3, name: '회의록', locked: false },
{ id: 4, name: '예산안', locked: false },
{ id: 5, name: '계약서(잠금)', locked: true },
{ id: 6, name: '교육 자료', locked: false },
];
// label: 끄는 동안 고스트에 보일 글자를 돌려줘요(선택한 행의 이름을 이어 보여 줘요).
// canDrag: false를 돌려주면 그 행은 끌 수 없어요. canDrop: false를 돌려주면 그 자리에는 놓을 수 없어요(표시선도 안 나와요).
// hooks.beforeRowDrop: 놓기 직전에 false를 돌려주면 놓지 않아요(rowDragCancelled의 reason은 'hook').
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '문서', width: 200 },
{ id: 'locked', title: '잠금', kind: 'boolean', width: 70 },
],
selection: 'multiple',
rowDrag: {
label: ({ rows: dragged }) => dragged.map((r) => r.name).join(' · '),
canDrag: (row) => !row.locked,
canDrop: ({ targetKey }) => targetKey !== 1, // 맨 위 공지 앞·뒤에는 놓을 수 없어요
},
hooks: {
beforeRowDrop: ({ keys }) => keys.length <= 3, // 한 번에 3개까지만
},
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '잠긴 행은 끌 수 없고, 맨 위 공지 앞뒤에는 놓을 수 없어요. 고스트에는 끄는 행의 이름이 나와요.',
en: 'Locked rows cannot be dragged, and nothing can be dropped next to the top notice. The ghost shows the names of the dragged rows.',
});
const offs = [
api.on('rowDragCancelled', (e) =>
log({ ko: `취소했어요 (${e.reason})`, en: `Cancelled (${e.reason})` }),
),
api.on('rowDropped', (e) =>
log({ ko: `놓았어요: ${e.keys.join(', ')}`, en: `Dropped: ${e.keys.join(', ')}` }),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectFour: (api: GridApi<Row>) => api.setSelectedKeys([2, 3, 4, 6]),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.selectFour(api)"
>행 4개 선택</button>
</div>
<mx-grid style="height: 360px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
locked: boolean;
}
const rows: Row[] = [
{ id: 1, name: '공지(고정)', locked: true },
{ id: 2, name: '업무 보고', locked: false },
{ id: 3, name: '회의록', locked: false },
{ id: 4, name: '예산안', locked: false },
{ id: 5, name: '계약서(잠금)', locked: true },
{ id: 6, name: '교육 자료', locked: false },
];
// label: 끄는 동안 고스트에 보일 글자를 돌려줘요(선택한 행의 이름을 이어 보여 줘요).
// canDrag: false를 돌려주면 그 행은 끌 수 없어요. canDrop: false를 돌려주면 그 자리에는 놓을 수 없어요(표시선도 안 나와요).
// hooks.beforeRowDrop: 놓기 직전에 false를 돌려주면 놓지 않아요(rowDragCancelled의 reason은 'hook').
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '문서', width: 200 },
{ id: 'locked', title: '잠금', kind: 'boolean', width: 70 },
],
selection: 'multiple',
rowDrag: {
label: ({ rows: dragged }) => dragged.map((r) => r.name).join(' · '),
canDrag: (row) => !row.locked,
canDrop: ({ targetKey }) => targetKey !== 1, // 맨 위 공지 앞·뒤에는 놓을 수 없어요
},
hooks: {
beforeRowDrop: ({ keys }) => keys.length <= 3, // 한 번에 3개까지만
},
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '잠긴 행은 끌 수 없고, 맨 위 공지 앞뒤에는 놓을 수 없어요. 고스트에는 끄는 행의 이름이 나와요.',
en: 'Locked rows cannot be dragged, and nothing can be dropped next to the top notice. The ghost shows the names of the dragged rows.',
});
const offs = [
api.on('rowDragCancelled', (e) =>
log({ ko: `취소했어요 (${e.reason})`, en: `Cancelled (${e.reason})` }),
),
api.on('rowDropped', (e) =>
log({ ko: `놓았어요: ${e.keys.join(', ')}`, en: `Dropped: ${e.keys.join(', ')}` }),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectFour: (api: GridApi<Row>) => api.setSelectedKeys([2, 3, 4, 6]),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="selectFour">Select 4 rows</button>
</div>
<div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('selectFour').addEventListener('click', () => actions.selectFour(api));const rows = [
{ id: 1, name: 'Notice (pinned)', locked: true },
{ id: 2, name: 'Work report', locked: false },
{ id: 3, name: 'Meeting notes', locked: false },
{ id: 4, name: 'Budget draft', locked: false },
{ id: 5, name: 'Contract (locked)', locked: true },
{ id: 6, name: 'Training material', locked: false },
];
// label: returns the text shown in the ghost while dragging (it joins the names of the selected rows).
// canDrag: a row cannot be dragged if it returns false. canDrop: nothing can be dropped at that position if it returns false (no indicator line either).
// hooks.beforeRowDrop: returning false just before the drop cancels it (the reason of rowDragCancelled is 'hook').
export const options = {
columns: [
{ id: 'name', title: 'Document', width: 200 },
{ id: 'locked', title: 'Locked', kind: 'boolean', width: 80 },
],
selection: 'multiple',
rowDrag: {
label: ({ rows: dragged }) => dragged.map((r) => r.name).join(' · '),
canDrag: (row) => !row.locked,
canDrop: ({ targetKey }) => targetKey !== 1, // nothing can be dropped before or after the top notice
},
hooks: {
beforeRowDrop: ({ keys }) => keys.length <= 3, // at most 3 at a time
},
rows,
rowKey: 'id',
};
export function setup(api, log) {
log('Locked rows cannot be dragged, and nothing can be dropped next to the top notice. The ghost shows the names of the dragged rows.');
const offs = [
api.on('rowDragCancelled', (e) => log(`Cancelled (${e.reason})`)),
api.on('rowDropped', (e) => log(`Dropped: ${e.keys.join(', ')}`)),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectFour: (api) => api.setSelectedKeys([2, 3, 4, 6]),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Customize the drag label and rules</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="selectFour">Select 4 rows</button>
</div>
<div id="grid" style="height: 360px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, name: 'Notice (pinned)', locked: true },
{ id: 2, name: 'Work report', locked: false },
{ id: 3, name: 'Meeting notes', locked: false },
{ id: 4, name: 'Budget draft', locked: false },
{ id: 5, name: 'Contract (locked)', locked: true },
{ id: 6, name: 'Training material', locked: false },
];
// label: returns the text shown in the ghost while dragging (it joins the names of the selected rows).
// canDrag: a row cannot be dragged if it returns false. canDrop: nothing can be dropped at that position if it returns false (no indicator line either).
// hooks.beforeRowDrop: returning false just before the drop cancels it (the reason of rowDragCancelled is 'hook').
const options = {
columns: [
{ id: 'name', title: 'Document', width: 200 },
{ id: 'locked', title: 'Locked', kind: 'boolean', width: 80 },
],
selection: 'multiple',
rowDrag: {
label: ({ rows: dragged }) => dragged.map((r) => r.name).join(' · '),
canDrag: (row) => !row.locked,
canDrop: ({ targetKey }) => targetKey !== 1, // nothing can be dropped before or after the top notice
},
hooks: {
beforeRowDrop: ({ keys }) => keys.length <= 3, // at most 3 at a time
},
rows,
rowKey: 'id',
};
function setup(api, log) {
log('Locked rows cannot be dragged, and nothing can be dropped next to the top notice. The ghost shows the names of the dragged rows.');
const offs = [
api.on('rowDragCancelled', (e) => log(`Cancelled (${e.reason})`)),
api.on('rowDropped', (e) => log(`Dropped: ${e.keys.join(', ')}`)),
];
return () => offs.forEach((off) => off());
}
const actions = {
selectFour: (api) => api.setSelectedKeys([2, 3, 4, 6]),
};
options.ariaLabel = "Customize the drag label and rules";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('selectFour').addEventListener('click', () => actions.selectFour(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.selectFour(api)}
>Select 4 rows</button>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
locked: boolean;
}
const rows: Row[] = [
{ id: 1, name: 'Notice (pinned)', locked: true },
{ id: 2, name: 'Work report', locked: false },
{ id: 3, name: 'Meeting notes', locked: false },
{ id: 4, name: 'Budget draft', locked: false },
{ id: 5, name: 'Contract (locked)', locked: true },
{ id: 6, name: 'Training material', locked: false },
];
// label: returns the text shown in the ghost while dragging (it joins the names of the selected rows).
// canDrag: a row cannot be dragged if it returns false. canDrop: nothing can be dropped at that position if it returns false (no indicator line either).
// hooks.beforeRowDrop: returning false just before the drop cancels it (the reason of rowDragCancelled is 'hook').
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Document', width: 200 },
{ id: 'locked', title: 'Locked', kind: 'boolean', width: 80 },
],
selection: 'multiple',
rowDrag: {
label: ({ rows: dragged }) => dragged.map((r) => r.name).join(' · '),
canDrag: (row) => !row.locked,
canDrop: ({ targetKey }) => targetKey !== 1, // nothing can be dropped before or after the top notice
},
hooks: {
beforeRowDrop: ({ keys }) => keys.length <= 3, // at most 3 at a time
},
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Locked rows cannot be dragged, and nothing can be dropped next to the top notice. The ghost shows the names of the dragged rows.',
);
const offs = [
api.on('rowDragCancelled', (e) => log(`Cancelled (${e.reason})`)),
api.on('rowDropped', (e) => log(`Dropped: ${e.keys.join(', ')}`)),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectFour: (api: GridApi<Row>) => api.setSelectedKeys([2, 3, 4, 6]),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.selectFour(api)"
>Select 4 rows</button>
</div>
<Grid style="height: 360px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
locked: boolean;
}
const rows: Row[] = [
{ id: 1, name: 'Notice (pinned)', locked: true },
{ id: 2, name: 'Work report', locked: false },
{ id: 3, name: 'Meeting notes', locked: false },
{ id: 4, name: 'Budget draft', locked: false },
{ id: 5, name: 'Contract (locked)', locked: true },
{ id: 6, name: 'Training material', locked: false },
];
// label: returns the text shown in the ghost while dragging (it joins the names of the selected rows).
// canDrag: a row cannot be dragged if it returns false. canDrop: nothing can be dropped at that position if it returns false (no indicator line either).
// hooks.beforeRowDrop: returning false just before the drop cancels it (the reason of rowDragCancelled is 'hook').
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Document', width: 200 },
{ id: 'locked', title: 'Locked', kind: 'boolean', width: 80 },
],
selection: 'multiple',
rowDrag: {
label: ({ rows: dragged }) => dragged.map((r) => r.name).join(' · '),
canDrag: (row) => !row.locked,
canDrop: ({ targetKey }) => targetKey !== 1, // nothing can be dropped before or after the top notice
},
hooks: {
beforeRowDrop: ({ keys }) => keys.length <= 3, // at most 3 at a time
},
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Locked rows cannot be dragged, and nothing can be dropped next to the top notice. The ghost shows the names of the dragged rows.',
);
const offs = [
api.on('rowDragCancelled', (e) => log(`Cancelled (${e.reason})`)),
api.on('rowDropped', (e) => log(`Dropped: ${e.keys.join(', ')}`)),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectFour: (api: GridApi<Row>) => api.setSelectedKeys([2, 3, 4, 6]),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.selectFour(api)"
>Select 4 rows</button>
</div>
<mx-grid style="height: 360px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
locked: boolean;
}
const rows: Row[] = [
{ id: 1, name: 'Notice (pinned)', locked: true },
{ id: 2, name: 'Work report', locked: false },
{ id: 3, name: 'Meeting notes', locked: false },
{ id: 4, name: 'Budget draft', locked: false },
{ id: 5, name: 'Contract (locked)', locked: true },
{ id: 6, name: 'Training material', locked: false },
];
// label: returns the text shown in the ghost while dragging (it joins the names of the selected rows).
// canDrag: a row cannot be dragged if it returns false. canDrop: nothing can be dropped at that position if it returns false (no indicator line either).
// hooks.beforeRowDrop: returning false just before the drop cancels it (the reason of rowDragCancelled is 'hook').
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Document', width: 200 },
{ id: 'locked', title: 'Locked', kind: 'boolean', width: 80 },
],
selection: 'multiple',
rowDrag: {
label: ({ rows: dragged }) => dragged.map((r) => r.name).join(' · '),
canDrag: (row) => !row.locked,
canDrop: ({ targetKey }) => targetKey !== 1, // nothing can be dropped before or after the top notice
},
hooks: {
beforeRowDrop: ({ keys }) => keys.length <= 3, // at most 3 at a time
},
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Locked rows cannot be dragged, and nothing can be dropped next to the top notice. The ghost shows the names of the dragged rows.',
);
const offs = [
api.on('rowDragCancelled', (e) => log(`Cancelled (${e.reason})`)),
api.on('rowDropped', (e) => log(`Dropped: ${e.keys.join(', ')}`)),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectFour: (api: GridApi<Row>) => api.setSelectedKeys([2, 3, 4, 6]),
};