저장 전에는 정렬·쪽 이동 막기Block sorting and paging before saving
hooks.beforeSort, beforeFilter, beforePageChange가 false를 돌려주면 그 조작은 취소돼요. 이 예제는 저장하지 않은 고침(hasChanges)이 있는 동안 정렬·필터·쪽 이동을 막아 고친 줄이 사라지거나 흩어지지 않게 해요. 훅의 source로 화면 조작과 코드 호출을 구분해요.When hooks.beforeSort, beforeFilter or beforePageChange returns false, that action is cancelled. This example blocks sorting, filtering and page changes while there are unsaved edits (hasChanges) so edited rows do not scatter. The hook source tells a gesture from a code call.
코드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="sort">코드로 정렬하기</button>
<button type="button" id="next">다음 쪽(코드)</button>
<button type="button" id="save">저장하기</button>
</div>
<div id="grid" style="height: 230px"></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('sort').addEventListener('click', () => actions.sort(api));
document.getElementById('next').addEventListener('click', () => actions.next(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));const en = document.documentElement.dataset.lang === 'en';
const names = en
? ['Alex', 'Blair', 'Casey', 'Drew', 'Emery', 'Finn', 'Gray', 'Harper', 'Indy', 'Jordan']
: [
'김서연',
'이준호',
'박민지',
'최도윤',
'정하은',
'한지우',
'오세훈',
'윤아름',
'강태양',
'서하늘',
];
const teams = en ? ['Dev', 'Design', 'Ops'] : ['개발', '디자인', '운영'];
let say = () => { };
let apiRef = null;
/** 저장하지 않은 고침이 있으면 막고 이유를 기록해요. 막힌 조작은 이벤트도 상태 변화도 없어요. */
const guard = (what) => (ctx) => {
if (apiRef?.hasChanges() !== true)
return;
say({
ko: `저장하지 않은 고침이 있어 ${what.ko}을(를) 막았어요 (${ctx.source === 'user' ? '화면 조작' : '코드 호출'})`,
en: `Blocked the ${what.en}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`,
});
return false;
};
export const options = {
columns: [
{ id: 'name', title: en ? 'Name' : '이름', width: 120, editable: true, sortable: true },
{ id: 'team', title: en ? 'Team' : '팀', width: 100, sortable: true },
{
id: 'score',
title: en ? 'Score' : '점수',
kind: 'number',
width: 90,
editable: true,
sortable: true,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
team: teams[i % 3],
score: 60 + ((i * 7) % 40),
})),
rowKey: 'id',
saveMode: 'batch',
pagination: { mode: 'client', pageSize: 5 },
hooks: {
beforeSort: guard({ ko: '정렬', en: 'sort' }),
beforeFilter: guard({ ko: '필터', en: 'filter' }),
beforePageChange: guard({ ko: '쪽 이동', en: 'page change' }),
},
};
export function setup(api, log) {
say = log;
apiRef = api;
return () => {
apiRef = null;
};
}
export const actions = {
save: (api) => {
api.commitChanges();
say({
ko: '저장했어요. 이제 정렬·쪽 이동이 풀려요.',
en: 'Saved. Sorting and paging work again.',
});
},
sort: (api) => {
api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
},
next: (api) => api.setPage(api.getPage() + 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="sort">코드로 정렬하기</button>
<button type="button" id="next">다음 쪽(코드)</button>
<button type="button" id="save">저장하기</button>
</div>
<div id="grid" style="height: 230px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const en = document.documentElement.dataset.lang === 'en';
const names = en
? ['Alex', 'Blair', 'Casey', 'Drew', 'Emery', 'Finn', 'Gray', 'Harper', 'Indy', 'Jordan']
: [
'김서연',
'이준호',
'박민지',
'최도윤',
'정하은',
'한지우',
'오세훈',
'윤아름',
'강태양',
'서하늘',
];
const teams = en ? ['Dev', 'Design', 'Ops'] : ['개발', '디자인', '운영'];
let say = () => { };
let apiRef = null;
/** 저장하지 않은 고침이 있으면 막고 이유를 기록해요. 막힌 조작은 이벤트도 상태 변화도 없어요. */
const guard = (what) => (ctx) => {
if (apiRef?.hasChanges() !== true)
return;
say({
ko: `저장하지 않은 고침이 있어 ${what.ko}을(를) 막았어요 (${ctx.source === 'user' ? '화면 조작' : '코드 호출'})`,
en: `Blocked the ${what.en}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`,
});
return false;
};
const options = {
columns: [
{ id: 'name', title: en ? 'Name' : '이름', width: 120, editable: true, sortable: true },
{ id: 'team', title: en ? 'Team' : '팀', width: 100, sortable: true },
{
id: 'score',
title: en ? 'Score' : '점수',
kind: 'number',
width: 90,
editable: true,
sortable: true,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
team: teams[i % 3],
score: 60 + ((i * 7) % 40),
})),
rowKey: 'id',
saveMode: 'batch',
pagination: { mode: 'client', pageSize: 5 },
hooks: {
beforeSort: guard({ ko: '정렬', en: 'sort' }),
beforeFilter: guard({ ko: '필터', en: 'filter' }),
beforePageChange: guard({ ko: '쪽 이동', en: 'page change' }),
},
};
function setup(api, log) {
say = log;
apiRef = api;
return () => {
apiRef = null;
};
}
const actions = {
save: (api) => {
api.commitChanges();
say({
ko: '저장했어요. 이제 정렬·쪽 이동이 풀려요.',
en: 'Saved. Sorting and paging work again.',
});
},
sort: (api) => {
api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
},
next: (api) => api.setPage(api.getPage() + 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('sort').addEventListener('click', () => actions.sort(api));
document.getElementById('next').addEventListener('click', () => actions.next(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.sort(api)}
>코드로 정렬하기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.next(api)}
>다음 쪽(코드)</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>저장하기</button>
</div>
<Grid style={{ height: 230 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
score: number;
}
const en = document.documentElement.dataset.lang === 'en';
const names = en
? ['Alex', 'Blair', 'Casey', 'Drew', 'Emery', 'Finn', 'Gray', 'Harper', 'Indy', 'Jordan']
: [
'김서연',
'이준호',
'박민지',
'최도윤',
'정하은',
'한지우',
'오세훈',
'윤아름',
'강태양',
'서하늘',
];
const teams = en ? ['Dev', 'Design', 'Ops'] : ['개발', '디자인', '운영'];
let say: (message: LogText) => void = () => {};
let apiRef: GridApi<Row> | null = null;
/** 저장하지 않은 고침이 있으면 막고 이유를 기록해요. 막힌 조작은 이벤트도 상태 변화도 없어요. */
const guard =
(what: { ko: string; en: string }) =>
(ctx: { source: string }): boolean | void => {
if (apiRef?.hasChanges() !== true) return;
say({
ko: `저장하지 않은 고침이 있어 ${what.ko}을(를) 막았어요 (${ctx.source === 'user' ? '화면 조작' : '코드 호출'})`,
en: `Blocked the ${what.en}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`,
});
return false;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: en ? 'Name' : '이름', width: 120, editable: true, sortable: true },
{ id: 'team', title: en ? 'Team' : '팀', width: 100, sortable: true },
{
id: 'score',
title: en ? 'Score' : '점수',
kind: 'number',
width: 90,
editable: true,
sortable: true,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
team: teams[i % 3] as string,
score: 60 + ((i * 7) % 40),
})),
rowKey: 'id',
saveMode: 'batch',
pagination: { mode: 'client', pageSize: 5 },
hooks: {
beforeSort: guard({ ko: '정렬', en: 'sort' }),
beforeFilter: guard({ ko: '필터', en: 'filter' }),
beforePageChange: guard({ ko: '쪽 이동', en: 'page change' }),
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
apiRef = api;
return () => {
apiRef = null;
};
}
export const actions = {
save: (api: GridApi<Row>) => {
api.commitChanges();
say({
ko: '저장했어요. 이제 정렬·쪽 이동이 풀려요.',
en: 'Saved. Sorting and paging work again.',
});
},
sort: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
},
next: (api: GridApi<Row>) => api.setPage(api.getPage() + 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.sort(api)">코드로 정렬하기</button>
<button type="button" :disabled="!api" @click="api && actions.next(api)">다음 쪽(코드)</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">저장하기</button>
</div>
<Grid style="height: 230px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
score: number;
}
const en = document.documentElement.dataset.lang === 'en';
const names = en
? ['Alex', 'Blair', 'Casey', 'Drew', 'Emery', 'Finn', 'Gray', 'Harper', 'Indy', 'Jordan']
: [
'김서연',
'이준호',
'박민지',
'최도윤',
'정하은',
'한지우',
'오세훈',
'윤아름',
'강태양',
'서하늘',
];
const teams = en ? ['Dev', 'Design', 'Ops'] : ['개발', '디자인', '운영'];
let say: (message: LogText) => void = () => {};
let apiRef: GridApi<Row> | null = null;
/** 저장하지 않은 고침이 있으면 막고 이유를 기록해요. 막힌 조작은 이벤트도 상태 변화도 없어요. */
const guard =
(what: { ko: string; en: string }) =>
(ctx: { source: string }): boolean | void => {
if (apiRef?.hasChanges() !== true) return;
say({
ko: `저장하지 않은 고침이 있어 ${what.ko}을(를) 막았어요 (${ctx.source === 'user' ? '화면 조작' : '코드 호출'})`,
en: `Blocked the ${what.en}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`,
});
return false;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: en ? 'Name' : '이름', width: 120, editable: true, sortable: true },
{ id: 'team', title: en ? 'Team' : '팀', width: 100, sortable: true },
{
id: 'score',
title: en ? 'Score' : '점수',
kind: 'number',
width: 90,
editable: true,
sortable: true,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
team: teams[i % 3] as string,
score: 60 + ((i * 7) % 40),
})),
rowKey: 'id',
saveMode: 'batch',
pagination: { mode: 'client', pageSize: 5 },
hooks: {
beforeSort: guard({ ko: '정렬', en: 'sort' }),
beforeFilter: guard({ ko: '필터', en: 'filter' }),
beforePageChange: guard({ ko: '쪽 이동', en: 'page change' }),
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
apiRef = api;
return () => {
apiRef = null;
};
}
export const actions = {
save: (api: GridApi<Row>) => {
api.commitChanges();
say({
ko: '저장했어요. 이제 정렬·쪽 이동이 풀려요.',
en: 'Saved. Sorting and paging work again.',
});
},
sort: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
},
next: (api: GridApi<Row>) => api.setPage(api.getPage() + 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.sort(api)"
>코드로 정렬하기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.next(api)"
>다음 쪽(코드)</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>저장하기</button>
</div>
<mx-grid style="height: 230px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
score: number;
}
const en = document.documentElement.dataset.lang === 'en';
const names = en
? ['Alex', 'Blair', 'Casey', 'Drew', 'Emery', 'Finn', 'Gray', 'Harper', 'Indy', 'Jordan']
: [
'김서연',
'이준호',
'박민지',
'최도윤',
'정하은',
'한지우',
'오세훈',
'윤아름',
'강태양',
'서하늘',
];
const teams = en ? ['Dev', 'Design', 'Ops'] : ['개발', '디자인', '운영'];
let say: (message: LogText) => void = () => {};
let apiRef: GridApi<Row> | null = null;
/** 저장하지 않은 고침이 있으면 막고 이유를 기록해요. 막힌 조작은 이벤트도 상태 변화도 없어요. */
const guard =
(what: { ko: string; en: string }) =>
(ctx: { source: string }): boolean | void => {
if (apiRef?.hasChanges() !== true) return;
say({
ko: `저장하지 않은 고침이 있어 ${what.ko}을(를) 막았어요 (${ctx.source === 'user' ? '화면 조작' : '코드 호출'})`,
en: `Blocked the ${what.en}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`,
});
return false;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: en ? 'Name' : '이름', width: 120, editable: true, sortable: true },
{ id: 'team', title: en ? 'Team' : '팀', width: 100, sortable: true },
{
id: 'score',
title: en ? 'Score' : '점수',
kind: 'number',
width: 90,
editable: true,
sortable: true,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
team: teams[i % 3] as string,
score: 60 + ((i * 7) % 40),
})),
rowKey: 'id',
saveMode: 'batch',
pagination: { mode: 'client', pageSize: 5 },
hooks: {
beforeSort: guard({ ko: '정렬', en: 'sort' }),
beforeFilter: guard({ ko: '필터', en: 'filter' }),
beforePageChange: guard({ ko: '쪽 이동', en: 'page change' }),
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
apiRef = api;
return () => {
apiRef = null;
};
}
export const actions = {
save: (api: GridApi<Row>) => {
api.commitChanges();
say({
ko: '저장했어요. 이제 정렬·쪽 이동이 풀려요.',
en: 'Saved. Sorting and paging work again.',
});
},
sort: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
},
next: (api: GridApi<Row>) => api.setPage(api.getPage() + 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="sort">Sort from code</button>
<button type="button" id="next">Next page (code)</button>
<button type="button" id="save">Save</button>
</div>
<div id="grid" style="height: 230px"></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('sort').addEventListener('click', () => actions.sort(api));
document.getElementById('next').addEventListener('click', () => actions.next(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Reed',
'Ava Brooks',
'Mason Lee',
'Sophia Hayes',
'Ethan Cole',
'Isabella Ward',
'Lucas Young',
];
const teams = ['Dev', 'Design', 'Ops'];
let say = () => { };
let apiRef = null;
/** Blocks the action and logs the reason while there are unsaved edits. A blocked action fires no event and changes no state. */
const guard = (what) => (ctx) => {
if (apiRef?.hasChanges() !== true)
return;
say(`Blocked the ${what}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`);
return false;
};
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 120, editable: true, sortable: true },
{ id: 'team', title: 'Team', width: 100, sortable: true },
{
id: 'score',
title: 'Score',
kind: 'number',
width: 90,
editable: true,
sortable: true,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
team: teams[i % 3],
score: 60 + ((i * 7) % 40),
})),
rowKey: 'id',
saveMode: 'batch',
pagination: { mode: 'client', pageSize: 5 },
hooks: {
beforeSort: guard('sort'),
beforeFilter: guard('filter'),
beforePageChange: guard('page change'),
},
};
export function setup(api, log) {
say = log;
apiRef = api;
return () => {
apiRef = null;
};
}
export const actions = {
save: (api) => {
api.commitChanges();
say('Saved. Sorting and paging work again.');
},
sort: (api) => {
api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
},
next: (api) => api.setPage(api.getPage() + 1),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Block sorting and paging before saving</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="sort">Sort from code</button>
<button type="button" id="next">Next page (code)</button>
<button type="button" id="save">Save</button>
</div>
<div id="grid" style="height: 230px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Reed',
'Ava Brooks',
'Mason Lee',
'Sophia Hayes',
'Ethan Cole',
'Isabella Ward',
'Lucas Young',
];
const teams = ['Dev', 'Design', 'Ops'];
let say = () => { };
let apiRef = null;
/** Blocks the action and logs the reason while there are unsaved edits. A blocked action fires no event and changes no state. */
const guard = (what) => (ctx) => {
if (apiRef?.hasChanges() !== true)
return;
say(`Blocked the ${what}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`);
return false;
};
const options = {
columns: [
{ id: 'name', title: 'Name', width: 120, editable: true, sortable: true },
{ id: 'team', title: 'Team', width: 100, sortable: true },
{
id: 'score',
title: 'Score',
kind: 'number',
width: 90,
editable: true,
sortable: true,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
team: teams[i % 3],
score: 60 + ((i * 7) % 40),
})),
rowKey: 'id',
saveMode: 'batch',
pagination: { mode: 'client', pageSize: 5 },
hooks: {
beforeSort: guard('sort'),
beforeFilter: guard('filter'),
beforePageChange: guard('page change'),
},
};
function setup(api, log) {
say = log;
apiRef = api;
return () => {
apiRef = null;
};
}
const actions = {
save: (api) => {
api.commitChanges();
say('Saved. Sorting and paging work again.');
},
sort: (api) => {
api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
},
next: (api) => api.setPage(api.getPage() + 1),
};
options.ariaLabel = "Block sorting and paging 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('sort').addEventListener('click', () => actions.sort(api));
document.getElementById('next').addEventListener('click', () => actions.next(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.sort(api)}
>Sort from code</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.next(api)}
>Next page (code)</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>Save</button>
</div>
<Grid style={{ height: 230 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
team: string;
score: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Reed',
'Ava Brooks',
'Mason Lee',
'Sophia Hayes',
'Ethan Cole',
'Isabella Ward',
'Lucas Young',
];
const teams = ['Dev', 'Design', 'Ops'];
let say: (message: LogText) => void = () => {};
let apiRef: GridApi<Row> | null = null;
/** Blocks the action and logs the reason while there are unsaved edits. A blocked action fires no event and changes no state. */
const guard =
(what: string) =>
(ctx: { source: string }): boolean | void => {
if (apiRef?.hasChanges() !== true) return;
say(
`Blocked the ${what}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`,
);
return false;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 120, editable: true, sortable: true },
{ id: 'team', title: 'Team', width: 100, sortable: true },
{
id: 'score',
title: 'Score',
kind: 'number',
width: 90,
editable: true,
sortable: true,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
team: teams[i % 3] as string,
score: 60 + ((i * 7) % 40),
})),
rowKey: 'id',
saveMode: 'batch',
pagination: { mode: 'client', pageSize: 5 },
hooks: {
beforeSort: guard('sort'),
beforeFilter: guard('filter'),
beforePageChange: guard('page change'),
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
apiRef = api;
return () => {
apiRef = null;
};
}
export const actions = {
save: (api: GridApi<Row>) => {
api.commitChanges();
say('Saved. Sorting and paging work again.');
},
sort: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
},
next: (api: GridApi<Row>) => api.setPage(api.getPage() + 1),
};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.sort(api)">Sort from code</button>
<button type="button" :disabled="!api" @click="api && actions.next(api)">Next page (code)</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">Save</button>
</div>
<Grid style="height: 230px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
team: string;
score: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Reed',
'Ava Brooks',
'Mason Lee',
'Sophia Hayes',
'Ethan Cole',
'Isabella Ward',
'Lucas Young',
];
const teams = ['Dev', 'Design', 'Ops'];
let say: (message: LogText) => void = () => {};
let apiRef: GridApi<Row> | null = null;
/** Blocks the action and logs the reason while there are unsaved edits. A blocked action fires no event and changes no state. */
const guard =
(what: string) =>
(ctx: { source: string }): boolean | void => {
if (apiRef?.hasChanges() !== true) return;
say(
`Blocked the ${what}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`,
);
return false;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 120, editable: true, sortable: true },
{ id: 'team', title: 'Team', width: 100, sortable: true },
{
id: 'score',
title: 'Score',
kind: 'number',
width: 90,
editable: true,
sortable: true,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
team: teams[i % 3] as string,
score: 60 + ((i * 7) % 40),
})),
rowKey: 'id',
saveMode: 'batch',
pagination: { mode: 'client', pageSize: 5 },
hooks: {
beforeSort: guard('sort'),
beforeFilter: guard('filter'),
beforePageChange: guard('page change'),
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
apiRef = api;
return () => {
apiRef = null;
};
}
export const actions = {
save: (api: GridApi<Row>) => {
api.commitChanges();
say('Saved. Sorting and paging work again.');
},
sort: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
},
next: (api: GridApi<Row>) => api.setPage(api.getPage() + 1),
};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.sort(api)"
>Sort from code</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.next(api)"
>Next page (code)</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>Save</button>
</div>
<mx-grid style="height: 230px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
team: string;
score: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Reed',
'Ava Brooks',
'Mason Lee',
'Sophia Hayes',
'Ethan Cole',
'Isabella Ward',
'Lucas Young',
];
const teams = ['Dev', 'Design', 'Ops'];
let say: (message: LogText) => void = () => {};
let apiRef: GridApi<Row> | null = null;
/** Blocks the action and logs the reason while there are unsaved edits. A blocked action fires no event and changes no state. */
const guard =
(what: string) =>
(ctx: { source: string }): boolean | void => {
if (apiRef?.hasChanges() !== true) return;
say(
`Blocked the ${what}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`,
);
return false;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 120, editable: true, sortable: true },
{ id: 'team', title: 'Team', width: 100, sortable: true },
{
id: 'score',
title: 'Score',
kind: 'number',
width: 90,
editable: true,
sortable: true,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
team: teams[i % 3] as string,
score: 60 + ((i * 7) % 40),
})),
rowKey: 'id',
saveMode: 'batch',
pagination: { mode: 'client', pageSize: 5 },
hooks: {
beforeSort: guard('sort'),
beforeFilter: guard('filter'),
beforePageChange: guard('page change'),
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
apiRef = api;
return () => {
apiRef = null;
};
}
export const actions = {
save: (api: GridApi<Row>) => {
api.commitChanges();
say('Saved. Sorting and paging work again.');
},
sort: (api: GridApi<Row>) => {
api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
},
next: (api: GridApi<Row>) => api.setPage(api.getPage() + 1),
};