엑셀처럼 칸을 끌어서 고르기Drag to pick cells like a spreadsheet
칸을 끌면 구간이 골라지고, Shift+클릭으로 넓히고, Ctrl+클릭으로 구간을 더할 수 있어요. 행 단위·한 칸 단위·선택 끄기도 설정 한 줄로 바꿔요.Drag to pick a block of cells, widen it with Shift+click and add another block with Ctrl+click. Row-only, single-cell and no-selection modes are one setting away.
코드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="mode">
<option value="cell-multiple" selected>칸 여러 구간 (기본)</option>
<option value="cell-single">칸 하나</option>
<option value="row-single">행 하나</option>
<option value="row-multiple">행 여러 개</option>
<option value="none">선택 끄기</option>
</select>
<button type="button" id="report">고른 구간 알려 주기</button>
<button type="button" id="pickBlock">코드로 구간 고르기</button>
<button type="button" id="pickCell">코드로 한 칸 고르기</button>
<button type="button" id="clear">선택 지우기</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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('report').addEventListener('click', () => actions.report(api));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickCell').addEventListener('click', () => actions.pickCell(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));// 카페 메뉴별 분기 판매량(잔). 칸을 끌어서 구간을 고르는 연습용 표예요.
const menus = [
'아메리카노',
'카페라떼',
'바닐라라떼',
'콜드브루',
'카푸치노',
'녹차라떼',
'딸기스무디',
'레몬에이드',
'허니브레드',
'치즈케이크',
];
// cellSelection: 'multiple'이면 칸을 끌어서 구간을 고르고, Shift+클릭으로 구간을 넓히고,
// Ctrl+클릭(또는 Ctrl+끌기)으로 구간을 더해요. 행 선택(selection)과는 따로 켜고 끄고, 함께 써도 돼요.
export const options = {
columns: [
{ id: 'menu', title: '메뉴', width: 140 },
...['q1', 'q2', 'q3', 'q4'].map((id, i) => ({
id,
title: `${i + 1}분기`,
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
})),
],
rows: menus.map((menu, i) => ({
id: i + 1,
menu,
q1: 1200 + ((i * 370) % 900),
q2: 1450 + ((i * 290) % 800),
q3: 980 + ((i * 410) % 1100),
q4: 1800 + ((i * 230) % 700),
})),
rowKey: 'id',
cellSelection: 'multiple',
};
const MODES = {
'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
'cell-single': { cellSelection: 'single', selection: 'none' },
'row-single': { cellSelection: 'none', selection: 'single' },
'row-multiple': { cellSelection: 'none', selection: 'multiple' },
none: { cellSelection: 'none', selection: 'none' },
};
// 버튼(actions)도 알림을 남길 수 있게 setup에서 받은 log를 보관해요.
let say = () => { };
const NEED_MULTIPLE = {
ko: "이 방식에서는 코드로 고를 수 없어요. 위 '선택 방식'을 칸 모드로 바꿔 보세요",
en: "This mode cannot select by code. Switch 'Selection mode' above to a cell mode",
};
export function setup(api, log) {
say = log;
const offCells = api.on('cellSelectionChanged', ({ ranges }) => log({
ko: `고른 칸 ${api.getSelectedCells().length}개 (구간 ${ranges.length}개)`,
en: `Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`,
}));
const offRows = api.on('selectionChanged', ({ selectedKeys }) => log({ ko: `고른 행 ${selectedKeys.length}개`, en: `Selected rows: ${selectedKeys.length}` }));
return () => {
offCells();
offRows();
};
}
// 칸 이름을 "메뉴·행번호 / 컬럼 제목" 꼴로 읽기 좋게 바꿔요.
const label = (api, ref) => {
const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey}의 ${title}`;
};
export const actions = {
// 선택 방식을 바꿔요. 바꾸기 전에 이전 선택은 지워요.
mode: (api, value) => {
api.clearCellSelection();
api.clearSelection();
api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']);
},
// 지금 고른 구간이 어디서 어디까지인지 알려 줘요(getCellRanges).
report: (api) => {
const ranges = api.getCellRanges();
say({
ko: ranges.length === 0
? '고른 칸이 없어요. 먼저 칸을 끌어 보세요'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
en: ranges.length === 0
? 'No cells selected. Drag across some cells first'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
});
},
// 코드로 구간을 골라요: 2행 1분기부터 4행 3분기까지. 칸 선택이 꺼져 있으면 알려 줘요.
pickBlock: (api) => {
if (api.getOptions().cellSelection !== 'multiple')
return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
},
// 칸 하나만 골라요.
pickCell: (api) => {
if (api.getOptions().cellSelection === 'none')
return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 5, columnId: 'q2' });
},
clear: (api) => {
api.clearCellSelection();
api.clearSelection();
},
};<!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="mode">
<option value="cell-multiple" selected>칸 여러 구간 (기본)</option>
<option value="cell-single">칸 하나</option>
<option value="row-single">행 하나</option>
<option value="row-multiple">행 여러 개</option>
<option value="none">선택 끄기</option>
</select>
<button type="button" id="report">고른 구간 알려 주기</button>
<button type="button" id="pickBlock">코드로 구간 고르기</button>
<button type="button" id="pickCell">코드로 한 칸 고르기</button>
<button type="button" id="clear">선택 지우기</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 menus = [
'아메리카노',
'카페라떼',
'바닐라라떼',
'콜드브루',
'카푸치노',
'녹차라떼',
'딸기스무디',
'레몬에이드',
'허니브레드',
'치즈케이크',
];
// cellSelection: 'multiple'이면 칸을 끌어서 구간을 고르고, Shift+클릭으로 구간을 넓히고,
// Ctrl+클릭(또는 Ctrl+끌기)으로 구간을 더해요. 행 선택(selection)과는 따로 켜고 끄고, 함께 써도 돼요.
const options = {
columns: [
{ id: 'menu', title: '메뉴', width: 140 },
...['q1', 'q2', 'q3', 'q4'].map((id, i) => ({
id,
title: `${i + 1}분기`,
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
})),
],
rows: menus.map((menu, i) => ({
id: i + 1,
menu,
q1: 1200 + ((i * 370) % 900),
q2: 1450 + ((i * 290) % 800),
q3: 980 + ((i * 410) % 1100),
q4: 1800 + ((i * 230) % 700),
})),
rowKey: 'id',
cellSelection: 'multiple',
};
const MODES = {
'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
'cell-single': { cellSelection: 'single', selection: 'none' },
'row-single': { cellSelection: 'none', selection: 'single' },
'row-multiple': { cellSelection: 'none', selection: 'multiple' },
none: { cellSelection: 'none', selection: 'none' },
};
// 버튼(actions)도 알림을 남길 수 있게 setup에서 받은 log를 보관해요.
let say = () => { };
const NEED_MULTIPLE = {
ko: "이 방식에서는 코드로 고를 수 없어요. 위 '선택 방식'을 칸 모드로 바꿔 보세요",
en: "This mode cannot select by code. Switch 'Selection mode' above to a cell mode",
};
function setup(api, log) {
say = log;
const offCells = api.on('cellSelectionChanged', ({ ranges }) => log({
ko: `고른 칸 ${api.getSelectedCells().length}개 (구간 ${ranges.length}개)`,
en: `Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`,
}));
const offRows = api.on('selectionChanged', ({ selectedKeys }) => log({ ko: `고른 행 ${selectedKeys.length}개`, en: `Selected rows: ${selectedKeys.length}` }));
return () => {
offCells();
offRows();
};
}
// 칸 이름을 "메뉴·행번호 / 컬럼 제목" 꼴로 읽기 좋게 바꿔요.
const label = (api, ref) => {
const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey}의 ${title}`;
};
const actions = {
// 선택 방식을 바꿔요. 바꾸기 전에 이전 선택은 지워요.
mode: (api, value) => {
api.clearCellSelection();
api.clearSelection();
api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']);
},
// 지금 고른 구간이 어디서 어디까지인지 알려 줘요(getCellRanges).
report: (api) => {
const ranges = api.getCellRanges();
say({
ko: ranges.length === 0
? '고른 칸이 없어요. 먼저 칸을 끌어 보세요'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
en: ranges.length === 0
? 'No cells selected. Drag across some cells first'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
});
},
// 코드로 구간을 골라요: 2행 1분기부터 4행 3분기까지. 칸 선택이 꺼져 있으면 알려 줘요.
pickBlock: (api) => {
if (api.getOptions().cellSelection !== 'multiple')
return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
},
// 칸 하나만 골라요.
pickCell: (api) => {
if (api.getOptions().cellSelection === 'none')
return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 5, columnId: 'q2' });
},
clear: (api) => {
api.clearCellSelection();
api.clearSelection();
},
};
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('report').addEventListener('click', () => actions.report(api));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickCell').addEventListener('click', () => actions.pickCell(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(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.mode(api, event.target.value)}
>
<option value="cell-multiple">칸 여러 구간 (기본)</option>
<option value="cell-single">칸 하나</option>
<option value="row-single">행 하나</option>
<option value="row-multiple">행 여러 개</option>
<option value="none">선택 끄기</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.report(api)}
>고른 구간 알려 주기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pickBlock(api)}
>코드로 구간 고르기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pickCell(api)}
>코드로 한 칸 고르기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>선택 지우기</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;
menu: string;
q1: number;
q2: number;
q3: number;
q4: number;
}
// 카페 메뉴별 분기 판매량(잔). 칸을 끌어서 구간을 고르는 연습용 표예요.
const menus = [
'아메리카노',
'카페라떼',
'바닐라라떼',
'콜드브루',
'카푸치노',
'녹차라떼',
'딸기스무디',
'레몬에이드',
'허니브레드',
'치즈케이크',
];
// cellSelection: 'multiple'이면 칸을 끌어서 구간을 고르고, Shift+클릭으로 구간을 넓히고,
// Ctrl+클릭(또는 Ctrl+끌기)으로 구간을 더해요. 행 선택(selection)과는 따로 켜고 끄고, 함께 써도 돼요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: '메뉴', width: 140 },
...(['q1', 'q2', 'q3', 'q4'] as const).map((id, i) => ({
id,
title: `${i + 1}분기`,
kind: 'number' as const,
width: 110,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR'),
})),
],
rows: menus.map((menu, i) => ({
id: i + 1,
menu,
q1: 1200 + ((i * 370) % 900),
q2: 1450 + ((i * 290) % 800),
q3: 980 + ((i * 410) % 1100),
q4: 1800 + ((i * 230) % 700),
})),
rowKey: 'id',
cellSelection: 'multiple',
};
const MODES: Record<string, Partial<GridOptions<Row>>> = {
'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
'cell-single': { cellSelection: 'single', selection: 'none' },
'row-single': { cellSelection: 'none', selection: 'single' },
'row-multiple': { cellSelection: 'none', selection: 'multiple' },
none: { cellSelection: 'none', selection: 'none' },
};
// 버튼(actions)도 알림을 남길 수 있게 setup에서 받은 log를 보관해요.
let say: (message: LogText) => void = () => {};
const NEED_MULTIPLE = {
ko: "이 방식에서는 코드로 고를 수 없어요. 위 '선택 방식'을 칸 모드로 바꿔 보세요",
en: "This mode cannot select by code. Switch 'Selection mode' above to a cell mode",
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const offCells = api.on('cellSelectionChanged', ({ ranges }) =>
log({
ko: `고른 칸 ${api.getSelectedCells().length}개 (구간 ${ranges.length}개)`,
en: `Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`,
}),
);
const offRows = api.on('selectionChanged', ({ selectedKeys }) =>
log({ ko: `고른 행 ${selectedKeys.length}개`, en: `Selected rows: ${selectedKeys.length}` }),
);
return () => {
offCells();
offRows();
};
}
// 칸 이름을 "메뉴·행번호 / 컬럼 제목" 꼴로 읽기 좋게 바꿔요.
const label = (api: GridApi<Row>, ref: { rowKey: string | number; columnId: string }): string => {
const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey}의 ${title}`;
};
export const actions = {
// 선택 방식을 바꿔요. 바꾸기 전에 이전 선택은 지워요.
mode: (api: GridApi<Row>, value?: string) => {
api.clearCellSelection();
api.clearSelection();
api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']!);
},
// 지금 고른 구간이 어디서 어디까지인지 알려 줘요(getCellRanges).
report: (api: GridApi<Row>) => {
const ranges = api.getCellRanges();
say({
ko:
ranges.length === 0
? '고른 칸이 없어요. 먼저 칸을 끌어 보세요'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
en:
ranges.length === 0
? 'No cells selected. Drag across some cells first'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
});
},
// 코드로 구간을 골라요: 2행 1분기부터 4행 3분기까지. 칸 선택이 꺼져 있으면 알려 줘요.
pickBlock: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection !== 'multiple') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
},
// 칸 하나만 골라요.
pickCell: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection === 'none') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 5, columnId: 'q2' });
},
clear: (api: GridApi<Row>) => {
api.clearCellSelection();
api.clearSelection();
},
};버튼을 누르면 이 예제의 코드가 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.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="cell-multiple" selected>칸 여러 구간 (기본)</option>
<option value="cell-single">칸 하나</option>
<option value="row-single">행 하나</option>
<option value="row-multiple">행 여러 개</option>
<option value="none">선택 끄기</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.report(api)">고른 구간 알려 주기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.pickBlock(api)"
>코드로 구간 고르기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.pickCell(api)"
>코드로 한 칸 고르기</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">선택 지우기</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;
menu: string;
q1: number;
q2: number;
q3: number;
q4: number;
}
// 카페 메뉴별 분기 판매량(잔). 칸을 끌어서 구간을 고르는 연습용 표예요.
const menus = [
'아메리카노',
'카페라떼',
'바닐라라떼',
'콜드브루',
'카푸치노',
'녹차라떼',
'딸기스무디',
'레몬에이드',
'허니브레드',
'치즈케이크',
];
// cellSelection: 'multiple'이면 칸을 끌어서 구간을 고르고, Shift+클릭으로 구간을 넓히고,
// Ctrl+클릭(또는 Ctrl+끌기)으로 구간을 더해요. 행 선택(selection)과는 따로 켜고 끄고, 함께 써도 돼요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: '메뉴', width: 140 },
...(['q1', 'q2', 'q3', 'q4'] as const).map((id, i) => ({
id,
title: `${i + 1}분기`,
kind: 'number' as const,
width: 110,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR'),
})),
],
rows: menus.map((menu, i) => ({
id: i + 1,
menu,
q1: 1200 + ((i * 370) % 900),
q2: 1450 + ((i * 290) % 800),
q3: 980 + ((i * 410) % 1100),
q4: 1800 + ((i * 230) % 700),
})),
rowKey: 'id',
cellSelection: 'multiple',
};
const MODES: Record<string, Partial<GridOptions<Row>>> = {
'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
'cell-single': { cellSelection: 'single', selection: 'none' },
'row-single': { cellSelection: 'none', selection: 'single' },
'row-multiple': { cellSelection: 'none', selection: 'multiple' },
none: { cellSelection: 'none', selection: 'none' },
};
// 버튼(actions)도 알림을 남길 수 있게 setup에서 받은 log를 보관해요.
let say: (message: LogText) => void = () => {};
const NEED_MULTIPLE = {
ko: "이 방식에서는 코드로 고를 수 없어요. 위 '선택 방식'을 칸 모드로 바꿔 보세요",
en: "This mode cannot select by code. Switch 'Selection mode' above to a cell mode",
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const offCells = api.on('cellSelectionChanged', ({ ranges }) =>
log({
ko: `고른 칸 ${api.getSelectedCells().length}개 (구간 ${ranges.length}개)`,
en: `Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`,
}),
);
const offRows = api.on('selectionChanged', ({ selectedKeys }) =>
log({ ko: `고른 행 ${selectedKeys.length}개`, en: `Selected rows: ${selectedKeys.length}` }),
);
return () => {
offCells();
offRows();
};
}
// 칸 이름을 "메뉴·행번호 / 컬럼 제목" 꼴로 읽기 좋게 바꿔요.
const label = (api: GridApi<Row>, ref: { rowKey: string | number; columnId: string }): string => {
const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey}의 ${title}`;
};
export const actions = {
// 선택 방식을 바꿔요. 바꾸기 전에 이전 선택은 지워요.
mode: (api: GridApi<Row>, value?: string) => {
api.clearCellSelection();
api.clearSelection();
api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']!);
},
// 지금 고른 구간이 어디서 어디까지인지 알려 줘요(getCellRanges).
report: (api: GridApi<Row>) => {
const ranges = api.getCellRanges();
say({
ko:
ranges.length === 0
? '고른 칸이 없어요. 먼저 칸을 끌어 보세요'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
en:
ranges.length === 0
? 'No cells selected. Drag across some cells first'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
});
},
// 코드로 구간을 골라요: 2행 1분기부터 4행 3분기까지. 칸 선택이 꺼져 있으면 알려 줘요.
pickBlock: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection !== 'multiple') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
},
// 칸 하나만 골라요.
pickCell: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection === 'none') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 5, columnId: 'q2' });
},
clear: (api: GridApi<Row>) => {
api.clearCellSelection();
api.clearSelection();
},
};버튼을 누르면 이 예제의 코드가 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.mode(api, $any($event.target).value)"
>
<option value="cell-multiple" selected>칸 여러 구간 (기본)</option>
<option value="cell-single">칸 하나</option>
<option value="row-single">행 하나</option>
<option value="row-multiple">행 여러 개</option>
<option value="none">선택 끄기</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.report(api)"
>고른 구간 알려 주기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pickBlock(api)"
>코드로 구간 고르기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pickCell(api)"
>코드로 한 칸 고르기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>선택 지우기</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;
menu: string;
q1: number;
q2: number;
q3: number;
q4: number;
}
// 카페 메뉴별 분기 판매량(잔). 칸을 끌어서 구간을 고르는 연습용 표예요.
const menus = [
'아메리카노',
'카페라떼',
'바닐라라떼',
'콜드브루',
'카푸치노',
'녹차라떼',
'딸기스무디',
'레몬에이드',
'허니브레드',
'치즈케이크',
];
// cellSelection: 'multiple'이면 칸을 끌어서 구간을 고르고, Shift+클릭으로 구간을 넓히고,
// Ctrl+클릭(또는 Ctrl+끌기)으로 구간을 더해요. 행 선택(selection)과는 따로 켜고 끄고, 함께 써도 돼요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: '메뉴', width: 140 },
...(['q1', 'q2', 'q3', 'q4'] as const).map((id, i) => ({
id,
title: `${i + 1}분기`,
kind: 'number' as const,
width: 110,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR'),
})),
],
rows: menus.map((menu, i) => ({
id: i + 1,
menu,
q1: 1200 + ((i * 370) % 900),
q2: 1450 + ((i * 290) % 800),
q3: 980 + ((i * 410) % 1100),
q4: 1800 + ((i * 230) % 700),
})),
rowKey: 'id',
cellSelection: 'multiple',
};
const MODES: Record<string, Partial<GridOptions<Row>>> = {
'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
'cell-single': { cellSelection: 'single', selection: 'none' },
'row-single': { cellSelection: 'none', selection: 'single' },
'row-multiple': { cellSelection: 'none', selection: 'multiple' },
none: { cellSelection: 'none', selection: 'none' },
};
// 버튼(actions)도 알림을 남길 수 있게 setup에서 받은 log를 보관해요.
let say: (message: LogText) => void = () => {};
const NEED_MULTIPLE = {
ko: "이 방식에서는 코드로 고를 수 없어요. 위 '선택 방식'을 칸 모드로 바꿔 보세요",
en: "This mode cannot select by code. Switch 'Selection mode' above to a cell mode",
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const offCells = api.on('cellSelectionChanged', ({ ranges }) =>
log({
ko: `고른 칸 ${api.getSelectedCells().length}개 (구간 ${ranges.length}개)`,
en: `Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`,
}),
);
const offRows = api.on('selectionChanged', ({ selectedKeys }) =>
log({ ko: `고른 행 ${selectedKeys.length}개`, en: `Selected rows: ${selectedKeys.length}` }),
);
return () => {
offCells();
offRows();
};
}
// 칸 이름을 "메뉴·행번호 / 컬럼 제목" 꼴로 읽기 좋게 바꿔요.
const label = (api: GridApi<Row>, ref: { rowKey: string | number; columnId: string }): string => {
const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey}의 ${title}`;
};
export const actions = {
// 선택 방식을 바꿔요. 바꾸기 전에 이전 선택은 지워요.
mode: (api: GridApi<Row>, value?: string) => {
api.clearCellSelection();
api.clearSelection();
api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']!);
},
// 지금 고른 구간이 어디서 어디까지인지 알려 줘요(getCellRanges).
report: (api: GridApi<Row>) => {
const ranges = api.getCellRanges();
say({
ko:
ranges.length === 0
? '고른 칸이 없어요. 먼저 칸을 끌어 보세요'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
en:
ranges.length === 0
? 'No cells selected. Drag across some cells first'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
});
},
// 코드로 구간을 골라요: 2행 1분기부터 4행 3분기까지. 칸 선택이 꺼져 있으면 알려 줘요.
pickBlock: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection !== 'multiple') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
},
// 칸 하나만 골라요.
pickCell: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection === 'none') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 5, columnId: 'q2' });
},
clear: (api: GridApi<Row>) => {
api.clearCellSelection();
api.clearSelection();
},
};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="Selection mode" id="mode">
<option value="cell-multiple" selected>Many blocks of cells</option>
<option value="cell-single">One cell</option>
<option value="row-single">One row</option>
<option value="row-multiple">Many rows</option>
<option value="none">No selection</option>
</select>
<button type="button" id="report">Tell me the selection</button>
<button type="button" id="pickBlock">Pick a block in code</button>
<button type="button" id="pickCell">Pick one cell in code</button>
<button type="button" id="clear">Clear selection</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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('report').addEventListener('click', () => actions.report(api));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickCell').addEventListener('click', () => actions.pickCell(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));// Quarterly cups sold per cafe menu item. A practice table for selecting ranges by dragging cells.
const menus = [
'Americano',
'Cafe Latte',
'Vanilla Latte',
'Cold Brew',
'Cappuccino',
'Green Tea Latte',
'Strawberry Smoothie',
'Lemonade',
'Honey Bread',
'Cheesecake',
];
// With cellSelection: 'multiple', drag across cells to pick a range, Shift+click to extend it,
// and Ctrl+click (or Ctrl+drag) to add another range. It is switched on and off separately from row selection (selection), and both can be used together.
export const options = {
columns: [
{ id: 'menu', title: 'Menu', width: 170 },
...['q1', 'q2', 'q3', 'q4'].map((id, i) => ({
id,
title: `Q${i + 1}`,
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
})),
],
rows: menus.map((menu, i) => ({
id: i + 1,
menu,
q1: 1200 + ((i * 370) % 900),
q2: 1450 + ((i * 290) % 800),
q3: 980 + ((i * 410) % 1100),
q4: 1800 + ((i * 230) % 700),
})),
rowKey: 'id',
cellSelection: 'multiple',
};
const MODES = {
'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
'cell-single': { cellSelection: 'single', selection: 'none' },
'row-single': { cellSelection: 'none', selection: 'single' },
'row-multiple': { cellSelection: 'none', selection: 'multiple' },
none: { cellSelection: 'none', selection: 'none' },
};
// Keep the log received in setup so the buttons (actions) can leave messages too.
let say = () => { };
const NEED_MULTIPLE = "This mode cannot select by code. Switch 'Selection mode' above to a cell mode";
export function setup(api, log) {
say = log;
const offCells = api.on('cellSelectionChanged', ({ ranges }) => log(`Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`));
const offRows = api.on('selectionChanged', ({ selectedKeys }) => log(`Selected rows: ${selectedKeys.length}`));
return () => {
offCells();
offRows();
};
}
// Turn a cell reference into a readable "menu item / column title" label.
const label = (api, ref) => {
const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey} ${title}`;
};
export const actions = {
// Change the selection mode. The previous selection is cleared first.
mode: (api, value) => {
api.clearCellSelection();
api.clearSelection();
api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']);
},
// Report where the current ranges start and end (getCellRanges).
report: (api) => {
const ranges = api.getCellRanges();
say(ranges.length === 0
? 'No cells selected. Drag across some cells first'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '));
},
// Select a range by code: from row 2 Q1 to row 4 Q3. Tell the user if cell selection is off.
pickBlock: (api) => {
if (api.getOptions().cellSelection !== 'multiple')
return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
},
// Select a single cell.
pickCell: (api) => {
if (api.getOptions().cellSelection === 'none')
return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 5, columnId: 'q2' });
},
clear: (api) => {
api.clearCellSelection();
api.clearSelection();
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Drag to pick cells like a spreadsheet</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Selection mode" id="mode">
<option value="cell-multiple" selected>Many blocks of cells</option>
<option value="cell-single">One cell</option>
<option value="row-single">One row</option>
<option value="row-multiple">Many rows</option>
<option value="none">No selection</option>
</select>
<button type="button" id="report">Tell me the selection</button>
<button type="button" id="pickBlock">Pick a block in code</button>
<button type="button" id="pickCell">Pick one cell in code</button>
<button type="button" id="clear">Clear selection</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>
// Quarterly cups sold per cafe menu item. A practice table for selecting ranges by dragging cells.
const menus = [
'Americano',
'Cafe Latte',
'Vanilla Latte',
'Cold Brew',
'Cappuccino',
'Green Tea Latte',
'Strawberry Smoothie',
'Lemonade',
'Honey Bread',
'Cheesecake',
];
// With cellSelection: 'multiple', drag across cells to pick a range, Shift+click to extend it,
// and Ctrl+click (or Ctrl+drag) to add another range. It is switched on and off separately from row selection (selection), and both can be used together.
const options = {
columns: [
{ id: 'menu', title: 'Menu', width: 170 },
...['q1', 'q2', 'q3', 'q4'].map((id, i) => ({
id,
title: `Q${i + 1}`,
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
})),
],
rows: menus.map((menu, i) => ({
id: i + 1,
menu,
q1: 1200 + ((i * 370) % 900),
q2: 1450 + ((i * 290) % 800),
q3: 980 + ((i * 410) % 1100),
q4: 1800 + ((i * 230) % 700),
})),
rowKey: 'id',
cellSelection: 'multiple',
};
const MODES = {
'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
'cell-single': { cellSelection: 'single', selection: 'none' },
'row-single': { cellSelection: 'none', selection: 'single' },
'row-multiple': { cellSelection: 'none', selection: 'multiple' },
none: { cellSelection: 'none', selection: 'none' },
};
// Keep the log received in setup so the buttons (actions) can leave messages too.
let say = () => { };
const NEED_MULTIPLE = "This mode cannot select by code. Switch 'Selection mode' above to a cell mode";
function setup(api, log) {
say = log;
const offCells = api.on('cellSelectionChanged', ({ ranges }) => log(`Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`));
const offRows = api.on('selectionChanged', ({ selectedKeys }) => log(`Selected rows: ${selectedKeys.length}`));
return () => {
offCells();
offRows();
};
}
// Turn a cell reference into a readable "menu item / column title" label.
const label = (api, ref) => {
const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey} ${title}`;
};
const actions = {
// Change the selection mode. The previous selection is cleared first.
mode: (api, value) => {
api.clearCellSelection();
api.clearSelection();
api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']);
},
// Report where the current ranges start and end (getCellRanges).
report: (api) => {
const ranges = api.getCellRanges();
say(ranges.length === 0
? 'No cells selected. Drag across some cells first'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '));
},
// Select a range by code: from row 2 Q1 to row 4 Q3. Tell the user if cell selection is off.
pickBlock: (api) => {
if (api.getOptions().cellSelection !== 'multiple')
return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
},
// Select a single cell.
pickCell: (api) => {
if (api.getOptions().cellSelection === 'none')
return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 5, columnId: 'q2' });
},
clear: (api) => {
api.clearCellSelection();
api.clearSelection();
},
};
options.ariaLabel = "Drag to pick cells like a spreadsheet";
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('report').addEventListener('click', () => actions.report(api));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickCell').addEventListener('click', () => actions.pickCell(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(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="Selection mode"
disabled={!api}
onChange={(event) => api && actions.mode(api, event.target.value)}
>
<option value="cell-multiple">Many blocks of cells</option>
<option value="cell-single">One cell</option>
<option value="row-single">One row</option>
<option value="row-multiple">Many rows</option>
<option value="none">No selection</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.report(api)}
>Tell me the selection</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pickBlock(api)}
>Pick a block in code</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pickCell(api)}
>Pick one cell in code</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear selection</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;
menu: string;
q1: number;
q2: number;
q3: number;
q4: number;
}
// Quarterly cups sold per cafe menu item. A practice table for selecting ranges by dragging cells.
const menus = [
'Americano',
'Cafe Latte',
'Vanilla Latte',
'Cold Brew',
'Cappuccino',
'Green Tea Latte',
'Strawberry Smoothie',
'Lemonade',
'Honey Bread',
'Cheesecake',
];
// With cellSelection: 'multiple', drag across cells to pick a range, Shift+click to extend it,
// and Ctrl+click (or Ctrl+drag) to add another range. It is switched on and off separately from row selection (selection), and both can be used together.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: 'Menu', width: 170 },
...(['q1', 'q2', 'q3', 'q4'] as const).map((id, i) => ({
id,
title: `Q${i + 1}`,
kind: 'number' as const,
width: 110,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('en-US'),
})),
],
rows: menus.map((menu, i) => ({
id: i + 1,
menu,
q1: 1200 + ((i * 370) % 900),
q2: 1450 + ((i * 290) % 800),
q3: 980 + ((i * 410) % 1100),
q4: 1800 + ((i * 230) % 700),
})),
rowKey: 'id',
cellSelection: 'multiple',
};
const MODES: Record<string, Partial<GridOptions<Row>>> = {
'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
'cell-single': { cellSelection: 'single', selection: 'none' },
'row-single': { cellSelection: 'none', selection: 'single' },
'row-multiple': { cellSelection: 'none', selection: 'multiple' },
none: { cellSelection: 'none', selection: 'none' },
};
// Keep the log received in setup so the buttons (actions) can leave messages too.
let say: (message: LogText) => void = () => {};
const NEED_MULTIPLE =
"This mode cannot select by code. Switch 'Selection mode' above to a cell mode";
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const offCells = api.on('cellSelectionChanged', ({ ranges }) =>
log(`Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`),
);
const offRows = api.on('selectionChanged', ({ selectedKeys }) =>
log(`Selected rows: ${selectedKeys.length}`),
);
return () => {
offCells();
offRows();
};
}
// Turn a cell reference into a readable "menu item / column title" label.
const label = (api: GridApi<Row>, ref: { rowKey: string | number; columnId: string }): string => {
const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey} ${title}`;
};
export const actions = {
// Change the selection mode. The previous selection is cleared first.
mode: (api: GridApi<Row>, value?: string) => {
api.clearCellSelection();
api.clearSelection();
api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']!);
},
// Report where the current ranges start and end (getCellRanges).
report: (api: GridApi<Row>) => {
const ranges = api.getCellRanges();
say(
ranges.length === 0
? 'No cells selected. Drag across some cells first'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
);
},
// Select a range by code: from row 2 Q1 to row 4 Q3. Tell the user if cell selection is off.
pickBlock: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection !== 'multiple') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
},
// Select a single cell.
pickCell: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection === 'none') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 5, columnId: 'q2' });
},
clear: (api: GridApi<Row>) => {
api.clearCellSelection();
api.clearSelection();
},
};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="Selection mode"
:disabled="!api"
@change="api && actions.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="cell-multiple" selected>Many blocks of cells</option>
<option value="cell-single">One cell</option>
<option value="row-single">One row</option>
<option value="row-multiple">Many rows</option>
<option value="none">No selection</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.report(api)">Tell me the selection</button>
<button
type="button"
:disabled="!api"
@click="api && actions.pickBlock(api)"
>Pick a block in code</button>
<button
type="button"
:disabled="!api"
@click="api && actions.pickCell(api)"
>Pick one cell in code</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear selection</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;
menu: string;
q1: number;
q2: number;
q3: number;
q4: number;
}
// Quarterly cups sold per cafe menu item. A practice table for selecting ranges by dragging cells.
const menus = [
'Americano',
'Cafe Latte',
'Vanilla Latte',
'Cold Brew',
'Cappuccino',
'Green Tea Latte',
'Strawberry Smoothie',
'Lemonade',
'Honey Bread',
'Cheesecake',
];
// With cellSelection: 'multiple', drag across cells to pick a range, Shift+click to extend it,
// and Ctrl+click (or Ctrl+drag) to add another range. It is switched on and off separately from row selection (selection), and both can be used together.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: 'Menu', width: 170 },
...(['q1', 'q2', 'q3', 'q4'] as const).map((id, i) => ({
id,
title: `Q${i + 1}`,
kind: 'number' as const,
width: 110,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('en-US'),
})),
],
rows: menus.map((menu, i) => ({
id: i + 1,
menu,
q1: 1200 + ((i * 370) % 900),
q2: 1450 + ((i * 290) % 800),
q3: 980 + ((i * 410) % 1100),
q4: 1800 + ((i * 230) % 700),
})),
rowKey: 'id',
cellSelection: 'multiple',
};
const MODES: Record<string, Partial<GridOptions<Row>>> = {
'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
'cell-single': { cellSelection: 'single', selection: 'none' },
'row-single': { cellSelection: 'none', selection: 'single' },
'row-multiple': { cellSelection: 'none', selection: 'multiple' },
none: { cellSelection: 'none', selection: 'none' },
};
// Keep the log received in setup so the buttons (actions) can leave messages too.
let say: (message: LogText) => void = () => {};
const NEED_MULTIPLE =
"This mode cannot select by code. Switch 'Selection mode' above to a cell mode";
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const offCells = api.on('cellSelectionChanged', ({ ranges }) =>
log(`Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`),
);
const offRows = api.on('selectionChanged', ({ selectedKeys }) =>
log(`Selected rows: ${selectedKeys.length}`),
);
return () => {
offCells();
offRows();
};
}
// Turn a cell reference into a readable "menu item / column title" label.
const label = (api: GridApi<Row>, ref: { rowKey: string | number; columnId: string }): string => {
const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey} ${title}`;
};
export const actions = {
// Change the selection mode. The previous selection is cleared first.
mode: (api: GridApi<Row>, value?: string) => {
api.clearCellSelection();
api.clearSelection();
api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']!);
},
// Report where the current ranges start and end (getCellRanges).
report: (api: GridApi<Row>) => {
const ranges = api.getCellRanges();
say(
ranges.length === 0
? 'No cells selected. Drag across some cells first'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
);
},
// Select a range by code: from row 2 Q1 to row 4 Q3. Tell the user if cell selection is off.
pickBlock: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection !== 'multiple') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
},
// Select a single cell.
pickCell: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection === 'none') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 5, columnId: 'q2' });
},
clear: (api: GridApi<Row>) => {
api.clearCellSelection();
api.clearSelection();
},
};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="Selection mode"
[disabled]="!api"
(change)="api && actions.mode(api, $any($event.target).value)"
>
<option value="cell-multiple" selected>Many blocks of cells</option>
<option value="cell-single">One cell</option>
<option value="row-single">One row</option>
<option value="row-multiple">Many rows</option>
<option value="none">No selection</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.report(api)"
>Tell me the selection</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pickBlock(api)"
>Pick a block in code</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pickCell(api)"
>Pick one cell in code</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear selection</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;
menu: string;
q1: number;
q2: number;
q3: number;
q4: number;
}
// Quarterly cups sold per cafe menu item. A practice table for selecting ranges by dragging cells.
const menus = [
'Americano',
'Cafe Latte',
'Vanilla Latte',
'Cold Brew',
'Cappuccino',
'Green Tea Latte',
'Strawberry Smoothie',
'Lemonade',
'Honey Bread',
'Cheesecake',
];
// With cellSelection: 'multiple', drag across cells to pick a range, Shift+click to extend it,
// and Ctrl+click (or Ctrl+drag) to add another range. It is switched on and off separately from row selection (selection), and both can be used together.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: 'Menu', width: 170 },
...(['q1', 'q2', 'q3', 'q4'] as const).map((id, i) => ({
id,
title: `Q${i + 1}`,
kind: 'number' as const,
width: 110,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('en-US'),
})),
],
rows: menus.map((menu, i) => ({
id: i + 1,
menu,
q1: 1200 + ((i * 370) % 900),
q2: 1450 + ((i * 290) % 800),
q3: 980 + ((i * 410) % 1100),
q4: 1800 + ((i * 230) % 700),
})),
rowKey: 'id',
cellSelection: 'multiple',
};
const MODES: Record<string, Partial<GridOptions<Row>>> = {
'cell-multiple': { cellSelection: 'multiple', selection: 'none' },
'cell-single': { cellSelection: 'single', selection: 'none' },
'row-single': { cellSelection: 'none', selection: 'single' },
'row-multiple': { cellSelection: 'none', selection: 'multiple' },
none: { cellSelection: 'none', selection: 'none' },
};
// Keep the log received in setup so the buttons (actions) can leave messages too.
let say: (message: LogText) => void = () => {};
const NEED_MULTIPLE =
"This mode cannot select by code. Switch 'Selection mode' above to a cell mode";
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const offCells = api.on('cellSelectionChanged', ({ ranges }) =>
log(`Selected cells: ${api.getSelectedCells().length} (${ranges.length} ranges)`),
);
const offRows = api.on('selectionChanged', ({ selectedKeys }) =>
log(`Selected rows: ${selectedKeys.length}`),
);
return () => {
offCells();
offRows();
};
}
// Turn a cell reference into a readable "menu item / column title" label.
const label = (api: GridApi<Row>, ref: { rowKey: string | number; columnId: string }): string => {
const title = api.getColumns().find((c) => c.id === ref.columnId)?.title ?? ref.columnId;
return `${api.getRowByKey(ref.rowKey)?.menu ?? ref.rowKey} ${title}`;
};
export const actions = {
// Change the selection mode. The previous selection is cleared first.
mode: (api: GridApi<Row>, value?: string) => {
api.clearCellSelection();
api.clearSelection();
api.setOptions(MODES[value ?? 'cell-multiple'] ?? MODES['cell-multiple']!);
},
// Report where the current ranges start and end (getCellRanges).
report: (api: GridApi<Row>) => {
const ranges = api.getCellRanges();
say(
ranges.length === 0
? 'No cells selected. Drag across some cells first'
: ranges
.map((r) => {
const a = label(api, r.from);
const b = label(api, r.to);
return a === b ? a : `${a} ~ ${b}`;
})
.join(' / '),
);
},
// Select a range by code: from row 2 Q1 to row 4 Q3. Tell the user if cell selection is off.
pickBlock: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection !== 'multiple') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 2, columnId: 'q1' }, { rowKey: 4, columnId: 'q3' });
},
// Select a single cell.
pickCell: (api: GridApi<Row>) => {
if (api.getOptions().cellSelection === 'none') return say(NEED_MULTIPLE);
api.selectCells({ rowKey: 5, columnId: 'q2' });
},
clear: (api: GridApi<Row>) => {
api.clearCellSelection();
api.clearSelection();
},
};