저장하기 전에 빈 필수 칸 점검Check required cells before saving
처음부터 비어 있던 칸은 고치지 않으면 검사되지 않아요. 그래서 모든 줄을 훑어 빈 칸을 컬럼별로 모아 보여 주고, 저장(save)은 바뀐 줄 전부를 검사해서 하나라도 틀리면 아무것도 보내지 않게 했어요.Cells that start empty are not checked until someone edits them. So scan every row and group the gaps per column, and let save() validate all changed rows and send nothing if one is wrong.
코드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="scan">빈 칸 점검</button>
<button type="button" id="firstGap">첫 빈 칸으로</button>
<button type="button" id="addEmpty">빈 새 줄 넣기</button>
<button type="button" id="save">저장</button>
<button type="button" id="discard">변경 버리기</button>
</div>
<div id="grid" style="height: 300px"></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('scan').addEventListener('click', () => actions.scan(api));
document.getElementById('firstGap').addEventListener('click', () => actions.firstGap(api));
document.getElementById('addEmpty').addEventListener('click', () => actions.addEmpty(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));const rows = [
{ id: 1, name: '김서연', email: 'seoyeon@example.com', team: '개발' },
{ id: 2, name: '이준호', email: '', team: '디자인' },
{ id: 3, name: '', email: '', team: '' },
{ id: 4, name: '최도윤', email: 'doyun@example.com', team: '기획' },
];
const FIELDS = ['name', 'email', 'team'];
const label = { name: '이름', email: '이메일', team: '팀' };
const labelEn = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say = () => { };
// 비어 있는 필수 칸은 눈에 띄게 표시해요(CSS 변수라서 밝은·어두운 테마 모두 맞아요).
const emptyMark = (ctx) => String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
export const options = {
columns: [
{
id: 'name',
title: '이름 *',
width: 120,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'email',
title: '이메일 *',
width: 210,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'team',
title: '팀 *',
width: 110,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300)); // 서버에 보내는 시간을 흉내 내요.
},
};
// 필수 칸은 "고칠 때"만 검사돼요. 처음부터 비어 있던 칸은 아무도 안 건드렸으니 검사되지 않아요.
// 그래서 저장하기 전에 모든 줄을 훑어서 빈 칸을 컬럼별로 모아 보여 줘요(내가 짠 점검 함수예요).
function gaps(api) {
return api
.getRows()
.flatMap((row) => FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })));
}
export function setup(api, log) {
say = log;
const found = gaps(api);
log({
ko: found.length
? `빈 칸이 ${found.length}개 있어요. "빈 칸 점검"으로 어디인지 확인해 보세요.`
: '모든 필수 칸이 채워져 있어요.',
en: found.length
? `${found.length} empty cells. Use "Check empty cells" to see where.`
: 'All required cells are filled.',
});
return api.on('validationFailed', (e) => log({
ko: `✗ ${e.rowKey}번 줄 ${label[e.columnId] ?? e.columnId}: ${e.message}`,
en: `✗ Row ${e.rowKey} ${labelEn[e.columnId] ?? e.columnId}: ${e.message}`,
}));
}
export const actions = {
scan: (api) => {
const found = gaps(api);
if (!found.length)
return say({ ko: '✓ 빈 칸이 없어요.', en: '✓ No empty cells.' });
const byField = FIELDS.map((f) => [f, found.filter((g) => g.field === f).map((g) => g.key)]).filter(([, keys]) => keys.length);
say({
ko: `빈 칸 ${found.length}개 → ${byField.map(([f, keys]) => `${label[f]}: ${keys.join(', ')}번 줄`).join(' / ')}`,
en: `${found.length} empty cells → ${byField.map(([f, keys]) => `${labelEn[f]}: rows ${keys.join(', ')}`).join(' / ')}`,
});
},
firstGap: (api) => {
const first = gaps(api)[0];
if (!first)
return say({ ko: '✓ 비어 있는 칸이 없어요.', en: '✓ No empty cells.' });
api.startEdit(first.key, first.field);
},
// save()는 바뀐 줄 전부를 먼저 검사하고, 하나라도 틀리면 아무것도 보내지 않아요.
addEmpty: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
say({
ko: `빈 새 줄(${nextId}번)을 맨 위에 넣었어요. 이제 저장해 보세요.`,
en: `Put an empty new row (${nextId}) at the top. Now try saving.`,
});
},
save: async (api) => {
const report = await api.save();
say({
ko: report.status === 'invalid'
? '값이 맞지 않아 저장하지 않았어요. 아래 ✗ 줄에서 이유를 확인해 주세요.'
: report.status === 'empty'
? '저장할 변경이 없어요. (처음부터 비어 있던 칸은 고친 것이 아니라서 변경에 들어가지 않아요)'
: report.status === 'saved'
? `모두 저장했어요. (${report.committed}줄)`
: `저장 결과를 확인해 주세요. (${report.status})`,
en: report.status === 'invalid'
? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
: report.status === 'empty'
? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
: report.status === 'saved'
? `All saved. (${report.committed} rows)`
: `Check the save result. (${report.status})`,
});
},
discard: (api) => api.rollbackChanges(),
};<!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="scan">빈 칸 점검</button>
<button type="button" id="firstGap">첫 빈 칸으로</button>
<button type="button" id="addEmpty">빈 새 줄 넣기</button>
<button type="button" id="save">저장</button>
<button type="button" id="discard">변경 버리기</button>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, name: '김서연', email: 'seoyeon@example.com', team: '개발' },
{ id: 2, name: '이준호', email: '', team: '디자인' },
{ id: 3, name: '', email: '', team: '' },
{ id: 4, name: '최도윤', email: 'doyun@example.com', team: '기획' },
];
const FIELDS = ['name', 'email', 'team'];
const label = { name: '이름', email: '이메일', team: '팀' };
const labelEn = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say = () => { };
// 비어 있는 필수 칸은 눈에 띄게 표시해요(CSS 변수라서 밝은·어두운 테마 모두 맞아요).
const emptyMark = (ctx) => String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
const options = {
columns: [
{
id: 'name',
title: '이름 *',
width: 120,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'email',
title: '이메일 *',
width: 210,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'team',
title: '팀 *',
width: 110,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300)); // 서버에 보내는 시간을 흉내 내요.
},
};
// 필수 칸은 "고칠 때"만 검사돼요. 처음부터 비어 있던 칸은 아무도 안 건드렸으니 검사되지 않아요.
// 그래서 저장하기 전에 모든 줄을 훑어서 빈 칸을 컬럼별로 모아 보여 줘요(내가 짠 점검 함수예요).
function gaps(api) {
return api
.getRows()
.flatMap((row) => FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })));
}
function setup(api, log) {
say = log;
const found = gaps(api);
log({
ko: found.length
? `빈 칸이 ${found.length}개 있어요. "빈 칸 점검"으로 어디인지 확인해 보세요.`
: '모든 필수 칸이 채워져 있어요.',
en: found.length
? `${found.length} empty cells. Use "Check empty cells" to see where.`
: 'All required cells are filled.',
});
return api.on('validationFailed', (e) => log({
ko: `✗ ${e.rowKey}번 줄 ${label[e.columnId] ?? e.columnId}: ${e.message}`,
en: `✗ Row ${e.rowKey} ${labelEn[e.columnId] ?? e.columnId}: ${e.message}`,
}));
}
const actions = {
scan: (api) => {
const found = gaps(api);
if (!found.length)
return say({ ko: '✓ 빈 칸이 없어요.', en: '✓ No empty cells.' });
const byField = FIELDS.map((f) => [f, found.filter((g) => g.field === f).map((g) => g.key)]).filter(([, keys]) => keys.length);
say({
ko: `빈 칸 ${found.length}개 → ${byField.map(([f, keys]) => `${label[f]}: ${keys.join(', ')}번 줄`).join(' / ')}`,
en: `${found.length} empty cells → ${byField.map(([f, keys]) => `${labelEn[f]}: rows ${keys.join(', ')}`).join(' / ')}`,
});
},
firstGap: (api) => {
const first = gaps(api)[0];
if (!first)
return say({ ko: '✓ 비어 있는 칸이 없어요.', en: '✓ No empty cells.' });
api.startEdit(first.key, first.field);
},
// save()는 바뀐 줄 전부를 먼저 검사하고, 하나라도 틀리면 아무것도 보내지 않아요.
addEmpty: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
say({
ko: `빈 새 줄(${nextId}번)을 맨 위에 넣었어요. 이제 저장해 보세요.`,
en: `Put an empty new row (${nextId}) at the top. Now try saving.`,
});
},
save: async (api) => {
const report = await api.save();
say({
ko: report.status === 'invalid'
? '값이 맞지 않아 저장하지 않았어요. 아래 ✗ 줄에서 이유를 확인해 주세요.'
: report.status === 'empty'
? '저장할 변경이 없어요. (처음부터 비어 있던 칸은 고친 것이 아니라서 변경에 들어가지 않아요)'
: report.status === 'saved'
? `모두 저장했어요. (${report.committed}줄)`
: `저장 결과를 확인해 주세요. (${report.status})`,
en: report.status === 'invalid'
? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
: report.status === 'empty'
? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
: report.status === 'saved'
? `All saved. (${report.committed} rows)`
: `Check the save result. (${report.status})`,
});
},
discard: (api) => api.rollbackChanges(),
};
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('scan').addEventListener('click', () => actions.scan(api));
document.getElementById('firstGap').addEventListener('click', () => actions.firstGap(api));
document.getElementById('addEmpty').addEventListener('click', () => actions.addEmpty(api));
document.getElementById('save').addEventListener('click', () => actions.save(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.scan(api)}
>빈 칸 점검</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.firstGap(api)}
>첫 빈 칸으로</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.addEmpty(api)}
>빈 새 줄 넣기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>저장</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>변경 버리기</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import type { CellContext, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
team: string;
}
const rows: Row[] = [
{ id: 1, name: '김서연', email: 'seoyeon@example.com', team: '개발' },
{ id: 2, name: '이준호', email: '', team: '디자인' },
{ id: 3, name: '', email: '', team: '' },
{ id: 4, name: '최도윤', email: 'doyun@example.com', team: '기획' },
];
const FIELDS = ['name', 'email', 'team'] as const;
const label: Record<string, string> = { name: '이름', email: '이메일', team: '팀' };
const labelEn: Record<string, string> = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say: (message: LogText) => void = () => {};
// 비어 있는 필수 칸은 눈에 띄게 표시해요(CSS 변수라서 밝은·어두운 테마 모두 맞아요).
const emptyMark = (ctx: CellContext<Row>): string | undefined =>
String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: '이름 *',
width: 120,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'email',
title: '이메일 *',
width: 210,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'team',
title: '팀 *',
width: 110,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300)); // 서버에 보내는 시간을 흉내 내요.
},
};
// 필수 칸은 "고칠 때"만 검사돼요. 처음부터 비어 있던 칸은 아무도 안 건드렸으니 검사되지 않아요.
// 그래서 저장하기 전에 모든 줄을 훑어서 빈 칸을 컬럼별로 모아 보여 줘요(내가 짠 점검 함수예요).
function gaps(api: GridApi<Row>): { key: number; field: string }[] {
return api
.getRows()
.flatMap((row) =>
FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })),
);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const found = gaps(api);
log({
ko: found.length
? `빈 칸이 ${found.length}개 있어요. "빈 칸 점검"으로 어디인지 확인해 보세요.`
: '모든 필수 칸이 채워져 있어요.',
en: found.length
? `${found.length} empty cells. Use "Check empty cells" to see where.`
: 'All required cells are filled.',
});
return api.on('validationFailed', (e) =>
log({
ko: `✗ ${e.rowKey}번 줄 ${label[e.columnId] ?? e.columnId}: ${e.message}`,
en: `✗ Row ${e.rowKey} ${labelEn[e.columnId] ?? e.columnId}: ${e.message}`,
}),
);
}
export const actions = {
scan: (api: GridApi<Row>) => {
const found = gaps(api);
if (!found.length) return say({ ko: '✓ 빈 칸이 없어요.', en: '✓ No empty cells.' });
const byField = FIELDS.map(
(f) => [f, found.filter((g) => g.field === f).map((g) => g.key)] as const,
).filter(([, keys]) => keys.length);
say({
ko: `빈 칸 ${found.length}개 → ${byField.map(([f, keys]) => `${label[f]}: ${keys.join(', ')}번 줄`).join(' / ')}`,
en: `${found.length} empty cells → ${byField.map(([f, keys]) => `${labelEn[f]}: rows ${keys.join(', ')}`).join(' / ')}`,
});
},
firstGap: (api: GridApi<Row>) => {
const first = gaps(api)[0];
if (!first) return say({ ko: '✓ 비어 있는 칸이 없어요.', en: '✓ No empty cells.' });
api.startEdit(first.key, first.field);
},
// save()는 바뀐 줄 전부를 먼저 검사하고, 하나라도 틀리면 아무것도 보내지 않아요.
addEmpty: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
say({
ko: `빈 새 줄(${nextId}번)을 맨 위에 넣었어요. 이제 저장해 보세요.`,
en: `Put an empty new row (${nextId}) at the top. Now try saving.`,
});
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({
ko:
report.status === 'invalid'
? '값이 맞지 않아 저장하지 않았어요. 아래 ✗ 줄에서 이유를 확인해 주세요.'
: report.status === 'empty'
? '저장할 변경이 없어요. (처음부터 비어 있던 칸은 고친 것이 아니라서 변경에 들어가지 않아요)'
: report.status === 'saved'
? `모두 저장했어요. (${report.committed}줄)`
: `저장 결과를 확인해 주세요. (${report.status})`,
en:
report.status === 'invalid'
? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
: report.status === 'empty'
? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
: report.status === 'saved'
? `All saved. (${report.committed} rows)`
: `Check the save result. (${report.status})`,
});
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};버튼을 누르면 이 예제의 코드가 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.scan(api)">빈 칸 점검</button>
<button
type="button"
:disabled="!api"
@click="api && actions.firstGap(api)"
>첫 빈 칸으로</button>
<button
type="button"
:disabled="!api"
@click="api && actions.addEmpty(api)"
>빈 새 줄 넣기</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">저장</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">변경 버리기</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import type { CellContext, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
team: string;
}
const rows: Row[] = [
{ id: 1, name: '김서연', email: 'seoyeon@example.com', team: '개발' },
{ id: 2, name: '이준호', email: '', team: '디자인' },
{ id: 3, name: '', email: '', team: '' },
{ id: 4, name: '최도윤', email: 'doyun@example.com', team: '기획' },
];
const FIELDS = ['name', 'email', 'team'] as const;
const label: Record<string, string> = { name: '이름', email: '이메일', team: '팀' };
const labelEn: Record<string, string> = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say: (message: LogText) => void = () => {};
// 비어 있는 필수 칸은 눈에 띄게 표시해요(CSS 변수라서 밝은·어두운 테마 모두 맞아요).
const emptyMark = (ctx: CellContext<Row>): string | undefined =>
String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: '이름 *',
width: 120,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'email',
title: '이메일 *',
width: 210,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'team',
title: '팀 *',
width: 110,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300)); // 서버에 보내는 시간을 흉내 내요.
},
};
// 필수 칸은 "고칠 때"만 검사돼요. 처음부터 비어 있던 칸은 아무도 안 건드렸으니 검사되지 않아요.
// 그래서 저장하기 전에 모든 줄을 훑어서 빈 칸을 컬럼별로 모아 보여 줘요(내가 짠 점검 함수예요).
function gaps(api: GridApi<Row>): { key: number; field: string }[] {
return api
.getRows()
.flatMap((row) =>
FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })),
);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const found = gaps(api);
log({
ko: found.length
? `빈 칸이 ${found.length}개 있어요. "빈 칸 점검"으로 어디인지 확인해 보세요.`
: '모든 필수 칸이 채워져 있어요.',
en: found.length
? `${found.length} empty cells. Use "Check empty cells" to see where.`
: 'All required cells are filled.',
});
return api.on('validationFailed', (e) =>
log({
ko: `✗ ${e.rowKey}번 줄 ${label[e.columnId] ?? e.columnId}: ${e.message}`,
en: `✗ Row ${e.rowKey} ${labelEn[e.columnId] ?? e.columnId}: ${e.message}`,
}),
);
}
export const actions = {
scan: (api: GridApi<Row>) => {
const found = gaps(api);
if (!found.length) return say({ ko: '✓ 빈 칸이 없어요.', en: '✓ No empty cells.' });
const byField = FIELDS.map(
(f) => [f, found.filter((g) => g.field === f).map((g) => g.key)] as const,
).filter(([, keys]) => keys.length);
say({
ko: `빈 칸 ${found.length}개 → ${byField.map(([f, keys]) => `${label[f]}: ${keys.join(', ')}번 줄`).join(' / ')}`,
en: `${found.length} empty cells → ${byField.map(([f, keys]) => `${labelEn[f]}: rows ${keys.join(', ')}`).join(' / ')}`,
});
},
firstGap: (api: GridApi<Row>) => {
const first = gaps(api)[0];
if (!first) return say({ ko: '✓ 비어 있는 칸이 없어요.', en: '✓ No empty cells.' });
api.startEdit(first.key, first.field);
},
// save()는 바뀐 줄 전부를 먼저 검사하고, 하나라도 틀리면 아무것도 보내지 않아요.
addEmpty: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
say({
ko: `빈 새 줄(${nextId}번)을 맨 위에 넣었어요. 이제 저장해 보세요.`,
en: `Put an empty new row (${nextId}) at the top. Now try saving.`,
});
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({
ko:
report.status === 'invalid'
? '값이 맞지 않아 저장하지 않았어요. 아래 ✗ 줄에서 이유를 확인해 주세요.'
: report.status === 'empty'
? '저장할 변경이 없어요. (처음부터 비어 있던 칸은 고친 것이 아니라서 변경에 들어가지 않아요)'
: report.status === 'saved'
? `모두 저장했어요. (${report.committed}줄)`
: `저장 결과를 확인해 주세요. (${report.status})`,
en:
report.status === 'invalid'
? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
: report.status === 'empty'
? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
: report.status === 'saved'
? `All saved. (${report.committed} rows)`
: `Check the save result. (${report.status})`,
});
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};버튼을 누르면 이 예제의 코드가 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.scan(api)"
>빈 칸 점검</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.firstGap(api)"
>첫 빈 칸으로</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.addEmpty(api)"
>빈 새 줄 넣기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>저장</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(api)"
>변경 버리기</button>
</div>
<mx-grid style="height: 300px" [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 { CellContext, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
team: string;
}
const rows: Row[] = [
{ id: 1, name: '김서연', email: 'seoyeon@example.com', team: '개발' },
{ id: 2, name: '이준호', email: '', team: '디자인' },
{ id: 3, name: '', email: '', team: '' },
{ id: 4, name: '최도윤', email: 'doyun@example.com', team: '기획' },
];
const FIELDS = ['name', 'email', 'team'] as const;
const label: Record<string, string> = { name: '이름', email: '이메일', team: '팀' };
const labelEn: Record<string, string> = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say: (message: LogText) => void = () => {};
// 비어 있는 필수 칸은 눈에 띄게 표시해요(CSS 변수라서 밝은·어두운 테마 모두 맞아요).
const emptyMark = (ctx: CellContext<Row>): string | undefined =>
String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: '이름 *',
width: 120,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'email',
title: '이메일 *',
width: 210,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'team',
title: '팀 *',
width: 110,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300)); // 서버에 보내는 시간을 흉내 내요.
},
};
// 필수 칸은 "고칠 때"만 검사돼요. 처음부터 비어 있던 칸은 아무도 안 건드렸으니 검사되지 않아요.
// 그래서 저장하기 전에 모든 줄을 훑어서 빈 칸을 컬럼별로 모아 보여 줘요(내가 짠 점검 함수예요).
function gaps(api: GridApi<Row>): { key: number; field: string }[] {
return api
.getRows()
.flatMap((row) =>
FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })),
);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const found = gaps(api);
log({
ko: found.length
? `빈 칸이 ${found.length}개 있어요. "빈 칸 점검"으로 어디인지 확인해 보세요.`
: '모든 필수 칸이 채워져 있어요.',
en: found.length
? `${found.length} empty cells. Use "Check empty cells" to see where.`
: 'All required cells are filled.',
});
return api.on('validationFailed', (e) =>
log({
ko: `✗ ${e.rowKey}번 줄 ${label[e.columnId] ?? e.columnId}: ${e.message}`,
en: `✗ Row ${e.rowKey} ${labelEn[e.columnId] ?? e.columnId}: ${e.message}`,
}),
);
}
export const actions = {
scan: (api: GridApi<Row>) => {
const found = gaps(api);
if (!found.length) return say({ ko: '✓ 빈 칸이 없어요.', en: '✓ No empty cells.' });
const byField = FIELDS.map(
(f) => [f, found.filter((g) => g.field === f).map((g) => g.key)] as const,
).filter(([, keys]) => keys.length);
say({
ko: `빈 칸 ${found.length}개 → ${byField.map(([f, keys]) => `${label[f]}: ${keys.join(', ')}번 줄`).join(' / ')}`,
en: `${found.length} empty cells → ${byField.map(([f, keys]) => `${labelEn[f]}: rows ${keys.join(', ')}`).join(' / ')}`,
});
},
firstGap: (api: GridApi<Row>) => {
const first = gaps(api)[0];
if (!first) return say({ ko: '✓ 비어 있는 칸이 없어요.', en: '✓ No empty cells.' });
api.startEdit(first.key, first.field);
},
// save()는 바뀐 줄 전부를 먼저 검사하고, 하나라도 틀리면 아무것도 보내지 않아요.
addEmpty: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
say({
ko: `빈 새 줄(${nextId}번)을 맨 위에 넣었어요. 이제 저장해 보세요.`,
en: `Put an empty new row (${nextId}) at the top. Now try saving.`,
});
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({
ko:
report.status === 'invalid'
? '값이 맞지 않아 저장하지 않았어요. 아래 ✗ 줄에서 이유를 확인해 주세요.'
: report.status === 'empty'
? '저장할 변경이 없어요. (처음부터 비어 있던 칸은 고친 것이 아니라서 변경에 들어가지 않아요)'
: report.status === 'saved'
? `모두 저장했어요. (${report.committed}줄)`
: `저장 결과를 확인해 주세요. (${report.status})`,
en:
report.status === 'invalid'
? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
: report.status === 'empty'
? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
: report.status === 'saved'
? `All saved. (${report.committed} rows)`
: `Check the save result. (${report.status})`,
});
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};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="scan">Scan empty cells</button>
<button type="button" id="firstGap">Go to first gap</button>
<button type="button" id="addEmpty">Add empty row</button>
<button type="button" id="save">Save</button>
<button type="button" id="discard">Discard changes</button>
</div>
<div id="grid" style="height: 300px"></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('scan').addEventListener('click', () => actions.scan(api));
document.getElementById('firstGap').addEventListener('click', () => actions.firstGap(api));
document.getElementById('addEmpty').addEventListener('click', () => actions.addEmpty(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));const rows = [
{ id: 1, name: 'Liam Carter', email: 'liam@example.com', team: 'Dev' },
{ id: 2, name: 'Emma Stone', email: '', team: 'Design' },
{ id: 3, name: '', email: '', team: '' },
{ id: 4, name: 'Noah Kim', email: 'noah@example.com', team: 'Planning' },
];
const FIELDS = ['name', 'email', 'team'];
const label = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say = () => { };
// Empty required cells are marked visibly (it uses CSS variables, so it fits both light and dark themes).
const emptyMark = (ctx) => String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
export const options = {
columns: [
{
id: 'name',
title: 'Name *',
width: 140,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'email',
title: 'Email *',
width: 210,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'team',
title: 'Team *',
width: 110,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300)); // Simulates the time it takes to send to a server.
},
};
// A required cell is only checked when it is edited. A cell that was empty from the start was never touched, so it is not checked.
// So before saving, scan every row and gather the empty cells by column (this is a check function written by the app).
function gaps(api) {
return api
.getRows()
.flatMap((row) => FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })));
}
export function setup(api, log) {
say = log;
const found = gaps(api);
log(found.length
? `${found.length} empty cells. Use "Scan empty cells" to see where.`
: 'All required cells are filled.');
return api.on('validationFailed', (e) => log(`✗ Row ${e.rowKey} ${label[e.columnId] ?? e.columnId}: ${e.message}`));
}
export const actions = {
scan: (api) => {
const found = gaps(api);
if (!found.length)
return say('✓ No empty cells.');
const byField = FIELDS.map((f) => [f, found.filter((g) => g.field === f).map((g) => g.key)]).filter(([, keys]) => keys.length);
say(`${found.length} empty cells → ${byField.map(([f, keys]) => `${label[f]}: rows ${keys.join(', ')}`).join(' / ')}`);
},
firstGap: (api) => {
const first = gaps(api)[0];
if (!first)
return say('✓ No empty cells.');
api.startEdit(first.key, first.field);
},
// save() checks every changed row first, and sends nothing if even one is wrong.
addEmpty: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
say(`Put an empty new row (${nextId}) at the top. Now try saving.`);
},
save: async (api) => {
const report = await api.save();
say(report.status === 'invalid'
? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
: report.status === 'empty'
? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
: report.status === 'saved'
? `All saved. (${report.committed} rows)`
: `Check the save result. (${report.status})`);
},
discard: (api) => api.rollbackChanges(),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Check required cells before saving</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="scan">Scan empty cells</button>
<button type="button" id="firstGap">Go to first gap</button>
<button type="button" id="addEmpty">Add empty row</button>
<button type="button" id="save">Save</button>
<button type="button" id="discard">Discard changes</button>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, name: 'Liam Carter', email: 'liam@example.com', team: 'Dev' },
{ id: 2, name: 'Emma Stone', email: '', team: 'Design' },
{ id: 3, name: '', email: '', team: '' },
{ id: 4, name: 'Noah Kim', email: 'noah@example.com', team: 'Planning' },
];
const FIELDS = ['name', 'email', 'team'];
const label = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say = () => { };
// Empty required cells are marked visibly (it uses CSS variables, so it fits both light and dark themes).
const emptyMark = (ctx) => String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
const options = {
columns: [
{
id: 'name',
title: 'Name *',
width: 140,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'email',
title: 'Email *',
width: 210,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'team',
title: 'Team *',
width: 110,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300)); // Simulates the time it takes to send to a server.
},
};
// A required cell is only checked when it is edited. A cell that was empty from the start was never touched, so it is not checked.
// So before saving, scan every row and gather the empty cells by column (this is a check function written by the app).
function gaps(api) {
return api
.getRows()
.flatMap((row) => FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })));
}
function setup(api, log) {
say = log;
const found = gaps(api);
log(found.length
? `${found.length} empty cells. Use "Scan empty cells" to see where.`
: 'All required cells are filled.');
return api.on('validationFailed', (e) => log(`✗ Row ${e.rowKey} ${label[e.columnId] ?? e.columnId}: ${e.message}`));
}
const actions = {
scan: (api) => {
const found = gaps(api);
if (!found.length)
return say('✓ No empty cells.');
const byField = FIELDS.map((f) => [f, found.filter((g) => g.field === f).map((g) => g.key)]).filter(([, keys]) => keys.length);
say(`${found.length} empty cells → ${byField.map(([f, keys]) => `${label[f]}: rows ${keys.join(', ')}`).join(' / ')}`);
},
firstGap: (api) => {
const first = gaps(api)[0];
if (!first)
return say('✓ No empty cells.');
api.startEdit(first.key, first.field);
},
// save() checks every changed row first, and sends nothing if even one is wrong.
addEmpty: (api) => {
nextId += 1;
api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
say(`Put an empty new row (${nextId}) at the top. Now try saving.`);
},
save: async (api) => {
const report = await api.save();
say(report.status === 'invalid'
? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
: report.status === 'empty'
? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
: report.status === 'saved'
? `All saved. (${report.committed} rows)`
: `Check the save result. (${report.status})`);
},
discard: (api) => api.rollbackChanges(),
};
options.ariaLabel = "Check required cells before saving";
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('scan').addEventListener('click', () => actions.scan(api));
document.getElementById('firstGap').addEventListener('click', () => actions.firstGap(api));
document.getElementById('addEmpty').addEventListener('click', () => actions.addEmpty(api));
document.getElementById('save').addEventListener('click', () => actions.save(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.scan(api)}
>Scan empty cells</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.firstGap(api)}
>Go to first gap</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.addEmpty(api)}
>Add empty row</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>Save</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.discard(api)}
>Discard changes</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import type { CellContext, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
team: string;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', email: 'liam@example.com', team: 'Dev' },
{ id: 2, name: 'Emma Stone', email: '', team: 'Design' },
{ id: 3, name: '', email: '', team: '' },
{ id: 4, name: 'Noah Kim', email: 'noah@example.com', team: 'Planning' },
];
const FIELDS = ['name', 'email', 'team'] as const;
const label: Record<string, string> = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say: (message: LogText) => void = () => {};
// Empty required cells are marked visibly (it uses CSS variables, so it fits both light and dark themes).
const emptyMark = (ctx: CellContext<Row>): string | undefined =>
String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: 'Name *',
width: 140,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'email',
title: 'Email *',
width: 210,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'team',
title: 'Team *',
width: 110,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300)); // Simulates the time it takes to send to a server.
},
};
// A required cell is only checked when it is edited. A cell that was empty from the start was never touched, so it is not checked.
// So before saving, scan every row and gather the empty cells by column (this is a check function written by the app).
function gaps(api: GridApi<Row>): { key: number; field: string }[] {
return api
.getRows()
.flatMap((row) =>
FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })),
);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const found = gaps(api);
log(
found.length
? `${found.length} empty cells. Use "Scan empty cells" to see where.`
: 'All required cells are filled.',
);
return api.on('validationFailed', (e) =>
log(`✗ Row ${e.rowKey} ${label[e.columnId] ?? e.columnId}: ${e.message}`),
);
}
export const actions = {
scan: (api: GridApi<Row>) => {
const found = gaps(api);
if (!found.length) return say('✓ No empty cells.');
const byField = FIELDS.map(
(f) => [f, found.filter((g) => g.field === f).map((g) => g.key)] as const,
).filter(([, keys]) => keys.length);
say(
`${found.length} empty cells → ${byField.map(([f, keys]) => `${label[f]}: rows ${keys.join(', ')}`).join(' / ')}`,
);
},
firstGap: (api: GridApi<Row>) => {
const first = gaps(api)[0];
if (!first) return say('✓ No empty cells.');
api.startEdit(first.key, first.field);
},
// save() checks every changed row first, and sends nothing if even one is wrong.
addEmpty: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
say(`Put an empty new row (${nextId}) at the top. Now try saving.`);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(
report.status === 'invalid'
? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
: report.status === 'empty'
? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
: report.status === 'saved'
? `All saved. (${report.committed} rows)`
: `Check the save result. (${report.status})`,
);
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};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.scan(api)">Scan empty cells</button>
<button
type="button"
:disabled="!api"
@click="api && actions.firstGap(api)"
>Go to first gap</button>
<button
type="button"
:disabled="!api"
@click="api && actions.addEmpty(api)"
>Add empty row</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">Save</button>
<button type="button" :disabled="!api" @click="api && actions.discard(api)">Discard changes</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import type { CellContext, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
team: string;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', email: 'liam@example.com', team: 'Dev' },
{ id: 2, name: 'Emma Stone', email: '', team: 'Design' },
{ id: 3, name: '', email: '', team: '' },
{ id: 4, name: 'Noah Kim', email: 'noah@example.com', team: 'Planning' },
];
const FIELDS = ['name', 'email', 'team'] as const;
const label: Record<string, string> = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say: (message: LogText) => void = () => {};
// Empty required cells are marked visibly (it uses CSS variables, so it fits both light and dark themes).
const emptyMark = (ctx: CellContext<Row>): string | undefined =>
String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: 'Name *',
width: 140,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'email',
title: 'Email *',
width: 210,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'team',
title: 'Team *',
width: 110,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300)); // Simulates the time it takes to send to a server.
},
};
// A required cell is only checked when it is edited. A cell that was empty from the start was never touched, so it is not checked.
// So before saving, scan every row and gather the empty cells by column (this is a check function written by the app).
function gaps(api: GridApi<Row>): { key: number; field: string }[] {
return api
.getRows()
.flatMap((row) =>
FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })),
);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const found = gaps(api);
log(
found.length
? `${found.length} empty cells. Use "Scan empty cells" to see where.`
: 'All required cells are filled.',
);
return api.on('validationFailed', (e) =>
log(`✗ Row ${e.rowKey} ${label[e.columnId] ?? e.columnId}: ${e.message}`),
);
}
export const actions = {
scan: (api: GridApi<Row>) => {
const found = gaps(api);
if (!found.length) return say('✓ No empty cells.');
const byField = FIELDS.map(
(f) => [f, found.filter((g) => g.field === f).map((g) => g.key)] as const,
).filter(([, keys]) => keys.length);
say(
`${found.length} empty cells → ${byField.map(([f, keys]) => `${label[f]}: rows ${keys.join(', ')}`).join(' / ')}`,
);
},
firstGap: (api: GridApi<Row>) => {
const first = gaps(api)[0];
if (!first) return say('✓ No empty cells.');
api.startEdit(first.key, first.field);
},
// save() checks every changed row first, and sends nothing if even one is wrong.
addEmpty: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
say(`Put an empty new row (${nextId}) at the top. Now try saving.`);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(
report.status === 'invalid'
? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
: report.status === 'empty'
? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
: report.status === 'saved'
? `All saved. (${report.committed} rows)`
: `Check the save result. (${report.status})`,
);
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};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.scan(api)"
>Scan empty cells</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.firstGap(api)"
>Go to first gap</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.addEmpty(api)"
>Add empty row</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>Save</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.discard(api)"
>Discard changes</button>
</div>
<mx-grid style="height: 300px" [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 { CellContext, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
email: string;
team: string;
}
const rows: Row[] = [
{ id: 1, name: 'Liam Carter', email: 'liam@example.com', team: 'Dev' },
{ id: 2, name: 'Emma Stone', email: '', team: 'Design' },
{ id: 3, name: '', email: '', team: '' },
{ id: 4, name: 'Noah Kim', email: 'noah@example.com', team: 'Planning' },
];
const FIELDS = ['name', 'email', 'team'] as const;
const label: Record<string, string> = { name: 'Name', email: 'Email', team: 'Team' };
let nextId = 100;
let say: (message: LogText) => void = () => {};
// Empty required cells are marked visibly (it uses CSS variables, so it fits both light and dark themes).
const emptyMark = (ctx: CellContext<Row>): string | undefined =>
String(ctx.value ?? '').trim() === '' ? 'mxg-cell-invalid' : undefined;
export const options: GridOptions<Row> = {
columns: [
{
id: 'name',
title: 'Name *',
width: 140,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'email',
title: 'Email *',
width: 210,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
{
id: 'team',
title: 'Team *',
width: 110,
editable: true,
validation: { required: true },
cellClass: emptyMark,
},
],
rows,
rowKey: 'id',
saveMode: 'batch',
saveHandler: async () => {
await new Promise((resolve) => setTimeout(resolve, 300)); // Simulates the time it takes to send to a server.
},
};
// A required cell is only checked when it is edited. A cell that was empty from the start was never touched, so it is not checked.
// So before saving, scan every row and gather the empty cells by column (this is a check function written by the app).
function gaps(api: GridApi<Row>): { key: number; field: string }[] {
return api
.getRows()
.flatMap((row) =>
FIELDS.filter((f) => String(row[f]).trim() === '').map((field) => ({ key: row.id, field })),
);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const found = gaps(api);
log(
found.length
? `${found.length} empty cells. Use "Scan empty cells" to see where.`
: 'All required cells are filled.',
);
return api.on('validationFailed', (e) =>
log(`✗ Row ${e.rowKey} ${label[e.columnId] ?? e.columnId}: ${e.message}`),
);
}
export const actions = {
scan: (api: GridApi<Row>) => {
const found = gaps(api);
if (!found.length) return say('✓ No empty cells.');
const byField = FIELDS.map(
(f) => [f, found.filter((g) => g.field === f).map((g) => g.key)] as const,
).filter(([, keys]) => keys.length);
say(
`${found.length} empty cells → ${byField.map(([f, keys]) => `${label[f]}: rows ${keys.join(', ')}`).join(' / ')}`,
);
},
firstGap: (api: GridApi<Row>) => {
const first = gaps(api)[0];
if (!first) return say('✓ No empty cells.');
api.startEdit(first.key, first.field);
},
// save() checks every changed row first, and sends nothing if even one is wrong.
addEmpty: (api: GridApi<Row>) => {
nextId += 1;
api.addRows([{ id: nextId, name: '', email: '', team: '' }], 0);
say(`Put an empty new row (${nextId}) at the top. Now try saving.`);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(
report.status === 'invalid'
? 'Not saved because a value is not valid. See the ✗ lines below for the reason.'
: report.status === 'empty'
? 'No changes to save. (A cell that was empty from the start is not an edit, so it is not a change)'
: report.status === 'saved'
? `All saved. (${report.committed} rows)`
: `Check the save result. (${report.status})`,
);
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};