여러 페이지에서 고친 것을 한 번에 저장Save edits from several pages at once
일괄 저장 모드에서는 고친 값이 모아 두어서, 페이지를 넘겨도 사라지지 않아요. 저장 버튼을 한 번 누르면 모든 페이지에서 고친 행이 함께 서버로 가요.In batch save mode edits are collected, so changing page does not lose them. One save sends the rows edited on every page together.
코드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="editOnThisPage">이 페이지 첫 행 고치기</button>
<button type="button" id="nextPage">다음 페이지</button>
<button type="button" id="save">저장</button>
</div>
<div id="grid" style="height: 500px"></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('editOnThisPage').addEventListener('click', () => actions.editOnThisPage(api));
document.getElementById('nextPage').addEventListener('click', () => actions.nextPage(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));let say = () => { };
// 서버에 저장하는 척하는 핸들러예요. 결과 없이 끝나면 모든 행이 저장된 거예요.
const saveToServer = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 400));
say({
ko: `서버에 ${changes.length}행을 저장했어요`,
en: `Saved ${changes.length} rows to the server`,
});
};
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
export const options = {
columns: [
{ id: 'name', title: '이름', width: 150, editable: true, validation: { required: true } },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 130,
align: 'end',
editable: true,
},
],
rows: Array.from({ length: 40 }, (_, i) => ({
id: i + 1,
name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
salary: 320 + i * 5,
})),
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
pagination: { mode: 'client', pageSize: 10 },
};
// 다른 페이지에서 고친 값도 페이지를 넘겨도 사라지지 않고, 저장 한 번에 모두 서버로 가요.
export function setup(api, log) {
say = log;
return api.on('changesCountChanged', ({ count, modified, saving }) => {
log({
ko: `저장 대기 ${count}행 (수정 ${modified}) · ${api.getPage()}페이지${saving ? ' · 저장 중…' : ''}`,
en: `${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`,
});
});
}
export const actions = {
// 지금 페이지 첫 행의 월급을 10만원 올려요(직접 셀을 두 번 눌러 고쳐도 같아요).
editOnThisPage: (api) => {
const row = api.getVisibleRows()[0];
if (row)
api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
nextPage: (api) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
save: async (api) => {
const report = await api.save();
const words = {
saved: ['모두 저장됐어요', 'All saved'],
empty: ['저장할 변경이 없어요', 'No changes to save'],
};
const word = words[report.status] ?? [
'일부는 저장하지 못했어요',
'Some rows could not be saved',
];
say({ ko: `저장 결과: ${word[0]}`, en: `Save result: ${word[1]}` });
},
};<!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="editOnThisPage">이 페이지 첫 행 고치기</button>
<button type="button" id="nextPage">다음 페이지</button>
<button type="button" id="save">저장</button>
</div>
<div id="grid" style="height: 500px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
let say = () => { };
// 서버에 저장하는 척하는 핸들러예요. 결과 없이 끝나면 모든 행이 저장된 거예요.
const saveToServer = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 400));
say({
ko: `서버에 ${changes.length}행을 저장했어요`,
en: `Saved ${changes.length} rows to the server`,
});
};
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
const options = {
columns: [
{ id: 'name', title: '이름', width: 150, editable: true, validation: { required: true } },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 130,
align: 'end',
editable: true,
},
],
rows: Array.from({ length: 40 }, (_, i) => ({
id: i + 1,
name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
salary: 320 + i * 5,
})),
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
pagination: { mode: 'client', pageSize: 10 },
};
// 다른 페이지에서 고친 값도 페이지를 넘겨도 사라지지 않고, 저장 한 번에 모두 서버로 가요.
function setup(api, log) {
say = log;
return api.on('changesCountChanged', ({ count, modified, saving }) => {
log({
ko: `저장 대기 ${count}행 (수정 ${modified}) · ${api.getPage()}페이지${saving ? ' · 저장 중…' : ''}`,
en: `${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`,
});
});
}
const actions = {
// 지금 페이지 첫 행의 월급을 10만원 올려요(직접 셀을 두 번 눌러 고쳐도 같아요).
editOnThisPage: (api) => {
const row = api.getVisibleRows()[0];
if (row)
api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
nextPage: (api) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
save: async (api) => {
const report = await api.save();
const words = {
saved: ['모두 저장됐어요', 'All saved'],
empty: ['저장할 변경이 없어요', 'No changes to save'],
};
const word = words[report.status] ?? [
'일부는 저장하지 못했어요',
'Some rows could not be saved',
];
say({ ko: `저장 결과: ${word[0]}`, en: `Save result: ${word[1]}` });
},
};
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('editOnThisPage').addEventListener('click', () => actions.editOnThisPage(api));
document.getElementById('nextPage').addEventListener('click', () => actions.nextPage(api));
document.getElementById('save').addEventListener('click', () => actions.save(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.editOnThisPage(api)}
>이 페이지 첫 행 고치기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.nextPage(api)}
>다음 페이지</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>저장</button>
</div>
<Grid style={{ height: 500 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
salary: number;
}
let say: (message: LogText) => void = () => {};
// 서버에 저장하는 척하는 핸들러예요. 결과 없이 끝나면 모든 행이 저장된 거예요.
const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 400));
say({
ko: `서버에 ${changes.length}행을 저장했어요`,
en: `Saved ${changes.length} rows to the server`,
});
};
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 150, editable: true, validation: { required: true } },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 130,
align: 'end',
editable: true,
},
],
rows: Array.from({ length: 40 }, (_, i) => ({
id: i + 1,
name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
salary: 320 + i * 5,
})),
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
pagination: { mode: 'client', pageSize: 10 },
};
// 다른 페이지에서 고친 값도 페이지를 넘겨도 사라지지 않고, 저장 한 번에 모두 서버로 가요.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('changesCountChanged', ({ count, modified, saving }) => {
log({
ko: `저장 대기 ${count}행 (수정 ${modified}) · ${api.getPage()}페이지${saving ? ' · 저장 중…' : ''}`,
en: `${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`,
});
});
}
export const actions = {
// 지금 페이지 첫 행의 월급을 10만원 올려요(직접 셀을 두 번 눌러 고쳐도 같아요).
editOnThisPage: (api: GridApi<Row>) => {
const row = api.getVisibleRows()[0];
if (row) api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
nextPage: (api: GridApi<Row>) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
save: async (api: GridApi<Row>) => {
const report = await api.save();
const words: Record<string, [string, string]> = {
saved: ['모두 저장됐어요', 'All saved'],
empty: ['저장할 변경이 없어요', 'No changes to save'],
};
const word = words[report.status] ?? [
'일부는 저장하지 못했어요',
'Some rows could not be saved',
];
say({ ko: `저장 결과: ${word[0]}`, en: `Save result: ${word[1]}` });
},
};버튼을 누르면 이 예제의 코드가 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.editOnThisPage(api)"
>이 페이지 첫 행 고치기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.nextPage(api)"
>다음 페이지</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">저장</button>
</div>
<Grid style="height: 500px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
salary: number;
}
let say: (message: LogText) => void = () => {};
// 서버에 저장하는 척하는 핸들러예요. 결과 없이 끝나면 모든 행이 저장된 거예요.
const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 400));
say({
ko: `서버에 ${changes.length}행을 저장했어요`,
en: `Saved ${changes.length} rows to the server`,
});
};
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 150, editable: true, validation: { required: true } },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 130,
align: 'end',
editable: true,
},
],
rows: Array.from({ length: 40 }, (_, i) => ({
id: i + 1,
name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
salary: 320 + i * 5,
})),
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
pagination: { mode: 'client', pageSize: 10 },
};
// 다른 페이지에서 고친 값도 페이지를 넘겨도 사라지지 않고, 저장 한 번에 모두 서버로 가요.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('changesCountChanged', ({ count, modified, saving }) => {
log({
ko: `저장 대기 ${count}행 (수정 ${modified}) · ${api.getPage()}페이지${saving ? ' · 저장 중…' : ''}`,
en: `${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`,
});
});
}
export const actions = {
// 지금 페이지 첫 행의 월급을 10만원 올려요(직접 셀을 두 번 눌러 고쳐도 같아요).
editOnThisPage: (api: GridApi<Row>) => {
const row = api.getVisibleRows()[0];
if (row) api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
nextPage: (api: GridApi<Row>) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
save: async (api: GridApi<Row>) => {
const report = await api.save();
const words: Record<string, [string, string]> = {
saved: ['모두 저장됐어요', 'All saved'],
empty: ['저장할 변경이 없어요', 'No changes to save'],
};
const word = words[report.status] ?? [
'일부는 저장하지 못했어요',
'Some rows could not be saved',
];
say({ ko: `저장 결과: ${word[0]}`, en: `Save result: ${word[1]}` });
},
};버튼을 누르면 이 예제의 코드가 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.editOnThisPage(api)"
>이 페이지 첫 행 고치기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.nextPage(api)"
>다음 페이지</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>저장</button>
</div>
<mx-grid style="height: 500px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
salary: number;
}
let say: (message: LogText) => void = () => {};
// 서버에 저장하는 척하는 핸들러예요. 결과 없이 끝나면 모든 행이 저장된 거예요.
const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 400));
say({
ko: `서버에 ${changes.length}행을 저장했어요`,
en: `Saved ${changes.length} rows to the server`,
});
};
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 150, editable: true, validation: { required: true } },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 130,
align: 'end',
editable: true,
},
],
rows: Array.from({ length: 40 }, (_, i) => ({
id: i + 1,
name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
salary: 320 + i * 5,
})),
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
pagination: { mode: 'client', pageSize: 10 },
};
// 다른 페이지에서 고친 값도 페이지를 넘겨도 사라지지 않고, 저장 한 번에 모두 서버로 가요.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('changesCountChanged', ({ count, modified, saving }) => {
log({
ko: `저장 대기 ${count}행 (수정 ${modified}) · ${api.getPage()}페이지${saving ? ' · 저장 중…' : ''}`,
en: `${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`,
});
});
}
export const actions = {
// 지금 페이지 첫 행의 월급을 10만원 올려요(직접 셀을 두 번 눌러 고쳐도 같아요).
editOnThisPage: (api: GridApi<Row>) => {
const row = api.getVisibleRows()[0];
if (row) api.updateRows([{ ...row, salary: row.salary + 10 }]);
},
nextPage: (api: GridApi<Row>) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
save: async (api: GridApi<Row>) => {
const report = await api.save();
const words: Record<string, [string, string]> = {
saved: ['모두 저장됐어요', 'All saved'],
empty: ['저장할 변경이 없어요', 'No changes to save'],
};
const word = words[report.status] ?? [
'일부는 저장하지 못했어요',
'Some rows could not be saved',
];
say({ ko: `저장 결과: ${word[0]}`, en: `Save result: ${word[1]}` });
},
};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="editOnThisPage">Edit first row on this page</button>
<button type="button" id="nextPage">Next page</button>
<button type="button" id="save">Save</button>
</div>
<div id="grid" style="height: 500px"></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('editOnThisPage').addEventListener('click', () => actions.editOnThisPage(api));
document.getElementById('nextPage').addEventListener('click', () => actions.nextPage(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));let say = () => { };
// A handler that pretends to save to a server. If it finishes without a result, every row counts as saved.
const saveToServer = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 400));
say(`Saved ${changes.length} rows to the server`);
};
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brown',
'Mia Johnson',
'Jack Miller',
'Ava Davis',
];
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 170, editable: true, validation: { required: true } },
{
id: 'salary',
title: 'Monthly pay ($)',
kind: 'number',
width: 180,
align: 'end',
editable: true,
},
],
rows: Array.from({ length: 40 }, (_, i) => ({
id: i + 1,
name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
salary: 3200 + i * 50,
})),
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
pagination: { mode: 'client', pageSize: 10 },
};
// Values edited on other pages do not disappear when you change pages, and one save sends them all to the server.
export function setup(api, log) {
say = log;
return api.on('changesCountChanged', ({ count, modified, saving }) => {
log(`${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`);
});
}
export const actions = {
// Raise the pay of the first row on this page by 100 (editing the cell by hand gives the same result).
editOnThisPage: (api) => {
const row = api.getVisibleRows()[0];
if (row)
api.updateRows([{ ...row, salary: row.salary + 100 }]);
},
nextPage: (api) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
save: async (api) => {
const report = await api.save();
const words = {
saved: 'All saved',
empty: 'No changes to save',
};
const word = words[report.status] ?? 'Some rows could not be saved';
say(`Save result: ${word}`);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Save edits from several pages at once</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="editOnThisPage">Edit first row on this page</button>
<button type="button" id="nextPage">Next page</button>
<button type="button" id="save">Save</button>
</div>
<div id="grid" style="height: 500px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
let say = () => { };
// A handler that pretends to save to a server. If it finishes without a result, every row counts as saved.
const saveToServer = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 400));
say(`Saved ${changes.length} rows to the server`);
};
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brown',
'Mia Johnson',
'Jack Miller',
'Ava Davis',
];
const options = {
columns: [
{ id: 'name', title: 'Name', width: 170, editable: true, validation: { required: true } },
{
id: 'salary',
title: 'Monthly pay ($)',
kind: 'number',
width: 180,
align: 'end',
editable: true,
},
],
rows: Array.from({ length: 40 }, (_, i) => ({
id: i + 1,
name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
salary: 3200 + i * 50,
})),
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
pagination: { mode: 'client', pageSize: 10 },
};
// Values edited on other pages do not disappear when you change pages, and one save sends them all to the server.
function setup(api, log) {
say = log;
return api.on('changesCountChanged', ({ count, modified, saving }) => {
log(`${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`);
});
}
const actions = {
// Raise the pay of the first row on this page by 100 (editing the cell by hand gives the same result).
editOnThisPage: (api) => {
const row = api.getVisibleRows()[0];
if (row)
api.updateRows([{ ...row, salary: row.salary + 100 }]);
},
nextPage: (api) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
save: async (api) => {
const report = await api.save();
const words = {
saved: 'All saved',
empty: 'No changes to save',
};
const word = words[report.status] ?? 'Some rows could not be saved';
say(`Save result: ${word}`);
},
};
options.ariaLabel = "Save edits from several pages at once";
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('editOnThisPage').addEventListener('click', () => actions.editOnThisPage(api));
document.getElementById('nextPage').addEventListener('click', () => actions.nextPage(api));
document.getElementById('save').addEventListener('click', () => actions.save(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.editOnThisPage(api)}
>Edit first row on this page</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.nextPage(api)}
>Next page</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>Save</button>
</div>
<Grid style={{ height: 500 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
salary: number;
}
let say: (message: LogText) => void = () => {};
// A handler that pretends to save to a server. If it finishes without a result, every row counts as saved.
const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 400));
say(`Saved ${changes.length} rows to the server`);
};
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brown',
'Mia Johnson',
'Jack Miller',
'Ava Davis',
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 170, editable: true, validation: { required: true } },
{
id: 'salary',
title: 'Monthly pay ($)',
kind: 'number',
width: 180,
align: 'end',
editable: true,
},
],
rows: Array.from({ length: 40 }, (_, i) => ({
id: i + 1,
name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
salary: 3200 + i * 50,
})),
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
pagination: { mode: 'client', pageSize: 10 },
};
// Values edited on other pages do not disappear when you change pages, and one save sends them all to the server.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('changesCountChanged', ({ count, modified, saving }) => {
log(
`${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`,
);
});
}
export const actions = {
// Raise the pay of the first row on this page by 100 (editing the cell by hand gives the same result).
editOnThisPage: (api: GridApi<Row>) => {
const row = api.getVisibleRows()[0];
if (row) api.updateRows([{ ...row, salary: row.salary + 100 }]);
},
nextPage: (api: GridApi<Row>) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
save: async (api: GridApi<Row>) => {
const report = await api.save();
const words: Record<string, string> = {
saved: 'All saved',
empty: 'No changes to save',
};
const word = words[report.status] ?? 'Some rows could not be saved';
say(`Save result: ${word}`);
},
};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.editOnThisPage(api)"
>Edit first row on this page</button>
<button
type="button"
:disabled="!api"
@click="api && actions.nextPage(api)"
>Next page</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">Save</button>
</div>
<Grid style="height: 500px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
salary: number;
}
let say: (message: LogText) => void = () => {};
// A handler that pretends to save to a server. If it finishes without a result, every row counts as saved.
const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 400));
say(`Saved ${changes.length} rows to the server`);
};
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brown',
'Mia Johnson',
'Jack Miller',
'Ava Davis',
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 170, editable: true, validation: { required: true } },
{
id: 'salary',
title: 'Monthly pay ($)',
kind: 'number',
width: 180,
align: 'end',
editable: true,
},
],
rows: Array.from({ length: 40 }, (_, i) => ({
id: i + 1,
name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
salary: 3200 + i * 50,
})),
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
pagination: { mode: 'client', pageSize: 10 },
};
// Values edited on other pages do not disappear when you change pages, and one save sends them all to the server.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('changesCountChanged', ({ count, modified, saving }) => {
log(
`${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`,
);
});
}
export const actions = {
// Raise the pay of the first row on this page by 100 (editing the cell by hand gives the same result).
editOnThisPage: (api: GridApi<Row>) => {
const row = api.getVisibleRows()[0];
if (row) api.updateRows([{ ...row, salary: row.salary + 100 }]);
},
nextPage: (api: GridApi<Row>) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
save: async (api: GridApi<Row>) => {
const report = await api.save();
const words: Record<string, string> = {
saved: 'All saved',
empty: 'No changes to save',
};
const word = words[report.status] ?? 'Some rows could not be saved';
say(`Save result: ${word}`);
},
};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.editOnThisPage(api)"
>Edit first row on this page</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.nextPage(api)"
>Next page</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>Save</button>
</div>
<mx-grid style="height: 500px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions, SaveHandler } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
salary: number;
}
let say: (message: LogText) => void = () => {};
// A handler that pretends to save to a server. If it finishes without a result, every row counts as saved.
const saveToServer: SaveHandler<Row> = async (changes) => {
await new Promise((resolve) => setTimeout(resolve, 400));
say(`Saved ${changes.length} rows to the server`);
};
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brown',
'Mia Johnson',
'Jack Miller',
'Ava Davis',
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 170, editable: true, validation: { required: true } },
{
id: 'salary',
title: 'Monthly pay ($)',
kind: 'number',
width: 180,
align: 'end',
editable: true,
},
],
rows: Array.from({ length: 40 }, (_, i) => ({
id: i + 1,
name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
salary: 3200 + i * 50,
})),
rowKey: 'id',
saveMode: 'batch',
saveHandler: saveToServer,
pagination: { mode: 'client', pageSize: 10 },
};
// Values edited on other pages do not disappear when you change pages, and one save sends them all to the server.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
return api.on('changesCountChanged', ({ count, modified, saving }) => {
log(
`${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`,
);
});
}
export const actions = {
// Raise the pay of the first row on this page by 100 (editing the cell by hand gives the same result).
editOnThisPage: (api: GridApi<Row>) => {
const row = api.getVisibleRows()[0];
if (row) api.updateRows([{ ...row, salary: row.salary + 100 }]);
},
nextPage: (api: GridApi<Row>) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
save: async (api: GridApi<Row>) => {
const report = await api.save();
const words: Record<string, string> = {
saved: 'All saved',
empty: 'No changes to save',
};
const word = words[report.status] ?? 'Some rows could not be saved';
say(`Save result: ${word}`);
},
};