고친 행 수와 저장 버튼 한 줄로 보여 주기A save bar with pending count and a save button
표에서 고친 행이 몇 개인지, 저장하는 중인지를 한 줄로 보여 주고 저장·되돌리기 버튼을 붙여요. 고친 내용 추적과 저장은 표가 하고, 프레임워크 쪽 도우미는 그 값을 화면 상태로 모아 주기만 해요. React, Vue, Angular 탭에는 각 프레임워크의 방식으로 쓴 같은 예제가 들어 있어요.A bar shows how many rows were edited and whether a save is running, with Save and Discard buttons. The grid does the tracking and saving; the framework helper only gathers those values into screen state. The React, Vue and Angular tabs hold the same example written the way each framework does it.
실행 화면은 JavaScript 버전이에요. 아래 탭의 React·Vue·Angular 코드는 같은 예제를 각 프레임워크로 직접 쓴 코드예요.The preview runs the JavaScript version. The React, Vue, Angular tabs below hold the same example written for each framework.
코드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="raise">둘째 행 월급 10 올리기</button>
<button type="button" id="makeBad">첫 행 월급을 -1로</button>
<button type="button" id="save">저장</button>
<button type="button" id="discard">되돌리기</button>
</div>
<div id="grid" style="height: 440px"></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('raise').addEventListener('click', () => actions.raise(api));
document.getElementById('makeBad').addEventListener('click', () => actions.makeBad(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
/** 서버에 저장하는 척하는 함수예요. 0.5초 뒤에 끝나고, 월급이 0보다 작은 행은 거절해요. */
export const saveToServer = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 500));
const failed = changes
.filter((c) => c.state !== 'removed' && c.row.salary < 0)
.map((c) => ({
key: c.key,
message: L('월급은 0보다 작을 수 없어요', 'Pay cannot be less than 0'),
}));
return { failed };
};
export const options = {
columns: [
{ id: 'name', title: '이름', width: 130, editable: true, validation: { required: true } },
{ id: 'dept', title: '부서', width: 120, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows: [
{ id: 1, name: '김민준', dept: '개발팀', salary: 520 },
{ id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
{ id: 3, name: '박지호', dept: '영업팀', salary: 450 },
],
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
/** 저장 결과를 한글로 풀어 주는 말이에요. */
const SAVE_WORDS_EN = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
invalid: 'Not saved because a value needs fixing',
empty: 'No changes to save',
};
export const SAVE_WORDS = {
saved: '모두 저장됐어요',
partial: '일부만 저장됐어요',
failed: '저장하지 못했어요',
invalid: '고칠 값이 있어서 저장하지 않았어요',
empty: '저장할 변경이 없어요',
};
// 이 화면(JavaScript 버전): 고친 개수와 저장 중 표시를 표 위 한 줄로 보여 줘요.
let line = null;
let say = () => { };
export function setup(api, log) {
say = log;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = L('저장할 변경이 없어요', 'No changes to save');
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
// 고친 행이 없거나 저장하는 중이면 저장·되돌리기 버튼을 잠가요. (React·Vue·Angular 탭의 버튼과 같은 규칙이에요)
const lock = (count, saving) => {
for (const id of ['save', 'discard']) {
const button = document.getElementById(id);
if (button instanceof HTMLButtonElement)
button.disabled = count === 0 || saving;
}
if (line)
line.textContent = saving
? L('저장하는 중…', 'Saving…')
: count > 0
? L(`저장할 변경 ${count}행`, `${count} rows to save`)
: L('저장할 변경이 없어요', 'No changes to save');
};
lock(0, false);
const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
return () => {
off();
line?.remove();
line = null;
};
}
export const actions = {
// 첫 행의 월급을 -1로 만들어서, 서버가 거절하는 경우를 볼 수 있어요.
makeBad: (api) => {
const row = api.getRows()[0];
if (row)
api.updateRows([{ ...row, salary: -1 }]);
say({
ko: '첫 행의 월급을 -1로 바꿨어요 (저장하면 서버가 거절해요)',
en: 'Changed the pay of the first row to -1 (the server rejects it on save)',
});
},
raise: (api) => {
const row = api.getRows()[1];
if (row)
api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
save: async (api) => {
const report = await api.save();
say({
ko: `저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`,
en: `Save result: ${SAVE_WORDS_EN[report.status] ?? 'Needs checking'}`,
});
},
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="raise">둘째 행 월급 10 올리기</button>
<button type="button" id="makeBad">첫 행 월급을 -1로</button>
<button type="button" id="save">저장</button>
<button type="button" id="discard">되돌리기</button>
</div>
<div id="grid" style="height: 440px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
/** 서버에 저장하는 척하는 함수예요. 0.5초 뒤에 끝나고, 월급이 0보다 작은 행은 거절해요. */
const saveToServer = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 500));
const failed = changes
.filter((c) => c.state !== 'removed' && c.row.salary < 0)
.map((c) => ({
key: c.key,
message: L('월급은 0보다 작을 수 없어요', 'Pay cannot be less than 0'),
}));
return { failed };
};
const options = {
columns: [
{ id: 'name', title: '이름', width: 130, editable: true, validation: { required: true } },
{ id: 'dept', title: '부서', width: 120, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows: [
{ id: 1, name: '김민준', dept: '개발팀', salary: 520 },
{ id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
{ id: 3, name: '박지호', dept: '영업팀', salary: 450 },
],
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
/** 저장 결과를 한글로 풀어 주는 말이에요. */
const SAVE_WORDS_EN = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
invalid: 'Not saved because a value needs fixing',
empty: 'No changes to save',
};
const SAVE_WORDS = {
saved: '모두 저장됐어요',
partial: '일부만 저장됐어요',
failed: '저장하지 못했어요',
invalid: '고칠 값이 있어서 저장하지 않았어요',
empty: '저장할 변경이 없어요',
};
// 이 화면(JavaScript 버전): 고친 개수와 저장 중 표시를 표 위 한 줄로 보여 줘요.
let line = null;
let say = () => { };
function setup(api, log) {
say = log;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = L('저장할 변경이 없어요', 'No changes to save');
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
// 고친 행이 없거나 저장하는 중이면 저장·되돌리기 버튼을 잠가요. (React·Vue·Angular 탭의 버튼과 같은 규칙이에요)
const lock = (count, saving) => {
for (const id of ['save', 'discard']) {
const button = document.getElementById(id);
if (button instanceof HTMLButtonElement)
button.disabled = count === 0 || saving;
}
if (line)
line.textContent = saving
? L('저장하는 중…', 'Saving…')
: count > 0
? L(`저장할 변경 ${count}행`, `${count} rows to save`)
: L('저장할 변경이 없어요', 'No changes to save');
};
lock(0, false);
const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
return () => {
off();
line?.remove();
line = null;
};
}
const actions = {
// 첫 행의 월급을 -1로 만들어서, 서버가 거절하는 경우를 볼 수 있어요.
makeBad: (api) => {
const row = api.getRows()[0];
if (row)
api.updateRows([{ ...row, salary: -1 }]);
say({
ko: '첫 행의 월급을 -1로 바꿨어요 (저장하면 서버가 거절해요)',
en: 'Changed the pay of the first row to -1 (the server rejects it on save)',
});
},
raise: (api) => {
const row = api.getRows()[1];
if (row)
api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
save: async (api) => {
const report = await api.save();
say({
ko: `저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`,
en: `Save result: ${SAVE_WORDS_EN[report.status] ?? 'Needs checking'}`,
});
},
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('raise').addEventListener('click', () => actions.raise(api));
document.getElementById('makeBad').addEventListener('click', () => actions.makeBad(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Grid, useGridApi, useGridChanges } from '@maxgrid/react';
import { useState } from 'react';
import { SAVE_WORDS, options, type Row } from './example';
// useGridChanges가 고친 행 수와 저장 중 여부를 React 상태처럼 돌려줘요.
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
const { count, saving } = useGridChanges(api);
const [message, setMessage] = useState('');
const save = async () => {
const report = await api?.save();
if (report) setMessage(`저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`);
};
return (
<>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
<span>
{saving ? '저장하는 중…' : count > 0 ? `저장할 변경 ${count}행` : '저장할 변경이 없어요'}
</span>
<button type="button" disabled={!api || count === 0 || saving} onClick={save}>
저장
</button>
<button
type="button"
disabled={count === 0 || saving}
onClick={() => api?.rollbackChanges()}
>
되돌리기
</button>
</div>
<div style={{ height: 200 }}>
<Grid<Row> ref={gridRef} options={options} />
</div>
<p>{message}</p>
</>
);
}import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
/** 서버에 저장하는 척하는 함수예요. 0.5초 뒤에 끝나고, 월급이 0보다 작은 행은 거절해요. */
export const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 500));
const failed = changes
.filter((c) => c.state !== 'removed' && c.row.salary < 0)
.map((c) => ({
key: c.key,
message: L('월급은 0보다 작을 수 없어요', 'Pay cannot be less than 0'),
}));
return { failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130, editable: true, validation: { required: true } },
{ id: 'dept', title: '부서', width: 120, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows: [
{ id: 1, name: '김민준', dept: '개발팀', salary: 520 },
{ id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
{ id: 3, name: '박지호', dept: '영업팀', salary: 450 },
],
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
/** 저장 결과를 한글로 풀어 주는 말이에요. */
const SAVE_WORDS_EN: Record<string, string> = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
invalid: 'Not saved because a value needs fixing',
empty: 'No changes to save',
};
export const SAVE_WORDS: Record<string, string> = {
saved: '모두 저장됐어요',
partial: '일부만 저장됐어요',
failed: '저장하지 못했어요',
invalid: '고칠 값이 있어서 저장하지 않았어요',
empty: '저장할 변경이 없어요',
};
// 이 화면(JavaScript 버전): 고친 개수와 저장 중 표시를 표 위 한 줄로 보여 줘요.
let line: HTMLElement | null = null;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = L('저장할 변경이 없어요', 'No changes to save');
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
// 고친 행이 없거나 저장하는 중이면 저장·되돌리기 버튼을 잠가요. (React·Vue·Angular 탭의 버튼과 같은 규칙이에요)
const lock = (count: number, saving: boolean): void => {
for (const id of ['save', 'discard']) {
const button = document.getElementById(id);
if (button instanceof HTMLButtonElement) button.disabled = count === 0 || saving;
}
if (line)
line.textContent = saving
? L('저장하는 중…', 'Saving…')
: count > 0
? L(`저장할 변경 ${count}행`, `${count} rows to save`)
: L('저장할 변경이 없어요', 'No changes to save');
};
lock(0, false);
const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
return () => {
off();
line?.remove();
line = null;
};
}
export const actions = {
// 첫 행의 월급을 -1로 만들어서, 서버가 거절하는 경우를 볼 수 있어요.
makeBad: (api: GridApi<Row>) => {
const row = api.getRows()[0];
if (row) api.updateRows([{ ...row, salary: -1 }]);
say({
ko: '첫 행의 월급을 -1로 바꿨어요 (저장하면 서버가 거절해요)',
en: 'Changed the pay of the first row to -1 (the server rejects it on save)',
});
},
raise: (api: GridApi<Row>) => {
const row = api.getRows()[1];
if (row) api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({
ko: `저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`,
en: `Save result: ${SAVE_WORDS_EN[report.status] ?? 'Needs checking'}`,
});
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { Grid, useChangeStatus, type GridInstance } from '@maxgrid/vue';
import { ref } from 'vue';
import { SAVE_WORDS, options, type Row } from './example';
// useChangeStatus가 고친 행 수와 저장 중 여부를 ref로 모아 줘요. listeners를 표에 이으면 값이 채워져요.
const grid = ref<GridInstance<Row> | null>(null);
const { count, saving, listeners } = useChangeStatus();
const message = ref('');
async function save() {
const report = await grid.value?.getApi()?.save();
if (report) message.value = `저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`;
}
</script>
<template>
<div class="bar">
<span>{{
saving ? '저장하는 중…' : count > 0 ? `저장할 변경 ${count}행` : '저장할 변경이 없어요'
}}</span>
<button type="button" :disabled="count === 0 || saving" @click="save">저장</button>
<button
type="button"
:disabled="count === 0 || saving"
@click="grid?.getApi()?.rollbackChanges()"
>
되돌리기
</button>
</div>
<Grid ref="grid" style="height: 200px" :options="options" v-bind="listeners" />
<p>{{ message }}</p>
</template>
<style scoped>
.bar {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
</style>import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
/** 서버에 저장하는 척하는 함수예요. 0.5초 뒤에 끝나고, 월급이 0보다 작은 행은 거절해요. */
export const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 500));
const failed = changes
.filter((c) => c.state !== 'removed' && c.row.salary < 0)
.map((c) => ({
key: c.key,
message: L('월급은 0보다 작을 수 없어요', 'Pay cannot be less than 0'),
}));
return { failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130, editable: true, validation: { required: true } },
{ id: 'dept', title: '부서', width: 120, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows: [
{ id: 1, name: '김민준', dept: '개발팀', salary: 520 },
{ id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
{ id: 3, name: '박지호', dept: '영업팀', salary: 450 },
],
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
/** 저장 결과를 한글로 풀어 주는 말이에요. */
const SAVE_WORDS_EN: Record<string, string> = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
invalid: 'Not saved because a value needs fixing',
empty: 'No changes to save',
};
export const SAVE_WORDS: Record<string, string> = {
saved: '모두 저장됐어요',
partial: '일부만 저장됐어요',
failed: '저장하지 못했어요',
invalid: '고칠 값이 있어서 저장하지 않았어요',
empty: '저장할 변경이 없어요',
};
// 이 화면(JavaScript 버전): 고친 개수와 저장 중 표시를 표 위 한 줄로 보여 줘요.
let line: HTMLElement | null = null;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = L('저장할 변경이 없어요', 'No changes to save');
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
// 고친 행이 없거나 저장하는 중이면 저장·되돌리기 버튼을 잠가요. (React·Vue·Angular 탭의 버튼과 같은 규칙이에요)
const lock = (count: number, saving: boolean): void => {
for (const id of ['save', 'discard']) {
const button = document.getElementById(id);
if (button instanceof HTMLButtonElement) button.disabled = count === 0 || saving;
}
if (line)
line.textContent = saving
? L('저장하는 중…', 'Saving…')
: count > 0
? L(`저장할 변경 ${count}행`, `${count} rows to save`)
: L('저장할 변경이 없어요', 'No changes to save');
};
lock(0, false);
const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
return () => {
off();
line?.remove();
line = null;
};
}
export const actions = {
// 첫 행의 월급을 -1로 만들어서, 서버가 거절하는 경우를 볼 수 있어요.
makeBad: (api: GridApi<Row>) => {
const row = api.getRows()[0];
if (row) api.updateRows([{ ...row, salary: -1 }]);
say({
ko: '첫 행의 월급을 -1로 바꿨어요 (저장하면 서버가 거절해요)',
en: 'Changed the pay of the first row to -1 (the server rejects it on save)',
});
},
raise: (api: GridApi<Row>) => {
const row = api.getRows()[1];
if (row) api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({
ko: `저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`,
en: `Save result: ${SAVE_WORDS_EN[report.status] ?? 'Needs checking'}`,
});
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, ViewChild, signal } from '@angular/core';
import {
GridComponent,
createSaveState,
type GridEventMessage,
type GridEventName,
} from '@maxgrid/angular';
import { SAVE_WORDS, options, type Row } from './example';
// createSaveState가 고친 행 수와 저장 중 여부를 signal로 모아 줘요. (gridEvent)에 handle을 이어 주세요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px">
<span>
{{
tracker.state().saving
? '저장하는 중…'
: tracker.state().count > 0
? '저장할 변경 ' + tracker.state().count + '행'
: '저장할 변경이 없어요'
}}
</span>
<button
type="button"
[disabled]="tracker.state().count === 0 || tracker.state().saving"
(click)="save()"
>
저장
</button>
<button
type="button"
[disabled]="tracker.state().count === 0 || tracker.state().saving"
(click)="discard()"
>
되돌리기
</button>
</div>
<mx-grid
style="height: 200px"
[options]="options"
[events]="events"
(gridEvent)="onEvent($event)"
/>
<p>{{ message() }}</p>
`,
})
export class ExampleGridComponent {
readonly options = options;
readonly tracker = createSaveState();
readonly events: GridEventName[] = ['changesCountChanged', 'saveStarted', 'saveFailed'];
readonly message = signal('');
@ViewChild(GridComponent) private readonly gridRef?: GridComponent<Row>;
onEvent(message: GridEventMessage<Row>): void {
this.tracker.handle(message);
}
async save(): Promise<void> {
const report = await this.gridRef?.getApi()?.save();
if (report) this.message.set(`저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`);
}
discard(): void {
this.gridRef?.getApi()?.rollbackChanges();
}
}import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
/** 서버에 저장하는 척하는 함수예요. 0.5초 뒤에 끝나고, 월급이 0보다 작은 행은 거절해요. */
export const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 500));
const failed = changes
.filter((c) => c.state !== 'removed' && c.row.salary < 0)
.map((c) => ({
key: c.key,
message: L('월급은 0보다 작을 수 없어요', 'Pay cannot be less than 0'),
}));
return { failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130, editable: true, validation: { required: true } },
{ id: 'dept', title: '부서', width: 120, editable: true },
{ id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
],
rows: [
{ id: 1, name: '김민준', dept: '개발팀', salary: 520 },
{ id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
{ id: 3, name: '박지호', dept: '영업팀', salary: 450 },
],
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
/** 저장 결과를 한글로 풀어 주는 말이에요. */
const SAVE_WORDS_EN: Record<string, string> = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
invalid: 'Not saved because a value needs fixing',
empty: 'No changes to save',
};
export const SAVE_WORDS: Record<string, string> = {
saved: '모두 저장됐어요',
partial: '일부만 저장됐어요',
failed: '저장하지 못했어요',
invalid: '고칠 값이 있어서 저장하지 않았어요',
empty: '저장할 변경이 없어요',
};
// 이 화면(JavaScript 버전): 고친 개수와 저장 중 표시를 표 위 한 줄로 보여 줘요.
let line: HTMLElement | null = null;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = L('저장할 변경이 없어요', 'No changes to save');
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
// 고친 행이 없거나 저장하는 중이면 저장·되돌리기 버튼을 잠가요. (React·Vue·Angular 탭의 버튼과 같은 규칙이에요)
const lock = (count: number, saving: boolean): void => {
for (const id of ['save', 'discard']) {
const button = document.getElementById(id);
if (button instanceof HTMLButtonElement) button.disabled = count === 0 || saving;
}
if (line)
line.textContent = saving
? L('저장하는 중…', 'Saving…')
: count > 0
? L(`저장할 변경 ${count}행`, `${count} rows to save`)
: L('저장할 변경이 없어요', 'No changes to save');
};
lock(0, false);
const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
return () => {
off();
line?.remove();
line = null;
};
}
export const actions = {
// 첫 행의 월급을 -1로 만들어서, 서버가 거절하는 경우를 볼 수 있어요.
makeBad: (api: GridApi<Row>) => {
const row = api.getRows()[0];
if (row) api.updateRows([{ ...row, salary: -1 }]);
say({
ko: '첫 행의 월급을 -1로 바꿨어요 (저장하면 서버가 거절해요)',
en: 'Changed the pay of the first row to -1 (the server rejects it on save)',
});
},
raise: (api: GridApi<Row>) => {
const row = api.getRows()[1];
if (row) api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say({
ko: `저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`,
en: `Save result: ${SAVE_WORDS_EN[report.status] ?? 'Needs checking'}`,
});
},
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="raise">Raise the second salary by 10</button>
<button type="button" id="makeBad">Make the first salary -1</button>
<button type="button" id="save">Save</button>
<button type="button" id="discard">Discard</button>
</div>
<div id="grid" style="height: 440px"></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('raise').addEventListener('click', () => actions.raise(api));
document.getElementById('makeBad').addEventListener('click', () => actions.makeBad(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));/** Pretends to save to a server. It finishes after 0.5 seconds and rejects rows whose pay is below 0. */
export const saveToServer = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 500));
const failed = changes
.filter((c) => c.state !== 'removed' && c.row.salary < 0)
.map((c) => ({
key: c.key,
message: 'Pay cannot be less than 0',
}));
return { failed };
};
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 130, editable: true, validation: { required: true } },
{ id: 'dept', title: 'Department', width: 120, editable: true },
{
id: 'salary',
title: 'Monthly pay ($100)',
kind: 'number',
width: 150,
align: 'end',
editable: true,
},
],
rows: [
{ id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
{ id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
{ id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
],
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
/** Words that explain the save result. */
export const SAVE_WORDS = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
invalid: 'Not saved because a value needs fixing',
empty: 'No changes to save',
};
// This screen (JavaScript version): show the changed count and the saving state in one line above the table.
let line = null;
let say = () => { };
export function setup(api, log) {
say = log;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = 'No changes to save';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
// Lock the save and discard buttons when no row is changed or while saving. (Same rule as the buttons in the React, Vue and Angular tabs)
const lock = (count, saving) => {
for (const id of ['save', 'discard']) {
const button = document.getElementById(id);
if (button instanceof HTMLButtonElement)
button.disabled = count === 0 || saving;
}
if (line)
line.textContent = saving
? 'Saving…'
: count > 0
? `${count} rows to save`
: 'No changes to save';
};
lock(0, false);
const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
return () => {
off();
line?.remove();
line = null;
};
}
export const actions = {
// Make the first row's pay -1 so you can see the case where the server rejects it.
makeBad: (api) => {
const row = api.getRows()[0];
if (row)
api.updateRows([{ ...row, salary: -1 }]);
say('Changed the pay of the first row to -1 (the server rejects it on save)');
},
raise: (api) => {
const row = api.getRows()[1];
if (row)
api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
save: async (api) => {
const report = await api.save();
say(`Save result: ${SAVE_WORDS[report.status] ?? 'Needs checking'}`);
},
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>A save bar with pending count and a save button</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="raise">Raise the second salary by 10</button>
<button type="button" id="makeBad">Make the first salary -1</button>
<button type="button" id="save">Save</button>
<button type="button" id="discard">Discard</button>
</div>
<div id="grid" style="height: 440px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
/** Pretends to save to a server. It finishes after 0.5 seconds and rejects rows whose pay is below 0. */
const saveToServer = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 500));
const failed = changes
.filter((c) => c.state !== 'removed' && c.row.salary < 0)
.map((c) => ({
key: c.key,
message: 'Pay cannot be less than 0',
}));
return { failed };
};
const options = {
columns: [
{ id: 'name', title: 'Name', width: 130, editable: true, validation: { required: true } },
{ id: 'dept', title: 'Department', width: 120, editable: true },
{
id: 'salary',
title: 'Monthly pay ($100)',
kind: 'number',
width: 150,
align: 'end',
editable: true,
},
],
rows: [
{ id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
{ id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
{ id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
],
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
/** Words that explain the save result. */
const SAVE_WORDS = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
invalid: 'Not saved because a value needs fixing',
empty: 'No changes to save',
};
// This screen (JavaScript version): show the changed count and the saving state in one line above the table.
let line = null;
let say = () => { };
function setup(api, log) {
say = log;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = 'No changes to save';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
// Lock the save and discard buttons when no row is changed or while saving. (Same rule as the buttons in the React, Vue and Angular tabs)
const lock = (count, saving) => {
for (const id of ['save', 'discard']) {
const button = document.getElementById(id);
if (button instanceof HTMLButtonElement)
button.disabled = count === 0 || saving;
}
if (line)
line.textContent = saving
? 'Saving…'
: count > 0
? `${count} rows to save`
: 'No changes to save';
};
lock(0, false);
const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
return () => {
off();
line?.remove();
line = null;
};
}
const actions = {
// Make the first row's pay -1 so you can see the case where the server rejects it.
makeBad: (api) => {
const row = api.getRows()[0];
if (row)
api.updateRows([{ ...row, salary: -1 }]);
say('Changed the pay of the first row to -1 (the server rejects it on save)');
},
raise: (api) => {
const row = api.getRows()[1];
if (row)
api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
save: async (api) => {
const report = await api.save();
say(`Save result: ${SAVE_WORDS[report.status] ?? 'Needs checking'}`);
},
discard: (api) => api.rollbackChanges(),
};
options.ariaLabel = "A save bar with pending count and a save button";
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('raise').addEventListener('click', () => actions.raise(api));
document.getElementById('makeBad').addEventListener('click', () => actions.makeBad(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 { Grid, useGridApi, useGridChanges } from '@maxgrid/react';
import { useState } from 'react';
import { SAVE_WORDS, options, type Row } from './example';
// useGridChanges가 고친 행 수와 저장 중 여부를 React 상태처럼 돌려줘요.
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
const { count, saving } = useGridChanges(api);
const [message, setMessage] = useState('');
const save = async () => {
const report = await api?.save();
if (report) setMessage(`저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`);
};
return (
<>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
<span>
{saving ? '저장하는 중…' : count > 0 ? `저장할 변경 ${count}행` : '저장할 변경이 없어요'}
</span>
<button type="button" disabled={!api || count === 0 || saving} onClick={save}>
저장
</button>
<button
type="button"
disabled={count === 0 || saving}
onClick={() => api?.rollbackChanges()}
>
되돌리기
</button>
</div>
<div style={{ height: 200 }}>
<Grid<Row> ref={gridRef} options={options} />
</div>
<p>{message}</p>
</>
);
}import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
/** Pretends to save to a server. It finishes after 0.5 seconds and rejects rows whose pay is below 0. */
export const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 500));
const failed = changes
.filter((c) => c.state !== 'removed' && c.row.salary < 0)
.map((c) => ({
key: c.key,
message: 'Pay cannot be less than 0',
}));
return { failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130, editable: true, validation: { required: true } },
{ id: 'dept', title: 'Department', width: 120, editable: true },
{
id: 'salary',
title: 'Monthly pay ($100)',
kind: 'number',
width: 150,
align: 'end',
editable: true,
},
],
rows: [
{ id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
{ id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
{ id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
],
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
/** Words that explain the save result. */
export const SAVE_WORDS: Record<string, string> = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
invalid: 'Not saved because a value needs fixing',
empty: 'No changes to save',
};
// This screen (JavaScript version): show the changed count and the saving state in one line above the table.
let line: HTMLElement | null = null;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = 'No changes to save';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
// Lock the save and discard buttons when no row is changed or while saving. (Same rule as the buttons in the React, Vue and Angular tabs)
const lock = (count: number, saving: boolean): void => {
for (const id of ['save', 'discard']) {
const button = document.getElementById(id);
if (button instanceof HTMLButtonElement) button.disabled = count === 0 || saving;
}
if (line)
line.textContent = saving
? 'Saving…'
: count > 0
? `${count} rows to save`
: 'No changes to save';
};
lock(0, false);
const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
return () => {
off();
line?.remove();
line = null;
};
}
export const actions = {
// Make the first row's pay -1 so you can see the case where the server rejects it.
makeBad: (api: GridApi<Row>) => {
const row = api.getRows()[0];
if (row) api.updateRows([{ ...row, salary: -1 }]);
say('Changed the pay of the first row to -1 (the server rejects it on save)');
},
raise: (api: GridApi<Row>) => {
const row = api.getRows()[1];
if (row) api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(`Save result: ${SAVE_WORDS[report.status] ?? 'Needs checking'}`);
},
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 { Grid, useChangeStatus, type GridInstance } from '@maxgrid/vue';
import { ref } from 'vue';
import { SAVE_WORDS, options, type Row } from './example';
// useChangeStatus가 고친 행 수와 저장 중 여부를 ref로 모아 줘요. listeners를 표에 이으면 값이 채워져요.
const grid = ref<GridInstance<Row> | null>(null);
const { count, saving, listeners } = useChangeStatus();
const message = ref('');
async function save() {
const report = await grid.value?.getApi()?.save();
if (report) message.value = `저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`;
}
</script>
<template>
<div class="bar">
<span>{{
saving ? '저장하는 중…' : count > 0 ? `저장할 변경 ${count}행` : '저장할 변경이 없어요'
}}</span>
<button type="button" :disabled="count === 0 || saving" @click="save">저장</button>
<button
type="button"
:disabled="count === 0 || saving"
@click="grid?.getApi()?.rollbackChanges()"
>
되돌리기
</button>
</div>
<Grid ref="grid" style="height: 200px" :options="options" v-bind="listeners" />
<p>{{ message }}</p>
</template>
<style scoped>
.bar {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
</style>import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
/** Pretends to save to a server. It finishes after 0.5 seconds and rejects rows whose pay is below 0. */
export const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 500));
const failed = changes
.filter((c) => c.state !== 'removed' && c.row.salary < 0)
.map((c) => ({
key: c.key,
message: 'Pay cannot be less than 0',
}));
return { failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130, editable: true, validation: { required: true } },
{ id: 'dept', title: 'Department', width: 120, editable: true },
{
id: 'salary',
title: 'Monthly pay ($100)',
kind: 'number',
width: 150,
align: 'end',
editable: true,
},
],
rows: [
{ id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
{ id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
{ id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
],
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
/** Words that explain the save result. */
export const SAVE_WORDS: Record<string, string> = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
invalid: 'Not saved because a value needs fixing',
empty: 'No changes to save',
};
// This screen (JavaScript version): show the changed count and the saving state in one line above the table.
let line: HTMLElement | null = null;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = 'No changes to save';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
// Lock the save and discard buttons when no row is changed or while saving. (Same rule as the buttons in the React, Vue and Angular tabs)
const lock = (count: number, saving: boolean): void => {
for (const id of ['save', 'discard']) {
const button = document.getElementById(id);
if (button instanceof HTMLButtonElement) button.disabled = count === 0 || saving;
}
if (line)
line.textContent = saving
? 'Saving…'
: count > 0
? `${count} rows to save`
: 'No changes to save';
};
lock(0, false);
const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
return () => {
off();
line?.remove();
line = null;
};
}
export const actions = {
// Make the first row's pay -1 so you can see the case where the server rejects it.
makeBad: (api: GridApi<Row>) => {
const row = api.getRows()[0];
if (row) api.updateRows([{ ...row, salary: -1 }]);
say('Changed the pay of the first row to -1 (the server rejects it on save)');
},
raise: (api: GridApi<Row>) => {
const row = api.getRows()[1];
if (row) api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(`Save result: ${SAVE_WORDS[report.status] ?? 'Needs checking'}`);
},
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, ViewChild, signal } from '@angular/core';
import {
GridComponent,
createSaveState,
type GridEventMessage,
type GridEventName,
} from '@maxgrid/angular';
import { SAVE_WORDS, options, type Row } from './example';
// createSaveState가 고친 행 수와 저장 중 여부를 signal로 모아 줘요. (gridEvent)에 handle을 이어 주세요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px">
<span>
{{
tracker.state().saving
? '저장하는 중…'
: tracker.state().count > 0
? '저장할 변경 ' + tracker.state().count + '행'
: '저장할 변경이 없어요'
}}
</span>
<button
type="button"
[disabled]="tracker.state().count === 0 || tracker.state().saving"
(click)="save()"
>
저장
</button>
<button
type="button"
[disabled]="tracker.state().count === 0 || tracker.state().saving"
(click)="discard()"
>
되돌리기
</button>
</div>
<mx-grid
style="height: 200px"
[options]="options"
[events]="events"
(gridEvent)="onEvent($event)"
/>
<p>{{ message() }}</p>
`,
})
export class ExampleGridComponent {
readonly options = options;
readonly tracker = createSaveState();
readonly events: GridEventName[] = ['changesCountChanged', 'saveStarted', 'saveFailed'];
readonly message = signal('');
@ViewChild(GridComponent) private readonly gridRef?: GridComponent<Row>;
onEvent(message: GridEventMessage<Row>): void {
this.tracker.handle(message);
}
async save(): Promise<void> {
const report = await this.gridRef?.getApi()?.save();
if (report) this.message.set(`저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`);
}
discard(): void {
this.gridRef?.getApi()?.rollbackChanges();
}
}import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
/** Pretends to save to a server. It finishes after 0.5 seconds and rejects rows whose pay is below 0. */
export const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 500));
const failed = changes
.filter((c) => c.state !== 'removed' && c.row.salary < 0)
.map((c) => ({
key: c.key,
message: 'Pay cannot be less than 0',
}));
return { failed };
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130, editable: true, validation: { required: true } },
{ id: 'dept', title: 'Department', width: 120, editable: true },
{
id: 'salary',
title: 'Monthly pay ($100)',
kind: 'number',
width: 150,
align: 'end',
editable: true,
},
],
rows: [
{ id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
{ id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
{ id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
],
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
};
/** Words that explain the save result. */
export const SAVE_WORDS: Record<string, string> = {
saved: 'All saved',
partial: 'Partly saved',
failed: 'Could not save',
invalid: 'Not saved because a value needs fixing',
empty: 'No changes to save',
};
// This screen (JavaScript version): show the changed count and the saving state in one line above the table.
let line: HTMLElement | null = null;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = 'No changes to save';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
// Lock the save and discard buttons when no row is changed or while saving. (Same rule as the buttons in the React, Vue and Angular tabs)
const lock = (count: number, saving: boolean): void => {
for (const id of ['save', 'discard']) {
const button = document.getElementById(id);
if (button instanceof HTMLButtonElement) button.disabled = count === 0 || saving;
}
if (line)
line.textContent = saving
? 'Saving…'
: count > 0
? `${count} rows to save`
: 'No changes to save';
};
lock(0, false);
const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
return () => {
off();
line?.remove();
line = null;
};
}
export const actions = {
// Make the first row's pay -1 so you can see the case where the server rejects it.
makeBad: (api: GridApi<Row>) => {
const row = api.getRows()[0];
if (row) api.updateRows([{ ...row, salary: -1 }]);
say('Changed the pay of the first row to -1 (the server rejects it on save)');
},
raise: (api: GridApi<Row>) => {
const row = api.getRows()[1];
if (row) api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
save: async (api: GridApi<Row>) => {
const report = await api.save();
say(`Save result: ${SAVE_WORDS[report.status] ?? 'Needs checking'}`);
},
discard: (api: GridApi<Row>) => api.rollbackChanges(),
};