헤더를 끌어 컬럼 순서 바꾸고, 잠그기Drag headers to reorder columns, and lock them
헤더를 끌면 컬럼 순서가 바뀌어요. '번호'처럼 움직이면 안 되는 컬럼은 movable: false로 잠그고, 폭 조절을 막거나 표 전체를 한 번에 잠글 수도 있어요. 코드로 옮기는 것은 잠금과 상관없이 돼요.Drag a header to reorder columns. Lock a column such as ID with movable: false, or lock all moving and resizing at once. Moving by code is never blocked.
코드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">
<select aria-label="잠금" id="lock">
<option value="free" selected>풀어 두기 (기본)</option>
<option value="all">전체 잠금</option>
</select>
<button type="button" id="amountFirst">금액을 맨 앞으로 (코드)</button>
<button type="button" id="groupLast">업무 묶음을 맨 뒤로 (코드)</button>
<button type="button" id="groupFirst">업무 묶음을 맨 앞으로 (코드)</button>
</div>
<div id="grid" style="height: 400px"></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('lock').addEventListener('change', (event) => actions.lock(api, event.target.value));
document.getElementById('amountFirst').addEventListener('click', () => actions.amountFirst(api));
document.getElementById('groupLast').addEventListener('click', () => actions.groupLast(api));
document.getElementById('groupFirst').addEventListener('click', () => actions.groupFirst(api));const names = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
// 컬럼 순서는 헤더를 끌어서 바꿔요. movable: false인 컬럼은 끌 수 없고,
// columnsMovable·columnsResizable로 그리드 전체를 한 번에 잠글 수도 있어요. 코드(moveColumn)는 잠겨 있어도 돼요.
export const options = {
columns: [
{ id: 'id', title: '번호 (잠금)', width: 100, movable: false, resizable: false, align: 'end' },
{ id: 'name', title: '이름', width: 130, minWidth: 90, maxWidth: 240 },
{ id: 'team', title: '팀', width: 130 },
{ id: 'status', title: '상태', width: 110 },
{ id: 'amount', title: '금액(원)', kind: 'number', width: 130, align: 'end' },
],
// 묶음(그룹) 제목을 끌면 묶인 컬럼이 한 덩어리로 같이 움직여요.
headerGroups: [{ id: 'work', title: '업무', children: ['team', 'status'] }],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5],
team: teams[(i * 3) % 4],
status: i % 3 === 0 ? '근무' : i % 3 === 1 ? '휴직' : '출장',
amount: 190000 + i * 73000,
})),
rowKey: 'id',
};
let say = () => { };
export function setup(api, log) {
say = log;
// 묶음을 옮기면 컬럼마다 이동 이벤트가 연달아 오기 때문에, 잠깐 모았다가 새 순서를 한 줄로 알려 줘요.
let timer;
let by = 'api';
const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const offs = [
api.on('columnMoved', (e) => {
by = e.source;
clearTimeout(timer);
timer = setTimeout(() => log({
ko: `새 순서(${by === 'api' ? '코드' : '직접'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
en: `New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
}), 80);
}),
api.on('columnResized', (e) => log({
ko: `${titleOf(e.columnId)} 폭 ${e.previousWidth} → ${e.width}px`,
en: `${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`,
})),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
function moveWork(api, where) {
const order = api.getColumnOrder();
const at = order.indexOf('team');
const already = where === 'first' ? at === 0 : at === order.length - 2;
if (already) {
say({
ko: `업무 묶음이 이미 맨 ${where === 'first' ? '앞' : '뒤'}에 있어요`,
en: `The work group is already at the ${where === 'first' ? 'start' : 'end'}`,
});
return;
}
api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
export const actions = {
// 묶음 전체를 한 덩어리로 옮겨요. 이미 그 자리에 있으면 바뀌는 게 없어서 알려 줘요.
groupLast: (api) => moveWork(api, 'last'),
groupFirst: (api) => moveWork(api, 'first'),
amountFirst: (api) => api.moveColumn('amount', 0),
lock: (api, value) => api.setOptions(value === 'all'
? { columnsMovable: false, columnsResizable: false }
: { columnsMovable: true, columnsResizable: true }),
};<!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">
<select aria-label="잠금" id="lock">
<option value="free" selected>풀어 두기 (기본)</option>
<option value="all">전체 잠금</option>
</select>
<button type="button" id="amountFirst">금액을 맨 앞으로 (코드)</button>
<button type="button" id="groupLast">업무 묶음을 맨 뒤로 (코드)</button>
<button type="button" id="groupFirst">업무 묶음을 맨 앞으로 (코드)</button>
</div>
<div id="grid" style="height: 400px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
// 컬럼 순서는 헤더를 끌어서 바꿔요. movable: false인 컬럼은 끌 수 없고,
// columnsMovable·columnsResizable로 그리드 전체를 한 번에 잠글 수도 있어요. 코드(moveColumn)는 잠겨 있어도 돼요.
const options = {
columns: [
{ id: 'id', title: '번호 (잠금)', width: 100, movable: false, resizable: false, align: 'end' },
{ id: 'name', title: '이름', width: 130, minWidth: 90, maxWidth: 240 },
{ id: 'team', title: '팀', width: 130 },
{ id: 'status', title: '상태', width: 110 },
{ id: 'amount', title: '금액(원)', kind: 'number', width: 130, align: 'end' },
],
// 묶음(그룹) 제목을 끌면 묶인 컬럼이 한 덩어리로 같이 움직여요.
headerGroups: [{ id: 'work', title: '업무', children: ['team', 'status'] }],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5],
team: teams[(i * 3) % 4],
status: i % 3 === 0 ? '근무' : i % 3 === 1 ? '휴직' : '출장',
amount: 190000 + i * 73000,
})),
rowKey: 'id',
};
let say = () => { };
function setup(api, log) {
say = log;
// 묶음을 옮기면 컬럼마다 이동 이벤트가 연달아 오기 때문에, 잠깐 모았다가 새 순서를 한 줄로 알려 줘요.
let timer;
let by = 'api';
const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const offs = [
api.on('columnMoved', (e) => {
by = e.source;
clearTimeout(timer);
timer = setTimeout(() => log({
ko: `새 순서(${by === 'api' ? '코드' : '직접'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
en: `New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
}), 80);
}),
api.on('columnResized', (e) => log({
ko: `${titleOf(e.columnId)} 폭 ${e.previousWidth} → ${e.width}px`,
en: `${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`,
})),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
function moveWork(api, where) {
const order = api.getColumnOrder();
const at = order.indexOf('team');
const already = where === 'first' ? at === 0 : at === order.length - 2;
if (already) {
say({
ko: `업무 묶음이 이미 맨 ${where === 'first' ? '앞' : '뒤'}에 있어요`,
en: `The work group is already at the ${where === 'first' ? 'start' : 'end'}`,
});
return;
}
api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
const actions = {
// 묶음 전체를 한 덩어리로 옮겨요. 이미 그 자리에 있으면 바뀌는 게 없어서 알려 줘요.
groupLast: (api) => moveWork(api, 'last'),
groupFirst: (api) => moveWork(api, 'first'),
amountFirst: (api) => api.moveColumn('amount', 0),
lock: (api, value) => api.setOptions(value === 'all'
? { columnsMovable: false, columnsResizable: false }
: { columnsMovable: true, columnsResizable: true }),
};
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('lock').addEventListener('change', (event) => actions.lock(api, event.target.value));
document.getElementById('amountFirst').addEventListener('click', () => actions.amountFirst(api));
document.getElementById('groupLast').addEventListener('click', () => actions.groupLast(api));
document.getElementById('groupFirst').addEventListener('click', () => actions.groupFirst(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">
<select
aria-label="잠금"
disabled={!api}
onChange={(event) => api && actions.lock(api, event.target.value)}
>
<option value="free">풀어 두기 (기본)</option>
<option value="all">전체 잠금</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.amountFirst(api)}
>금액을 맨 앞으로 (코드)</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.groupLast(api)}
>업무 묶음을 맨 뒤로 (코드)</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.groupFirst(api)}
>업무 묶음을 맨 앞으로 (코드)</button>
</div>
<Grid style={{ height: 400 }} 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;
team: string;
status: string;
amount: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
// 컬럼 순서는 헤더를 끌어서 바꿔요. movable: false인 컬럼은 끌 수 없고,
// columnsMovable·columnsResizable로 그리드 전체를 한 번에 잠글 수도 있어요. 코드(moveColumn)는 잠겨 있어도 돼요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '번호 (잠금)', width: 100, movable: false, resizable: false, align: 'end' },
{ id: 'name', title: '이름', width: 130, minWidth: 90, maxWidth: 240 },
{ id: 'team', title: '팀', width: 130 },
{ id: 'status', title: '상태', width: 110 },
{ id: 'amount', title: '금액(원)', kind: 'number', width: 130, align: 'end' },
],
// 묶음(그룹) 제목을 끌면 묶인 컬럼이 한 덩어리로 같이 움직여요.
headerGroups: [{ id: 'work', title: '업무', children: ['team', 'status'] }],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
status: i % 3 === 0 ? '근무' : i % 3 === 1 ? '휴직' : '출장',
amount: 190000 + i * 73000,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// 묶음을 옮기면 컬럼마다 이동 이벤트가 연달아 오기 때문에, 잠깐 모았다가 새 순서를 한 줄로 알려 줘요.
let timer: ReturnType<typeof setTimeout> | undefined;
let by: 'api' | 'pointer' | string = 'api';
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const offs = [
api.on('columnMoved', (e) => {
by = e.source;
clearTimeout(timer);
timer = setTimeout(
() =>
log({
ko: `새 순서(${by === 'api' ? '코드' : '직접'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
en: `New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
}),
80,
);
}),
api.on('columnResized', (e) =>
log({
ko: `${titleOf(e.columnId)} 폭 ${e.previousWidth} → ${e.width}px`,
en: `${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`,
}),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
function moveWork(api: GridApi<Row>, where: 'first' | 'last'): void {
const order = api.getColumnOrder();
const at = order.indexOf('team');
const already = where === 'first' ? at === 0 : at === order.length - 2;
if (already) {
say({
ko: `업무 묶음이 이미 맨 ${where === 'first' ? '앞' : '뒤'}에 있어요`,
en: `The work group is already at the ${where === 'first' ? 'start' : 'end'}`,
});
return;
}
api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
export const actions = {
// 묶음 전체를 한 덩어리로 옮겨요. 이미 그 자리에 있으면 바뀌는 게 없어서 알려 줘요.
groupLast: (api: GridApi<Row>) => moveWork(api, 'last'),
groupFirst: (api: GridApi<Row>) => moveWork(api, 'first'),
amountFirst: (api: GridApi<Row>) => api.moveColumn('amount', 0),
lock: (api: GridApi<Row>, value?: string) =>
api.setOptions(
value === 'all'
? { columnsMovable: false, columnsResizable: false }
: { columnsMovable: true, columnsResizable: true },
),
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="잠금"
:disabled="!api"
@change="api && actions.lock(api, ($event.target as HTMLSelectElement).value)"
>
<option value="free" selected>풀어 두기 (기본)</option>
<option value="all">전체 잠금</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.amountFirst(api)"
>금액을 맨 앞으로 (코드)</button>
<button
type="button"
:disabled="!api"
@click="api && actions.groupLast(api)"
>업무 묶음을 맨 뒤로 (코드)</button>
<button
type="button"
:disabled="!api"
@click="api && actions.groupFirst(api)"
>업무 묶음을 맨 앞으로 (코드)</button>
</div>
<Grid style="height: 400px" :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;
team: string;
status: string;
amount: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
// 컬럼 순서는 헤더를 끌어서 바꿔요. movable: false인 컬럼은 끌 수 없고,
// columnsMovable·columnsResizable로 그리드 전체를 한 번에 잠글 수도 있어요. 코드(moveColumn)는 잠겨 있어도 돼요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '번호 (잠금)', width: 100, movable: false, resizable: false, align: 'end' },
{ id: 'name', title: '이름', width: 130, minWidth: 90, maxWidth: 240 },
{ id: 'team', title: '팀', width: 130 },
{ id: 'status', title: '상태', width: 110 },
{ id: 'amount', title: '금액(원)', kind: 'number', width: 130, align: 'end' },
],
// 묶음(그룹) 제목을 끌면 묶인 컬럼이 한 덩어리로 같이 움직여요.
headerGroups: [{ id: 'work', title: '업무', children: ['team', 'status'] }],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
status: i % 3 === 0 ? '근무' : i % 3 === 1 ? '휴직' : '출장',
amount: 190000 + i * 73000,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// 묶음을 옮기면 컬럼마다 이동 이벤트가 연달아 오기 때문에, 잠깐 모았다가 새 순서를 한 줄로 알려 줘요.
let timer: ReturnType<typeof setTimeout> | undefined;
let by: 'api' | 'pointer' | string = 'api';
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const offs = [
api.on('columnMoved', (e) => {
by = e.source;
clearTimeout(timer);
timer = setTimeout(
() =>
log({
ko: `새 순서(${by === 'api' ? '코드' : '직접'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
en: `New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
}),
80,
);
}),
api.on('columnResized', (e) =>
log({
ko: `${titleOf(e.columnId)} 폭 ${e.previousWidth} → ${e.width}px`,
en: `${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`,
}),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
function moveWork(api: GridApi<Row>, where: 'first' | 'last'): void {
const order = api.getColumnOrder();
const at = order.indexOf('team');
const already = where === 'first' ? at === 0 : at === order.length - 2;
if (already) {
say({
ko: `업무 묶음이 이미 맨 ${where === 'first' ? '앞' : '뒤'}에 있어요`,
en: `The work group is already at the ${where === 'first' ? 'start' : 'end'}`,
});
return;
}
api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
export const actions = {
// 묶음 전체를 한 덩어리로 옮겨요. 이미 그 자리에 있으면 바뀌는 게 없어서 알려 줘요.
groupLast: (api: GridApi<Row>) => moveWork(api, 'last'),
groupFirst: (api: GridApi<Row>) => moveWork(api, 'first'),
amountFirst: (api: GridApi<Row>) => api.moveColumn('amount', 0),
lock: (api: GridApi<Row>, value?: string) =>
api.setOptions(
value === 'all'
? { columnsMovable: false, columnsResizable: false }
: { columnsMovable: true, columnsResizable: true },
),
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="잠금"
[disabled]="!api"
(change)="api && actions.lock(api, $any($event.target).value)"
>
<option value="free" selected>풀어 두기 (기본)</option>
<option value="all">전체 잠금</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.amountFirst(api)"
>금액을 맨 앞으로 (코드)</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.groupLast(api)"
>업무 묶음을 맨 뒤로 (코드)</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.groupFirst(api)"
>업무 묶음을 맨 앞으로 (코드)</button>
</div>
<mx-grid style="height: 400px" [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;
team: string;
status: string;
amount: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
// 컬럼 순서는 헤더를 끌어서 바꿔요. movable: false인 컬럼은 끌 수 없고,
// columnsMovable·columnsResizable로 그리드 전체를 한 번에 잠글 수도 있어요. 코드(moveColumn)는 잠겨 있어도 돼요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '번호 (잠금)', width: 100, movable: false, resizable: false, align: 'end' },
{ id: 'name', title: '이름', width: 130, minWidth: 90, maxWidth: 240 },
{ id: 'team', title: '팀', width: 130 },
{ id: 'status', title: '상태', width: 110 },
{ id: 'amount', title: '금액(원)', kind: 'number', width: 130, align: 'end' },
],
// 묶음(그룹) 제목을 끌면 묶인 컬럼이 한 덩어리로 같이 움직여요.
headerGroups: [{ id: 'work', title: '업무', children: ['team', 'status'] }],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
status: i % 3 === 0 ? '근무' : i % 3 === 1 ? '휴직' : '출장',
amount: 190000 + i * 73000,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// 묶음을 옮기면 컬럼마다 이동 이벤트가 연달아 오기 때문에, 잠깐 모았다가 새 순서를 한 줄로 알려 줘요.
let timer: ReturnType<typeof setTimeout> | undefined;
let by: 'api' | 'pointer' | string = 'api';
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const offs = [
api.on('columnMoved', (e) => {
by = e.source;
clearTimeout(timer);
timer = setTimeout(
() =>
log({
ko: `새 순서(${by === 'api' ? '코드' : '직접'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
en: `New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
}),
80,
);
}),
api.on('columnResized', (e) =>
log({
ko: `${titleOf(e.columnId)} 폭 ${e.previousWidth} → ${e.width}px`,
en: `${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`,
}),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
function moveWork(api: GridApi<Row>, where: 'first' | 'last'): void {
const order = api.getColumnOrder();
const at = order.indexOf('team');
const already = where === 'first' ? at === 0 : at === order.length - 2;
if (already) {
say({
ko: `업무 묶음이 이미 맨 ${where === 'first' ? '앞' : '뒤'}에 있어요`,
en: `The work group is already at the ${where === 'first' ? 'start' : 'end'}`,
});
return;
}
api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
export const actions = {
// 묶음 전체를 한 덩어리로 옮겨요. 이미 그 자리에 있으면 바뀌는 게 없어서 알려 줘요.
groupLast: (api: GridApi<Row>) => moveWork(api, 'last'),
groupFirst: (api: GridApi<Row>) => moveWork(api, 'first'),
amountFirst: (api: GridApi<Row>) => api.moveColumn('amount', 0),
lock: (api: GridApi<Row>, value?: string) =>
api.setOptions(
value === 'all'
? { columnsMovable: false, columnsResizable: false }
: { columnsMovable: true, columnsResizable: true },
),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<select aria-label="Lock" id="lock">
<option value="free" selected>Free (default)</option>
<option value="all">Lock everything</option>
</select>
<button type="button" id="amountFirst">Move amount first (code)</button>
<button type="button" id="groupLast">Move Work group last (code)</button>
<button type="button" id="groupFirst">Move Work group first (code)</button>
</div>
<div id="grid" style="height: 400px"></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('lock').addEventListener('change', (event) => actions.lock(api, event.target.value));
document.getElementById('amountFirst').addEventListener('click', () => actions.amountFirst(api));
document.getElementById('groupLast').addEventListener('click', () => actions.groupLast(api));
document.getElementById('groupFirst').addEventListener('click', () => actions.groupFirst(api));const names = ['Liam Carter', 'Emma Stone', 'Noah Hayes', 'Olivia Reed', 'Ethan Cole'];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
// The column order changes by dragging a header. A column with movable: false cannot be dragged,
// and columnsMovable and columnsResizable can lock the whole grid at once. Code (moveColumn) works even when locked.
export const options = {
columns: [
{ id: 'id', title: 'ID (locked)', width: 100, movable: false, resizable: false, align: 'end' },
{ id: 'name', title: 'Name', width: 130, minWidth: 90, maxWidth: 240 },
{ id: 'team', title: 'Team', width: 130 },
{ id: 'status', title: 'Status', width: 110 },
{ id: 'amount', title: 'Amount ($)', kind: 'number', width: 130, align: 'end' },
],
// Dragging a group title moves the grouped columns together as one block.
headerGroups: [{ id: 'work', title: 'Work', children: ['team', 'status'] }],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5],
team: teams[(i * 3) % 4],
status: i % 3 === 0 ? 'Working' : i % 3 === 1 ? 'On leave' : 'Traveling',
amount: 190 + i * 73,
})),
rowKey: 'id',
};
let say = () => { };
export function setup(api, log) {
say = log;
// Moving a group sends move events one column after another, so collect them briefly and report the new order in one line.
let timer;
let by = 'api';
const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const offs = [
api.on('columnMoved', (e) => {
by = e.source;
clearTimeout(timer);
timer = setTimeout(() => log(`New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`), 80);
}),
api.on('columnResized', (e) => log(`${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`)),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
function moveWork(api, where) {
const order = api.getColumnOrder();
const at = order.indexOf('team');
const already = where === 'first' ? at === 0 : at === order.length - 2;
if (already) {
say(`The work group is already at the ${where === 'first' ? 'start' : 'end'}`);
return;
}
api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
export const actions = {
// Move the whole group as one block. If it is already there nothing changes, so say so.
groupLast: (api) => moveWork(api, 'last'),
groupFirst: (api) => moveWork(api, 'first'),
amountFirst: (api) => api.moveColumn('amount', 0),
lock: (api, value) => api.setOptions(value === 'all'
? { columnsMovable: false, columnsResizable: false }
: { columnsMovable: true, columnsResizable: true }),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Drag headers to reorder columns, and lock them</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Lock" id="lock">
<option value="free" selected>Free (default)</option>
<option value="all">Lock everything</option>
</select>
<button type="button" id="amountFirst">Move amount first (code)</button>
<button type="button" id="groupLast">Move Work group last (code)</button>
<button type="button" id="groupFirst">Move Work group first (code)</button>
</div>
<div id="grid" style="height: 400px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = ['Liam Carter', 'Emma Stone', 'Noah Hayes', 'Olivia Reed', 'Ethan Cole'];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
// The column order changes by dragging a header. A column with movable: false cannot be dragged,
// and columnsMovable and columnsResizable can lock the whole grid at once. Code (moveColumn) works even when locked.
const options = {
columns: [
{ id: 'id', title: 'ID (locked)', width: 100, movable: false, resizable: false, align: 'end' },
{ id: 'name', title: 'Name', width: 130, minWidth: 90, maxWidth: 240 },
{ id: 'team', title: 'Team', width: 130 },
{ id: 'status', title: 'Status', width: 110 },
{ id: 'amount', title: 'Amount ($)', kind: 'number', width: 130, align: 'end' },
],
// Dragging a group title moves the grouped columns together as one block.
headerGroups: [{ id: 'work', title: 'Work', children: ['team', 'status'] }],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5],
team: teams[(i * 3) % 4],
status: i % 3 === 0 ? 'Working' : i % 3 === 1 ? 'On leave' : 'Traveling',
amount: 190 + i * 73,
})),
rowKey: 'id',
};
let say = () => { };
function setup(api, log) {
say = log;
// Moving a group sends move events one column after another, so collect them briefly and report the new order in one line.
let timer;
let by = 'api';
const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const offs = [
api.on('columnMoved', (e) => {
by = e.source;
clearTimeout(timer);
timer = setTimeout(() => log(`New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`), 80);
}),
api.on('columnResized', (e) => log(`${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`)),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
function moveWork(api, where) {
const order = api.getColumnOrder();
const at = order.indexOf('team');
const already = where === 'first' ? at === 0 : at === order.length - 2;
if (already) {
say(`The work group is already at the ${where === 'first' ? 'start' : 'end'}`);
return;
}
api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
const actions = {
// Move the whole group as one block. If it is already there nothing changes, so say so.
groupLast: (api) => moveWork(api, 'last'),
groupFirst: (api) => moveWork(api, 'first'),
amountFirst: (api) => api.moveColumn('amount', 0),
lock: (api, value) => api.setOptions(value === 'all'
? { columnsMovable: false, columnsResizable: false }
: { columnsMovable: true, columnsResizable: true }),
};
options.ariaLabel = "Drag headers to reorder columns, and lock them";
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('lock').addEventListener('change', (event) => actions.lock(api, event.target.value));
document.getElementById('amountFirst').addEventListener('click', () => actions.amountFirst(api));
document.getElementById('groupLast').addEventListener('click', () => actions.groupLast(api));
document.getElementById('groupFirst').addEventListener('click', () => actions.groupFirst(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">
<select
aria-label="Lock"
disabled={!api}
onChange={(event) => api && actions.lock(api, event.target.value)}
>
<option value="free">Free (default)</option>
<option value="all">Lock everything</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.amountFirst(api)}
>Move amount first (code)</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.groupLast(api)}
>Move Work group last (code)</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.groupFirst(api)}
>Move Work group first (code)</button>
</div>
<Grid style={{ height: 400 }} 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;
team: string;
status: string;
amount: number;
}
const names = ['Liam Carter', 'Emma Stone', 'Noah Hayes', 'Olivia Reed', 'Ethan Cole'];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
// The column order changes by dragging a header. A column with movable: false cannot be dragged,
// and columnsMovable and columnsResizable can lock the whole grid at once. Code (moveColumn) works even when locked.
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'ID (locked)', width: 100, movable: false, resizable: false, align: 'end' },
{ id: 'name', title: 'Name', width: 130, minWidth: 90, maxWidth: 240 },
{ id: 'team', title: 'Team', width: 130 },
{ id: 'status', title: 'Status', width: 110 },
{ id: 'amount', title: 'Amount ($)', kind: 'number', width: 130, align: 'end' },
],
// Dragging a group title moves the grouped columns together as one block.
headerGroups: [{ id: 'work', title: 'Work', children: ['team', 'status'] }],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
status: i % 3 === 0 ? 'Working' : i % 3 === 1 ? 'On leave' : 'Traveling',
amount: 190 + i * 73,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// Moving a group sends move events one column after another, so collect them briefly and report the new order in one line.
let timer: ReturnType<typeof setTimeout> | undefined;
let by: 'api' | 'pointer' | string = 'api';
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const offs = [
api.on('columnMoved', (e) => {
by = e.source;
clearTimeout(timer);
timer = setTimeout(
() =>
log(
`New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
),
80,
);
}),
api.on('columnResized', (e) =>
log(`${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
function moveWork(api: GridApi<Row>, where: 'first' | 'last'): void {
const order = api.getColumnOrder();
const at = order.indexOf('team');
const already = where === 'first' ? at === 0 : at === order.length - 2;
if (already) {
say(`The work group is already at the ${where === 'first' ? 'start' : 'end'}`);
return;
}
api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
export const actions = {
// Move the whole group as one block. If it is already there nothing changes, so say so.
groupLast: (api: GridApi<Row>) => moveWork(api, 'last'),
groupFirst: (api: GridApi<Row>) => moveWork(api, 'first'),
amountFirst: (api: GridApi<Row>) => api.moveColumn('amount', 0),
lock: (api: GridApi<Row>, value?: string) =>
api.setOptions(
value === 'all'
? { columnsMovable: false, columnsResizable: false }
: { columnsMovable: true, columnsResizable: true },
),
};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">
<select
aria-label="Lock"
:disabled="!api"
@change="api && actions.lock(api, ($event.target as HTMLSelectElement).value)"
>
<option value="free" selected>Free (default)</option>
<option value="all">Lock everything</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.amountFirst(api)"
>Move amount first (code)</button>
<button
type="button"
:disabled="!api"
@click="api && actions.groupLast(api)"
>Move Work group last (code)</button>
<button
type="button"
:disabled="!api"
@click="api && actions.groupFirst(api)"
>Move Work group first (code)</button>
</div>
<Grid style="height: 400px" :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;
team: string;
status: string;
amount: number;
}
const names = ['Liam Carter', 'Emma Stone', 'Noah Hayes', 'Olivia Reed', 'Ethan Cole'];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
// The column order changes by dragging a header. A column with movable: false cannot be dragged,
// and columnsMovable and columnsResizable can lock the whole grid at once. Code (moveColumn) works even when locked.
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'ID (locked)', width: 100, movable: false, resizable: false, align: 'end' },
{ id: 'name', title: 'Name', width: 130, minWidth: 90, maxWidth: 240 },
{ id: 'team', title: 'Team', width: 130 },
{ id: 'status', title: 'Status', width: 110 },
{ id: 'amount', title: 'Amount ($)', kind: 'number', width: 130, align: 'end' },
],
// Dragging a group title moves the grouped columns together as one block.
headerGroups: [{ id: 'work', title: 'Work', children: ['team', 'status'] }],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
status: i % 3 === 0 ? 'Working' : i % 3 === 1 ? 'On leave' : 'Traveling',
amount: 190 + i * 73,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// Moving a group sends move events one column after another, so collect them briefly and report the new order in one line.
let timer: ReturnType<typeof setTimeout> | undefined;
let by: 'api' | 'pointer' | string = 'api';
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const offs = [
api.on('columnMoved', (e) => {
by = e.source;
clearTimeout(timer);
timer = setTimeout(
() =>
log(
`New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
),
80,
);
}),
api.on('columnResized', (e) =>
log(`${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
function moveWork(api: GridApi<Row>, where: 'first' | 'last'): void {
const order = api.getColumnOrder();
const at = order.indexOf('team');
const already = where === 'first' ? at === 0 : at === order.length - 2;
if (already) {
say(`The work group is already at the ${where === 'first' ? 'start' : 'end'}`);
return;
}
api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
export const actions = {
// Move the whole group as one block. If it is already there nothing changes, so say so.
groupLast: (api: GridApi<Row>) => moveWork(api, 'last'),
groupFirst: (api: GridApi<Row>) => moveWork(api, 'first'),
amountFirst: (api: GridApi<Row>) => api.moveColumn('amount', 0),
lock: (api: GridApi<Row>, value?: string) =>
api.setOptions(
value === 'all'
? { columnsMovable: false, columnsResizable: false }
: { columnsMovable: true, columnsResizable: true },
),
};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">
<select
aria-label="Lock"
[disabled]="!api"
(change)="api && actions.lock(api, $any($event.target).value)"
>
<option value="free" selected>Free (default)</option>
<option value="all">Lock everything</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.amountFirst(api)"
>Move amount first (code)</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.groupLast(api)"
>Move Work group last (code)</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.groupFirst(api)"
>Move Work group first (code)</button>
</div>
<mx-grid style="height: 400px" [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;
team: string;
status: string;
amount: number;
}
const names = ['Liam Carter', 'Emma Stone', 'Noah Hayes', 'Olivia Reed', 'Ethan Cole'];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
// The column order changes by dragging a header. A column with movable: false cannot be dragged,
// and columnsMovable and columnsResizable can lock the whole grid at once. Code (moveColumn) works even when locked.
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'ID (locked)', width: 100, movable: false, resizable: false, align: 'end' },
{ id: 'name', title: 'Name', width: 130, minWidth: 90, maxWidth: 240 },
{ id: 'team', title: 'Team', width: 130 },
{ id: 'status', title: 'Status', width: 110 },
{ id: 'amount', title: 'Amount ($)', kind: 'number', width: 130, align: 'end' },
],
// Dragging a group title moves the grouped columns together as one block.
headerGroups: [{ id: 'work', title: 'Work', children: ['team', 'status'] }],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
status: i % 3 === 0 ? 'Working' : i % 3 === 1 ? 'On leave' : 'Traveling',
amount: 190 + i * 73,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// Moving a group sends move events one column after another, so collect them briefly and report the new order in one line.
let timer: ReturnType<typeof setTimeout> | undefined;
let by: 'api' | 'pointer' | string = 'api';
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const offs = [
api.on('columnMoved', (e) => {
by = e.source;
clearTimeout(timer);
timer = setTimeout(
() =>
log(
`New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
),
80,
);
}),
api.on('columnResized', (e) =>
log(`${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
function moveWork(api: GridApi<Row>, where: 'first' | 'last'): void {
const order = api.getColumnOrder();
const at = order.indexOf('team');
const already = where === 'first' ? at === 0 : at === order.length - 2;
if (already) {
say(`The work group is already at the ${where === 'first' ? 'start' : 'end'}`);
return;
}
api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
export const actions = {
// Move the whole group as one block. If it is already there nothing changes, so say so.
groupLast: (api: GridApi<Row>) => moveWork(api, 'last'),
groupFirst: (api: GridApi<Row>) => moveWork(api, 'first'),
amountFirst: (api: GridApi<Row>) => api.moveColumn('amount', 0),
lock: (api: GridApi<Row>, value?: string) =>
api.setOptions(
value === 'all'
? { columnsMovable: false, columnsResizable: false }
: { columnsMovable: true, columnsResizable: true },
),
};