고른 줄에 한꺼번에 적용하기Apply a change to all selected rows
줄을 여러 개 골라 상태·우선순위를 한 번에 바꾸고, 맨 위 줄의 담당자를 나머지에 채우고, 모두 1시간씩 더할 수 있어요. 여러 줄을 한 번에 고쳐도 변경 기록에는 한 묶음으로 남아서 저장 전에 한꺼번에 버릴 수 있어요.Pick several rows and change status or priority at once, fill the top row's owner into the rest, or add an hour to all. Even a multi-row change is one batch in the change log, so you can discard it before saving.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="selectAll">전체 선택</button>
<select aria-label="상태 바꾸기" id="status">
<option value="pick" selected>(고르세요)</option>
<option value="open">접수</option>
<option value="doing">진행</option>
<option value="done">완료</option>
</select>
<select aria-label="우선순위 바꾸기" id="priority">
<option value="pick" selected>(고르세요)</option>
<option value="low">낮음</option>
<option value="high">높음</option>
</select>
<button type="button" id="fillOwner">담당자 아래로 채우기</button>
<button type="button" id="addHour">시간 +1</button>
<button type="button" id="discard">변경 버리기</button>
</div>
<div id="grid" style="height: 290px"></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('selectAll').addEventListener('click', () => actions.selectAll(api));
document.getElementById('status').addEventListener('change', (event) => actions.status(api, event.target.value));
document.getElementById('priority').addEventListener('change', (event) => actions.priority(api, event.target.value));
document.getElementById('fillOwner').addEventListener('click', () => actions.fillOwner(api));
document.getElementById('addHour').addEventListener('click', () => actions.addHour(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));const tickets = [
'로그인 이동 오류',
'푸터 링크 정리',
'검색 결과가 느려요',
'가격표 오타',
'Safari에서 내보내기 실패',
'알림 설정 저장 안 됨',
];
const rows = tickets.map((ticket, i) => ({
id: i + 1,
ticket,
owner: i === 0 ? '김서연' : '',
status: 'open',
priority: i % 2 ? 'high' : 'low',
hours: i === 0 ? 3 : 0,
}));
const statusName = { open: '접수', doing: '진행', done: '완료' };
const priorityName = { low: '낮음', high: '높음' };
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0)
return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word) => (batchim(word) ? '을' : '를');
const euroRo = (word) => (batchim(word) && batchim(word) !== 8 ? '으로' : '로');
export const options = {
columns: [
{ id: 'ticket', title: '티켓', width: 180 },
{ id: 'owner', title: '담당자', width: 100, editable: true },
{
id: 'status',
title: '상태',
width: 80,
formatValue: (v) => statusName[String(v)] ?? String(v),
},
{
id: 'priority',
title: '우선순위',
width: 90,
formatValue: (v) => priorityName[String(v)] ?? String(v),
},
{ id: 'hours', title: '시간', kind: 'number', width: 80, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
let say = () => { };
export function setup(api, log) {
say = log;
log({
ko: '왼쪽 체크박스로 줄을 고른 뒤 위의 버튼이나 선택 상자를 써 보세요.',
en: 'Select rows with the checkboxes on the left, then use the buttons or selects above.',
});
return api.on('changesCountChanged', ({ count }) => log({ ko: `저장 안 한 변경: ${count}줄`, en: `Unsaved changes: ${count} rows` }));
}
const selectedRows = (api) => api.getSelectedKeys().flatMap((key) => {
const row = api.getRowByKey(key);
return row ? [row] : [];
});
// 여러 줄을 고칠 때는 updateRows를 한 번만 불러요. 그러면 변경 기록에 한 묶음으로 남아서 저장 전에 한꺼번에 검토하거나 버릴 수 있어요.
function setSelected(api, column, value, names) {
if (!value || value === 'pick')
return;
// 같은 값을 또 고를 수 있게 선택 상자를 "(고르세요)"로 되돌려요(선택 상자의 id는 컨트롤 id와 같아요).
const box = document.getElementById(column);
if (box instanceof HTMLSelectElement)
box.value = 'pick';
const rows = selectedRows(api);
if (!rows.length)
return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
say({
ko: `${n}줄의 ${column === 'status' ? '상태' : '우선순위'}를 "${names[value] ?? value}"${euroRo(names[value] ?? value)} 바꿨어요.`,
en: `Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`,
});
}
export const actions = {
status: (api, value) => setSelected(api, 'status', value, statusName),
priority: (api, value) => setSelected(api, 'priority', value, priorityName),
// 아래로 채우기: 고른 줄 중 맨 위 줄의 담당자를 나머지 고른 줄에 복사해요(엑셀의 Ctrl+D처럼).
fillOwner: (api) => {
const [first, ...rest] = selectedRows(api);
if (!first || !rest.length)
return say({
ko: '두 줄 이상 골라 주세요. 맨 위 줄의 값이 나머지에 채워져요.',
en: 'Select two or more rows. The value of the top row is filled into the rest.',
});
const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
say({
ko: `"${first.owner || '(빈 값)'}"${eulReul(first.owner || '값')} ${n}줄에 채웠어요.`,
en: `Filled "${first.owner || '(empty)'}" into ${n} rows.`,
});
},
addHour: (api) => {
const rows = selectedRows(api);
if (!rows.length)
return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
say({
ko: `${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))}줄에 1시간씩 더했어요.`,
en: `Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`,
});
},
selectAll: (api) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
discard: (api) => {
api.rollbackChanges();
api.setSelectedKeys([]);
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>고른 줄에 한꺼번에 적용하기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="selectAll">전체 선택</button>
<select aria-label="상태 바꾸기" id="status">
<option value="pick" selected>(고르세요)</option>
<option value="open">접수</option>
<option value="doing">진행</option>
<option value="done">완료</option>
</select>
<select aria-label="우선순위 바꾸기" id="priority">
<option value="pick" selected>(고르세요)</option>
<option value="low">낮음</option>
<option value="high">높음</option>
</select>
<button type="button" id="fillOwner">담당자 아래로 채우기</button>
<button type="button" id="addHour">시간 +1</button>
<button type="button" id="discard">변경 버리기</button>
</div>
<div id="grid" style="height: 290px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const tickets = [
'로그인 이동 오류',
'푸터 링크 정리',
'검색 결과가 느려요',
'가격표 오타',
'Safari에서 내보내기 실패',
'알림 설정 저장 안 됨',
];
const rows = tickets.map((ticket, i) => ({
id: i + 1,
ticket,
owner: i === 0 ? '김서연' : '',
status: 'open',
priority: i % 2 ? 'high' : 'low',
hours: i === 0 ? 3 : 0,
}));
const statusName = { open: '접수', doing: '진행', done: '완료' };
const priorityName = { low: '낮음', high: '높음' };
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0)
return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word) => (batchim(word) ? '을' : '를');
const euroRo = (word) => (batchim(word) && batchim(word) !== 8 ? '으로' : '로');
const options = {
columns: [
{ id: 'ticket', title: '티켓', width: 180 },
{ id: 'owner', title: '담당자', width: 100, editable: true },
{
id: 'status',
title: '상태',
width: 80,
formatValue: (v) => statusName[String(v)] ?? String(v),
},
{
id: 'priority',
title: '우선순위',
width: 90,
formatValue: (v) => priorityName[String(v)] ?? String(v),
},
{ id: 'hours', title: '시간', kind: 'number', width: 80, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
let say = () => { };
function setup(api, log) {
say = log;
log({
ko: '왼쪽 체크박스로 줄을 고른 뒤 위의 버튼이나 선택 상자를 써 보세요.',
en: 'Select rows with the checkboxes on the left, then use the buttons or selects above.',
});
return api.on('changesCountChanged', ({ count }) => log({ ko: `저장 안 한 변경: ${count}줄`, en: `Unsaved changes: ${count} rows` }));
}
const selectedRows = (api) => api.getSelectedKeys().flatMap((key) => {
const row = api.getRowByKey(key);
return row ? [row] : [];
});
// 여러 줄을 고칠 때는 updateRows를 한 번만 불러요. 그러면 변경 기록에 한 묶음으로 남아서 저장 전에 한꺼번에 검토하거나 버릴 수 있어요.
function setSelected(api, column, value, names) {
if (!value || value === 'pick')
return;
// 같은 값을 또 고를 수 있게 선택 상자를 "(고르세요)"로 되돌려요(선택 상자의 id는 컨트롤 id와 같아요).
const box = document.getElementById(column);
if (box instanceof HTMLSelectElement)
box.value = 'pick';
const rows = selectedRows(api);
if (!rows.length)
return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
say({
ko: `${n}줄의 ${column === 'status' ? '상태' : '우선순위'}를 "${names[value] ?? value}"${euroRo(names[value] ?? value)} 바꿨어요.`,
en: `Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`,
});
}
const actions = {
status: (api, value) => setSelected(api, 'status', value, statusName),
priority: (api, value) => setSelected(api, 'priority', value, priorityName),
// 아래로 채우기: 고른 줄 중 맨 위 줄의 담당자를 나머지 고른 줄에 복사해요(엑셀의 Ctrl+D처럼).
fillOwner: (api) => {
const [first, ...rest] = selectedRows(api);
if (!first || !rest.length)
return say({
ko: '두 줄 이상 골라 주세요. 맨 위 줄의 값이 나머지에 채워져요.',
en: 'Select two or more rows. The value of the top row is filled into the rest.',
});
const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
say({
ko: `"${first.owner || '(빈 값)'}"${eulReul(first.owner || '값')} ${n}줄에 채웠어요.`,
en: `Filled "${first.owner || '(empty)'}" into ${n} rows.`,
});
},
addHour: (api) => {
const rows = selectedRows(api);
if (!rows.length)
return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
say({
ko: `${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))}줄에 1시간씩 더했어요.`,
en: `Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`,
});
},
selectAll: (api) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
discard: (api) => {
api.rollbackChanges();
api.setSelectedKeys([]);
},
};
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('selectAll').addEventListener('click', () => actions.selectAll(api));
document.getElementById('status').addEventListener('change', (event) => actions.status(api, event.target.value));
document.getElementById('priority').addEventListener('change', (event) => actions.priority(api, event.target.value));
document.getElementById('fillOwner').addEventListener('click', () => actions.fillOwner(api));
document.getElementById('addHour').addEventListener('click', () => actions.addHour(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.selectAll(api)}
>전체 선택</button>
<select
aria-label="상태 바꾸기"
disabled={!api}
onChange={(event) => api && actions.status(api, event.target.value)}
>
<option value="pick">(고르세요)</option>
<option value="open">접수</option>
<option value="doing">진행</option>
<option value="done">완료</option>
</select>
<select defaultValue="pick"
aria-label="우선순위 바꾸기"
disabled={!api}
onChange={(event) => api && actions.priority(api, event.target.value)}
>
<option value="pick">(고르세요)</option>
<option value="low">낮음</option>
<option value="high">높음</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.fillOwner(api)}
>담당자 아래로 채우기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.addHour(api)}
>시간 +1</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>변경 버리기</button>
</div>
<Grid style={{ height: 290 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
ticket: string;
owner: string;
status: string;
priority: string;
hours: number;
}
const tickets = [
'로그인 이동 오류',
'푸터 링크 정리',
'검색 결과가 느려요',
'가격표 오타',
'Safari에서 내보내기 실패',
'알림 설정 저장 안 됨',
];
const rows: Row[] = tickets.map((ticket, i) => ({
id: i + 1,
ticket,
owner: i === 0 ? '김서연' : '',
status: 'open',
priority: i % 2 ? 'high' : 'low',
hours: i === 0 ? 3 : 0,
}));
const statusName: Record<string, string> = { open: '접수', doing: '진행', done: '완료' };
const priorityName: Record<string, string> = { low: '낮음', high: '높음' };
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0) return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word: string): string => (batchim(word) ? '을' : '를');
const euroRo = (word: string): string => (batchim(word) && batchim(word) !== 8 ? '으로' : '로');
export const options: GridOptions<Row> = {
columns: [
{ id: 'ticket', title: '티켓', width: 180 },
{ id: 'owner', title: '담당자', width: 100, editable: true },
{
id: 'status',
title: '상태',
width: 80,
formatValue: (v) => statusName[String(v)] ?? String(v),
},
{
id: 'priority',
title: '우선순위',
width: 90,
formatValue: (v) => priorityName[String(v)] ?? String(v),
},
{ id: 'hours', title: '시간', kind: 'number', width: 80, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '왼쪽 체크박스로 줄을 고른 뒤 위의 버튼이나 선택 상자를 써 보세요.',
en: 'Select rows with the checkboxes on the left, then use the buttons or selects above.',
});
return api.on('changesCountChanged', ({ count }) =>
log({ ko: `저장 안 한 변경: ${count}줄`, en: `Unsaved changes: ${count} rows` }),
);
}
const selectedRows = (api: GridApi<Row>): Row[] =>
api.getSelectedKeys().flatMap((key) => {
const row = api.getRowByKey(key);
return row ? [row] : [];
});
// 여러 줄을 고칠 때는 updateRows를 한 번만 불러요. 그러면 변경 기록에 한 묶음으로 남아서 저장 전에 한꺼번에 검토하거나 버릴 수 있어요.
function setSelected(
api: GridApi<Row>,
column: 'status' | 'priority',
value: string | undefined,
names: Record<string, string>,
): void {
if (!value || value === 'pick') return;
// 같은 값을 또 고를 수 있게 선택 상자를 "(고르세요)"로 되돌려요(선택 상자의 id는 컨트롤 id와 같아요).
const box = document.getElementById(column);
if (box instanceof HTMLSelectElement) box.value = 'pick';
const rows = selectedRows(api);
if (!rows.length)
return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
say({
ko: `${n}줄의 ${column === 'status' ? '상태' : '우선순위'}를 "${names[value] ?? value}"${euroRo(names[value] ?? value)} 바꿨어요.`,
en: `Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`,
});
}
export const actions = {
status: (api: GridApi<Row>, value?: string) => setSelected(api, 'status', value, statusName),
priority: (api: GridApi<Row>, value?: string) =>
setSelected(api, 'priority', value, priorityName),
// 아래로 채우기: 고른 줄 중 맨 위 줄의 담당자를 나머지 고른 줄에 복사해요(엑셀의 Ctrl+D처럼).
fillOwner: (api: GridApi<Row>) => {
const [first, ...rest] = selectedRows(api);
if (!first || !rest.length)
return say({
ko: '두 줄 이상 골라 주세요. 맨 위 줄의 값이 나머지에 채워져요.',
en: 'Select two or more rows. The value of the top row is filled into the rest.',
});
const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
say({
ko: `"${first.owner || '(빈 값)'}"${eulReul(first.owner || '값')} ${n}줄에 채웠어요.`,
en: `Filled "${first.owner || '(empty)'}" into ${n} rows.`,
});
},
addHour: (api: GridApi<Row>) => {
const rows = selectedRows(api);
if (!rows.length)
return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
say({
ko: `${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))}줄에 1시간씩 더했어요.`,
en: `Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`,
});
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
discard: (api: GridApi<Row>) => {
api.rollbackChanges();
api.setSelectedKeys([]);
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.selectAll(api)"
>전체 선택</button>
<select
aria-label="상태 바꾸기"
:disabled="!api"
@change="api && actions.status(api, ($event.target as HTMLSelectElement).value)"
>
<option value="pick" selected>(고르세요)</option>
<option value="open">접수</option>
<option value="doing">진행</option>
<option value="done">완료</option>
</select>
<select
aria-label="우선순위 바꾸기"
:disabled="!api"
@change="api && actions.priority(api, ($event.target as HTMLSelectElement).value)"
>
<option value="pick" selected>(고르세요)</option>
<option value="low">낮음</option>
<option value="high">높음</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.fillOwner(api)"
>담당자 아래로 채우기</button>
<button type="button" :disabled="!api" @click="api && actions.addHour(api)">시간 +1</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">변경 버리기</button>
</div>
<Grid style="height: 290px" :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;
ticket: string;
owner: string;
status: string;
priority: string;
hours: number;
}
const tickets = [
'로그인 이동 오류',
'푸터 링크 정리',
'검색 결과가 느려요',
'가격표 오타',
'Safari에서 내보내기 실패',
'알림 설정 저장 안 됨',
];
const rows: Row[] = tickets.map((ticket, i) => ({
id: i + 1,
ticket,
owner: i === 0 ? '김서연' : '',
status: 'open',
priority: i % 2 ? 'high' : 'low',
hours: i === 0 ? 3 : 0,
}));
const statusName: Record<string, string> = { open: '접수', doing: '진행', done: '완료' };
const priorityName: Record<string, string> = { low: '낮음', high: '높음' };
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0) return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word: string): string => (batchim(word) ? '을' : '를');
const euroRo = (word: string): string => (batchim(word) && batchim(word) !== 8 ? '으로' : '로');
export const options: GridOptions<Row> = {
columns: [
{ id: 'ticket', title: '티켓', width: 180 },
{ id: 'owner', title: '담당자', width: 100, editable: true },
{
id: 'status',
title: '상태',
width: 80,
formatValue: (v) => statusName[String(v)] ?? String(v),
},
{
id: 'priority',
title: '우선순위',
width: 90,
formatValue: (v) => priorityName[String(v)] ?? String(v),
},
{ id: 'hours', title: '시간', kind: 'number', width: 80, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '왼쪽 체크박스로 줄을 고른 뒤 위의 버튼이나 선택 상자를 써 보세요.',
en: 'Select rows with the checkboxes on the left, then use the buttons or selects above.',
});
return api.on('changesCountChanged', ({ count }) =>
log({ ko: `저장 안 한 변경: ${count}줄`, en: `Unsaved changes: ${count} rows` }),
);
}
const selectedRows = (api: GridApi<Row>): Row[] =>
api.getSelectedKeys().flatMap((key) => {
const row = api.getRowByKey(key);
return row ? [row] : [];
});
// 여러 줄을 고칠 때는 updateRows를 한 번만 불러요. 그러면 변경 기록에 한 묶음으로 남아서 저장 전에 한꺼번에 검토하거나 버릴 수 있어요.
function setSelected(
api: GridApi<Row>,
column: 'status' | 'priority',
value: string | undefined,
names: Record<string, string>,
): void {
if (!value || value === 'pick') return;
// 같은 값을 또 고를 수 있게 선택 상자를 "(고르세요)"로 되돌려요(선택 상자의 id는 컨트롤 id와 같아요).
const box = document.getElementById(column);
if (box instanceof HTMLSelectElement) box.value = 'pick';
const rows = selectedRows(api);
if (!rows.length)
return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
say({
ko: `${n}줄의 ${column === 'status' ? '상태' : '우선순위'}를 "${names[value] ?? value}"${euroRo(names[value] ?? value)} 바꿨어요.`,
en: `Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`,
});
}
export const actions = {
status: (api: GridApi<Row>, value?: string) => setSelected(api, 'status', value, statusName),
priority: (api: GridApi<Row>, value?: string) =>
setSelected(api, 'priority', value, priorityName),
// 아래로 채우기: 고른 줄 중 맨 위 줄의 담당자를 나머지 고른 줄에 복사해요(엑셀의 Ctrl+D처럼).
fillOwner: (api: GridApi<Row>) => {
const [first, ...rest] = selectedRows(api);
if (!first || !rest.length)
return say({
ko: '두 줄 이상 골라 주세요. 맨 위 줄의 값이 나머지에 채워져요.',
en: 'Select two or more rows. The value of the top row is filled into the rest.',
});
const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
say({
ko: `"${first.owner || '(빈 값)'}"${eulReul(first.owner || '값')} ${n}줄에 채웠어요.`,
en: `Filled "${first.owner || '(empty)'}" into ${n} rows.`,
});
},
addHour: (api: GridApi<Row>) => {
const rows = selectedRows(api);
if (!rows.length)
return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
say({
ko: `${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))}줄에 1시간씩 더했어요.`,
en: `Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`,
});
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
discard: (api: GridApi<Row>) => {
api.rollbackChanges();
api.setSelectedKeys([]);
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.selectAll(api)"
>전체 선택</button>
<select
aria-label="상태 바꾸기"
[disabled]="!api"
(change)="api && actions.status(api, $any($event.target).value)"
>
<option value="pick" selected>(고르세요)</option>
<option value="open">접수</option>
<option value="doing">진행</option>
<option value="done">완료</option>
</select>
<select
aria-label="우선순위 바꾸기"
[disabled]="!api"
(change)="api && actions.priority(api, $any($event.target).value)"
>
<option value="pick" selected>(고르세요)</option>
<option value="low">낮음</option>
<option value="high">높음</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.fillOwner(api)"
>담당자 아래로 채우기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.addHour(api)"
>시간 +1</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(api)"
>변경 버리기</button>
</div>
<mx-grid style="height: 290px" [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;
ticket: string;
owner: string;
status: string;
priority: string;
hours: number;
}
const tickets = [
'로그인 이동 오류',
'푸터 링크 정리',
'검색 결과가 느려요',
'가격표 오타',
'Safari에서 내보내기 실패',
'알림 설정 저장 안 됨',
];
const rows: Row[] = tickets.map((ticket, i) => ({
id: i + 1,
ticket,
owner: i === 0 ? '김서연' : '',
status: 'open',
priority: i % 2 ? 'high' : 'low',
hours: i === 0 ? 3 : 0,
}));
const statusName: Record<string, string> = { open: '접수', doing: '진행', done: '완료' };
const priorityName: Record<string, string> = { low: '낮음', high: '높음' };
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0) return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const eulReul = (word: string): string => (batchim(word) ? '을' : '를');
const euroRo = (word: string): string => (batchim(word) && batchim(word) !== 8 ? '으로' : '로');
export const options: GridOptions<Row> = {
columns: [
{ id: 'ticket', title: '티켓', width: 180 },
{ id: 'owner', title: '담당자', width: 100, editable: true },
{
id: 'status',
title: '상태',
width: 80,
formatValue: (v) => statusName[String(v)] ?? String(v),
},
{
id: 'priority',
title: '우선순위',
width: 90,
formatValue: (v) => priorityName[String(v)] ?? String(v),
},
{ id: 'hours', title: '시간', kind: 'number', width: 80, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '왼쪽 체크박스로 줄을 고른 뒤 위의 버튼이나 선택 상자를 써 보세요.',
en: 'Select rows with the checkboxes on the left, then use the buttons or selects above.',
});
return api.on('changesCountChanged', ({ count }) =>
log({ ko: `저장 안 한 변경: ${count}줄`, en: `Unsaved changes: ${count} rows` }),
);
}
const selectedRows = (api: GridApi<Row>): Row[] =>
api.getSelectedKeys().flatMap((key) => {
const row = api.getRowByKey(key);
return row ? [row] : [];
});
// 여러 줄을 고칠 때는 updateRows를 한 번만 불러요. 그러면 변경 기록에 한 묶음으로 남아서 저장 전에 한꺼번에 검토하거나 버릴 수 있어요.
function setSelected(
api: GridApi<Row>,
column: 'status' | 'priority',
value: string | undefined,
names: Record<string, string>,
): void {
if (!value || value === 'pick') return;
// 같은 값을 또 고를 수 있게 선택 상자를 "(고르세요)"로 되돌려요(선택 상자의 id는 컨트롤 id와 같아요).
const box = document.getElementById(column);
if (box instanceof HTMLSelectElement) box.value = 'pick';
const rows = selectedRows(api);
if (!rows.length)
return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
say({
ko: `${n}줄의 ${column === 'status' ? '상태' : '우선순위'}를 "${names[value] ?? value}"${euroRo(names[value] ?? value)} 바꿨어요.`,
en: `Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`,
});
}
export const actions = {
status: (api: GridApi<Row>, value?: string) => setSelected(api, 'status', value, statusName),
priority: (api: GridApi<Row>, value?: string) =>
setSelected(api, 'priority', value, priorityName),
// 아래로 채우기: 고른 줄 중 맨 위 줄의 담당자를 나머지 고른 줄에 복사해요(엑셀의 Ctrl+D처럼).
fillOwner: (api: GridApi<Row>) => {
const [first, ...rest] = selectedRows(api);
if (!first || !rest.length)
return say({
ko: '두 줄 이상 골라 주세요. 맨 위 줄의 값이 나머지에 채워져요.',
en: 'Select two or more rows. The value of the top row is filled into the rest.',
});
const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
say({
ko: `"${first.owner || '(빈 값)'}"${eulReul(first.owner || '값')} ${n}줄에 채웠어요.`,
en: `Filled "${first.owner || '(empty)'}" into ${n} rows.`,
});
},
addHour: (api: GridApi<Row>) => {
const rows = selectedRows(api);
if (!rows.length)
return say({ ko: '먼저 줄을 하나 이상 골라 주세요.', en: 'Select at least one row first.' });
say({
ko: `${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))}줄에 1시간씩 더했어요.`,
en: `Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`,
});
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
discard: (api: GridApi<Row>) => {
api.rollbackChanges();
api.setSelectedKeys([]);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="selectAll">Select all</button>
<select aria-label="Set status" id="status">
<option value="pick" selected>(pick one)</option>
<option value="open">Open</option>
<option value="doing">In progress</option>
<option value="done">Done</option>
</select>
<select aria-label="Set priority" id="priority">
<option value="pick" selected>(pick one)</option>
<option value="low">Low</option>
<option value="high">High</option>
</select>
<button type="button" id="fillOwner">Fill owner down</button>
<button type="button" id="addHour">Add 1 hour</button>
<button type="button" id="discard">Discard changes</button>
</div>
<div id="grid" style="height: 290px"></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('selectAll').addEventListener('click', () => actions.selectAll(api));
document.getElementById('status').addEventListener('change', (event) => actions.status(api, event.target.value));
document.getElementById('priority').addEventListener('change', (event) => actions.priority(api, event.target.value));
document.getElementById('fillOwner').addEventListener('click', () => actions.fillOwner(api));
document.getElementById('addHour').addEventListener('click', () => actions.addHour(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));const tickets = [
'Login redirect error',
'Tidy footer links',
'Search results are slow',
'Typo in price list',
'Export fails in Safari',
'Notification settings not saved',
];
const rows = tickets.map((ticket, i) => ({
id: i + 1,
ticket,
owner: i === 0 ? 'Liam Carter' : '',
status: 'open',
priority: i % 2 ? 'high' : 'low',
hours: i === 0 ? 3 : 0,
}));
const statusName = { open: 'Open', doing: 'In progress', done: 'Done' };
const priorityName = { low: 'Low', high: 'High' };
export const options = {
columns: [
{ id: 'ticket', title: 'Ticket', width: 230 },
{ id: 'owner', title: 'Owner', width: 120, editable: true },
{
id: 'status',
title: 'Status',
width: 110,
formatValue: (v) => statusName[String(v)] ?? String(v),
},
{
id: 'priority',
title: 'Priority',
width: 90,
formatValue: (v) => priorityName[String(v)] ?? String(v),
},
{ id: 'hours', title: 'Hours', kind: 'number', width: 80, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
let say = () => { };
export function setup(api, log) {
say = log;
log('Select rows with the checkboxes on the left, then use the buttons or selects above.');
return api.on('changesCountChanged', ({ count }) => log(`Unsaved changes: ${count} rows`));
}
const selectedRows = (api) => api.getSelectedKeys().flatMap((key) => {
const row = api.getRowByKey(key);
return row ? [row] : [];
});
// When editing several rows, call updateRows only once. The changes are then recorded as one batch, so they can be reviewed or discarded together before saving.
function setSelected(api, column, value, names) {
if (!value || value === 'pick')
return;
// Reset the select to "(pick one)" so the same value can be chosen again (the select's id equals the control id).
const box = document.getElementById(column);
if (box instanceof HTMLSelectElement)
box.value = 'pick';
const rows = selectedRows(api);
if (!rows.length)
return say('Select at least one row first.');
const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
say(`Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`);
}
export const actions = {
status: (api, value) => setSelected(api, 'status', value, statusName),
priority: (api, value) => setSelected(api, 'priority', value, priorityName),
// Fill down: copy the owner of the top selected row to the other selected rows (like Ctrl+D in a spreadsheet).
fillOwner: (api) => {
const [first, ...rest] = selectedRows(api);
if (!first || !rest.length)
return say('Select two or more rows. The value of the top row is filled into the rest.');
const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
say(`Filled "${first.owner || '(empty)'}" into ${n} rows.`);
},
addHour: (api) => {
const rows = selectedRows(api);
if (!rows.length)
return say('Select at least one row first.');
say(`Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`);
},
selectAll: (api) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
discard: (api) => {
api.rollbackChanges();
api.setSelectedKeys([]);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Apply a change to all selected rows</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="selectAll">Select all</button>
<select aria-label="Set status" id="status">
<option value="pick" selected>(pick one)</option>
<option value="open">Open</option>
<option value="doing">In progress</option>
<option value="done">Done</option>
</select>
<select aria-label="Set priority" id="priority">
<option value="pick" selected>(pick one)</option>
<option value="low">Low</option>
<option value="high">High</option>
</select>
<button type="button" id="fillOwner">Fill owner down</button>
<button type="button" id="addHour">Add 1 hour</button>
<button type="button" id="discard">Discard changes</button>
</div>
<div id="grid" style="height: 290px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const tickets = [
'Login redirect error',
'Tidy footer links',
'Search results are slow',
'Typo in price list',
'Export fails in Safari',
'Notification settings not saved',
];
const rows = tickets.map((ticket, i) => ({
id: i + 1,
ticket,
owner: i === 0 ? 'Liam Carter' : '',
status: 'open',
priority: i % 2 ? 'high' : 'low',
hours: i === 0 ? 3 : 0,
}));
const statusName = { open: 'Open', doing: 'In progress', done: 'Done' };
const priorityName = { low: 'Low', high: 'High' };
const options = {
columns: [
{ id: 'ticket', title: 'Ticket', width: 230 },
{ id: 'owner', title: 'Owner', width: 120, editable: true },
{
id: 'status',
title: 'Status',
width: 110,
formatValue: (v) => statusName[String(v)] ?? String(v),
},
{
id: 'priority',
title: 'Priority',
width: 90,
formatValue: (v) => priorityName[String(v)] ?? String(v),
},
{ id: 'hours', title: 'Hours', kind: 'number', width: 80, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
let say = () => { };
function setup(api, log) {
say = log;
log('Select rows with the checkboxes on the left, then use the buttons or selects above.');
return api.on('changesCountChanged', ({ count }) => log(`Unsaved changes: ${count} rows`));
}
const selectedRows = (api) => api.getSelectedKeys().flatMap((key) => {
const row = api.getRowByKey(key);
return row ? [row] : [];
});
// When editing several rows, call updateRows only once. The changes are then recorded as one batch, so they can be reviewed or discarded together before saving.
function setSelected(api, column, value, names) {
if (!value || value === 'pick')
return;
// Reset the select to "(pick one)" so the same value can be chosen again (the select's id equals the control id).
const box = document.getElementById(column);
if (box instanceof HTMLSelectElement)
box.value = 'pick';
const rows = selectedRows(api);
if (!rows.length)
return say('Select at least one row first.');
const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
say(`Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`);
}
const actions = {
status: (api, value) => setSelected(api, 'status', value, statusName),
priority: (api, value) => setSelected(api, 'priority', value, priorityName),
// Fill down: copy the owner of the top selected row to the other selected rows (like Ctrl+D in a spreadsheet).
fillOwner: (api) => {
const [first, ...rest] = selectedRows(api);
if (!first || !rest.length)
return say('Select two or more rows. The value of the top row is filled into the rest.');
const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
say(`Filled "${first.owner || '(empty)'}" into ${n} rows.`);
},
addHour: (api) => {
const rows = selectedRows(api);
if (!rows.length)
return say('Select at least one row first.');
say(`Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`);
},
selectAll: (api) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
discard: (api) => {
api.rollbackChanges();
api.setSelectedKeys([]);
},
};
options.ariaLabel = "Apply a change to all selected rows";
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('selectAll').addEventListener('click', () => actions.selectAll(api));
document.getElementById('status').addEventListener('change', (event) => actions.status(api, event.target.value));
document.getElementById('priority').addEventListener('change', (event) => actions.priority(api, event.target.value));
document.getElementById('fillOwner').addEventListener('click', () => actions.fillOwner(api));
document.getElementById('addHour').addEventListener('click', () => actions.addHour(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.selectAll(api)}
>Select all</button>
<select
aria-label="Set status"
disabled={!api}
onChange={(event) => api && actions.status(api, event.target.value)}
>
<option value="pick">(pick one)</option>
<option value="open">Open</option>
<option value="doing">In progress</option>
<option value="done">Done</option>
</select>
<select defaultValue="pick"
aria-label="Set priority"
disabled={!api}
onChange={(event) => api && actions.priority(api, event.target.value)}
>
<option value="pick">(pick one)</option>
<option value="low">Low</option>
<option value="high">High</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.fillOwner(api)}
>Fill owner down</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.addHour(api)}
>Add 1 hour</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>Discard changes</button>
</div>
<Grid style={{ height: 290 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
ticket: string;
owner: string;
status: string;
priority: string;
hours: number;
}
const tickets = [
'Login redirect error',
'Tidy footer links',
'Search results are slow',
'Typo in price list',
'Export fails in Safari',
'Notification settings not saved',
];
const rows: Row[] = tickets.map((ticket, i) => ({
id: i + 1,
ticket,
owner: i === 0 ? 'Liam Carter' : '',
status: 'open',
priority: i % 2 ? 'high' : 'low',
hours: i === 0 ? 3 : 0,
}));
const statusName: Record<string, string> = { open: 'Open', doing: 'In progress', done: 'Done' };
const priorityName: Record<string, string> = { low: 'Low', high: 'High' };
export const options: GridOptions<Row> = {
columns: [
{ id: 'ticket', title: 'Ticket', width: 230 },
{ id: 'owner', title: 'Owner', width: 120, editable: true },
{
id: 'status',
title: 'Status',
width: 110,
formatValue: (v) => statusName[String(v)] ?? String(v),
},
{
id: 'priority',
title: 'Priority',
width: 90,
formatValue: (v) => priorityName[String(v)] ?? String(v),
},
{ id: 'hours', title: 'Hours', kind: 'number', width: 80, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Select rows with the checkboxes on the left, then use the buttons or selects above.');
return api.on('changesCountChanged', ({ count }) => log(`Unsaved changes: ${count} rows`));
}
const selectedRows = (api: GridApi<Row>): Row[] =>
api.getSelectedKeys().flatMap((key) => {
const row = api.getRowByKey(key);
return row ? [row] : [];
});
// When editing several rows, call updateRows only once. The changes are then recorded as one batch, so they can be reviewed or discarded together before saving.
function setSelected(
api: GridApi<Row>,
column: 'status' | 'priority',
value: string | undefined,
names: Record<string, string>,
): void {
if (!value || value === 'pick') return;
// Reset the select to "(pick one)" so the same value can be chosen again (the select's id equals the control id).
const box = document.getElementById(column);
if (box instanceof HTMLSelectElement) box.value = 'pick';
const rows = selectedRows(api);
if (!rows.length) return say('Select at least one row first.');
const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
say(
`Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`,
);
}
export const actions = {
status: (api: GridApi<Row>, value?: string) => setSelected(api, 'status', value, statusName),
priority: (api: GridApi<Row>, value?: string) =>
setSelected(api, 'priority', value, priorityName),
// Fill down: copy the owner of the top selected row to the other selected rows (like Ctrl+D in a spreadsheet).
fillOwner: (api: GridApi<Row>) => {
const [first, ...rest] = selectedRows(api);
if (!first || !rest.length)
return say('Select two or more rows. The value of the top row is filled into the rest.');
const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
say(`Filled "${first.owner || '(empty)'}" into ${n} rows.`);
},
addHour: (api: GridApi<Row>) => {
const rows = selectedRows(api);
if (!rows.length) return say('Select at least one row first.');
say(
`Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`,
);
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
discard: (api: GridApi<Row>) => {
api.rollbackChanges();
api.setSelectedKeys([]);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.selectAll(api)"
>Select all</button>
<select
aria-label="Set status"
:disabled="!api"
@change="api && actions.status(api, ($event.target as HTMLSelectElement).value)"
>
<option value="pick" selected>(pick one)</option>
<option value="open">Open</option>
<option value="doing">In progress</option>
<option value="done">Done</option>
</select>
<select
aria-label="Set priority"
:disabled="!api"
@change="api && actions.priority(api, ($event.target as HTMLSelectElement).value)"
>
<option value="pick" selected>(pick one)</option>
<option value="low">Low</option>
<option value="high">High</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.fillOwner(api)"
>Fill owner down</button>
<button type="button" :disabled="!api" @click="api && actions.addHour(api)">Add 1 hour</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">Discard changes</button>
</div>
<Grid style="height: 290px" :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;
ticket: string;
owner: string;
status: string;
priority: string;
hours: number;
}
const tickets = [
'Login redirect error',
'Tidy footer links',
'Search results are slow',
'Typo in price list',
'Export fails in Safari',
'Notification settings not saved',
];
const rows: Row[] = tickets.map((ticket, i) => ({
id: i + 1,
ticket,
owner: i === 0 ? 'Liam Carter' : '',
status: 'open',
priority: i % 2 ? 'high' : 'low',
hours: i === 0 ? 3 : 0,
}));
const statusName: Record<string, string> = { open: 'Open', doing: 'In progress', done: 'Done' };
const priorityName: Record<string, string> = { low: 'Low', high: 'High' };
export const options: GridOptions<Row> = {
columns: [
{ id: 'ticket', title: 'Ticket', width: 230 },
{ id: 'owner', title: 'Owner', width: 120, editable: true },
{
id: 'status',
title: 'Status',
width: 110,
formatValue: (v) => statusName[String(v)] ?? String(v),
},
{
id: 'priority',
title: 'Priority',
width: 90,
formatValue: (v) => priorityName[String(v)] ?? String(v),
},
{ id: 'hours', title: 'Hours', kind: 'number', width: 80, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Select rows with the checkboxes on the left, then use the buttons or selects above.');
return api.on('changesCountChanged', ({ count }) => log(`Unsaved changes: ${count} rows`));
}
const selectedRows = (api: GridApi<Row>): Row[] =>
api.getSelectedKeys().flatMap((key) => {
const row = api.getRowByKey(key);
return row ? [row] : [];
});
// When editing several rows, call updateRows only once. The changes are then recorded as one batch, so they can be reviewed or discarded together before saving.
function setSelected(
api: GridApi<Row>,
column: 'status' | 'priority',
value: string | undefined,
names: Record<string, string>,
): void {
if (!value || value === 'pick') return;
// Reset the select to "(pick one)" so the same value can be chosen again (the select's id equals the control id).
const box = document.getElementById(column);
if (box instanceof HTMLSelectElement) box.value = 'pick';
const rows = selectedRows(api);
if (!rows.length) return say('Select at least one row first.');
const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
say(
`Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`,
);
}
export const actions = {
status: (api: GridApi<Row>, value?: string) => setSelected(api, 'status', value, statusName),
priority: (api: GridApi<Row>, value?: string) =>
setSelected(api, 'priority', value, priorityName),
// Fill down: copy the owner of the top selected row to the other selected rows (like Ctrl+D in a spreadsheet).
fillOwner: (api: GridApi<Row>) => {
const [first, ...rest] = selectedRows(api);
if (!first || !rest.length)
return say('Select two or more rows. The value of the top row is filled into the rest.');
const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
say(`Filled "${first.owner || '(empty)'}" into ${n} rows.`);
},
addHour: (api: GridApi<Row>) => {
const rows = selectedRows(api);
if (!rows.length) return say('Select at least one row first.');
say(
`Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`,
);
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
discard: (api: GridApi<Row>) => {
api.rollbackChanges();
api.setSelectedKeys([]);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.selectAll(api)"
>Select all</button>
<select
aria-label="Set status"
[disabled]="!api"
(change)="api && actions.status(api, $any($event.target).value)"
>
<option value="pick" selected>(pick one)</option>
<option value="open">Open</option>
<option value="doing">In progress</option>
<option value="done">Done</option>
</select>
<select
aria-label="Set priority"
[disabled]="!api"
(change)="api && actions.priority(api, $any($event.target).value)"
>
<option value="pick" selected>(pick one)</option>
<option value="low">Low</option>
<option value="high">High</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.fillOwner(api)"
>Fill owner down</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.addHour(api)"
>Add 1 hour</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(api)"
>Discard changes</button>
</div>
<mx-grid style="height: 290px" [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;
ticket: string;
owner: string;
status: string;
priority: string;
hours: number;
}
const tickets = [
'Login redirect error',
'Tidy footer links',
'Search results are slow',
'Typo in price list',
'Export fails in Safari',
'Notification settings not saved',
];
const rows: Row[] = tickets.map((ticket, i) => ({
id: i + 1,
ticket,
owner: i === 0 ? 'Liam Carter' : '',
status: 'open',
priority: i % 2 ? 'high' : 'low',
hours: i === 0 ? 3 : 0,
}));
const statusName: Record<string, string> = { open: 'Open', doing: 'In progress', done: 'Done' };
const priorityName: Record<string, string> = { low: 'Low', high: 'High' };
export const options: GridOptions<Row> = {
columns: [
{ id: 'ticket', title: 'Ticket', width: 230 },
{ id: 'owner', title: 'Owner', width: 120, editable: true },
{
id: 'status',
title: 'Status',
width: 110,
formatValue: (v) => statusName[String(v)] ?? String(v),
},
{
id: 'priority',
title: 'Priority',
width: 90,
formatValue: (v) => priorityName[String(v)] ?? String(v),
},
{ id: 'hours', title: 'Hours', kind: 'number', width: 80, align: 'end', editable: true },
],
rows,
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
saveMode: 'batch',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Select rows with the checkboxes on the left, then use the buttons or selects above.');
return api.on('changesCountChanged', ({ count }) => log(`Unsaved changes: ${count} rows`));
}
const selectedRows = (api: GridApi<Row>): Row[] =>
api.getSelectedKeys().flatMap((key) => {
const row = api.getRowByKey(key);
return row ? [row] : [];
});
// When editing several rows, call updateRows only once. The changes are then recorded as one batch, so they can be reviewed or discarded together before saving.
function setSelected(
api: GridApi<Row>,
column: 'status' | 'priority',
value: string | undefined,
names: Record<string, string>,
): void {
if (!value || value === 'pick') return;
// Reset the select to "(pick one)" so the same value can be chosen again (the select's id equals the control id).
const box = document.getElementById(column);
if (box instanceof HTMLSelectElement) box.value = 'pick';
const rows = selectedRows(api);
if (!rows.length) return say('Select at least one row first.');
const n = api.updateRows(rows.map((row) => ({ ...row, [column]: value })));
say(
`Set ${column === 'status' ? 'status' : 'priority'} of ${n} rows to "${names[value] ?? value}".`,
);
}
export const actions = {
status: (api: GridApi<Row>, value?: string) => setSelected(api, 'status', value, statusName),
priority: (api: GridApi<Row>, value?: string) =>
setSelected(api, 'priority', value, priorityName),
// Fill down: copy the owner of the top selected row to the other selected rows (like Ctrl+D in a spreadsheet).
fillOwner: (api: GridApi<Row>) => {
const [first, ...rest] = selectedRows(api);
if (!first || !rest.length)
return say('Select two or more rows. The value of the top row is filled into the rest.');
const n = api.updateRows(rest.map((row) => ({ ...row, owner: first.owner })));
say(`Filled "${first.owner || '(empty)'}" into ${n} rows.`);
},
addHour: (api: GridApi<Row>) => {
const rows = selectedRows(api);
if (!rows.length) return say('Select at least one row first.');
say(
`Added 1 hour to ${api.updateRows(rows.map((row) => ({ ...row, hours: row.hours + 1 })))} rows.`,
);
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
discard: (api: GridApi<Row>) => {
api.rollbackChanges();
api.setSelectedKeys([]);
},
};