서버에서 한 페이지씩만 받아 오기Fetch one page at a time from a server
주문 2,000건이 서버에 있어도 화면에는 필요한 10건만 받아 와요. 페이지를 넘기거나 헤더로 정렬하거나 검색·국가를 바꿀 때마다 그리드가 서버에 새 요청을 보내고, 늦게 온 옛 응답은 알아서 버려요.Even with 2,000 orders on a server, the grid fetches only the 10 it shows. Paging, sorting or changing the search triggers a new request, and stale responses are dropped automatically.
코드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">
<input type="text" aria-label="고객사·상품 검색" placeholder="예: 한빛" id="query" />
<select aria-label="국가" id="country">
<option value="all" selected>전체</option>
<option value="kr">한국</option>
<option value="us">미국</option>
<option value="jp">일본</option>
<option value="cn">중국</option>
<option value="gb">영국</option>
<option value="fr">프랑스</option>
</select>
<button type="button" id="failOnce">다음 요청 한 번 실패시키기</button>
</div>
<div id="grid" style="height: 460px"></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('query').addEventListener('input', (event) => actions.query(api, event.target.value));
document.getElementById('country').addEventListener('change', (event) => actions.country(api, event.target.value));
document.getElementById('failOnce').addEventListener('click', () => actions.failOnce(api));const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'해든전자',
];
const countries = ['한국', '미국', '일본', '중국', '영국', '프랑스'];
const products = ['무선 이어폰', '스마트 워치', '노트북 거치대', '보조배터리', '블루투스 스피커'];
// 서버에 주문 2,000건이 있다고 가정해요. 이 예제는 서버 대신 메모리에서 0.4초 뒤에 답을 돌려줘요.
const ALL = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
customer: customers[i % 7],
country: countries[(i * 5) % 6],
product: products[(i * 7) % 5],
amount: 29000 + ((i * 7919) % 480000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// 실제 서비스라면 GET /orders?page=3&size=10&sort=amount,desc&q=… 같은 요청이에요.
// 그리드는 "몇 쪽, 몇 건, 어떤 정렬·필터"인지만 넘기고, 서버는 그 쪽 행과 전체 건수를 돌려줘요.
function fetchPage({ page, pageSize, sort, signal }) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (failNext) {
failNext = false;
reject(new Error('서버가 응답하지 않아요'));
return;
}
let rows = ALL.filter((r) => (!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
(state.country === 'all' || r.country === state.country));
const first = sort[0];
if (first) {
const sign = first.direction === 'desc' ? -1 : 1;
const key = first.columnId;
rows = [...rows].sort((a, b) => typeof a[key] === 'number'
? sign * (a[key] - b[key])
: sign * String(a[key]).localeCompare(String(b[key]), 'ko'));
}
resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
}, delay);
// 더 새로운 요청이 오면 그리드가 이전 요청을 취소해요.
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('aborted', 'AbortError'));
});
});
}
export const options = {
columns: [
{ id: 'customer', title: '고객사', width: 130 },
{ id: 'country', title: '국가', width: 90 },
{ id: 'product', title: '상품', width: 160 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
pagination: {
mode: 'server',
pageSize: 10,
pageSizes: [10, 20],
loadPage: fetchPage,
jump: true,
},
};
export function setup(api, log) {
delay = 400;
failNext = false;
state.query = '';
state.country = 'all';
const offPage = api.on('pageChanged', ({ page, reason }) => log({
ko: `${page}페이지를 서버에 요청 (${reason})`,
en: `Requested page ${page} from the server (${reason})`,
}));
const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
if (error)
log({
ko: '불러오기 실패 — 페이지 막대의 "다시 시도"를 눌러 보세요',
en: 'Load failed — press "Retry" in the pager',
});
else if (!loading)
log({
ko: `도착: 조건에 맞는 ${api.getPageInfo().totalRows}건`,
en: `Arrived: ${api.getPageInfo().totalRows} matching rows`,
});
});
return () => {
offPage();
offLoad();
};
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 표의 값으로 바꿔 써요.
const COUNTRY_BY_KEY = {
kr: '한국',
us: '미국',
jp: '일본',
cn: '중국',
gb: '영국',
fr: '프랑스',
};
export const actions = {
query: (api, value) => {
state.query = (value ?? '').trim();
api.reloadPage();
},
country: (api, value) => {
state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
api.reloadPage();
},
// 다음 요청 한 번을 일부러 실패시켜요.
failOnce: (api) => {
failNext = true;
api.reloadPage();
},
};<!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">
<input type="text" aria-label="고객사·상품 검색" placeholder="예: 한빛" id="query" />
<select aria-label="국가" id="country">
<option value="all" selected>전체</option>
<option value="kr">한국</option>
<option value="us">미국</option>
<option value="jp">일본</option>
<option value="cn">중국</option>
<option value="gb">영국</option>
<option value="fr">프랑스</option>
</select>
<button type="button" id="failOnce">다음 요청 한 번 실패시키기</button>
</div>
<div id="grid" style="height: 460px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'해든전자',
];
const countries = ['한국', '미국', '일본', '중국', '영국', '프랑스'];
const products = ['무선 이어폰', '스마트 워치', '노트북 거치대', '보조배터리', '블루투스 스피커'];
// 서버에 주문 2,000건이 있다고 가정해요. 이 예제는 서버 대신 메모리에서 0.4초 뒤에 답을 돌려줘요.
const ALL = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
customer: customers[i % 7],
country: countries[(i * 5) % 6],
product: products[(i * 7) % 5],
amount: 29000 + ((i * 7919) % 480000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// 실제 서비스라면 GET /orders?page=3&size=10&sort=amount,desc&q=… 같은 요청이에요.
// 그리드는 "몇 쪽, 몇 건, 어떤 정렬·필터"인지만 넘기고, 서버는 그 쪽 행과 전체 건수를 돌려줘요.
function fetchPage({ page, pageSize, sort, signal }) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (failNext) {
failNext = false;
reject(new Error('서버가 응답하지 않아요'));
return;
}
let rows = ALL.filter((r) => (!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
(state.country === 'all' || r.country === state.country));
const first = sort[0];
if (first) {
const sign = first.direction === 'desc' ? -1 : 1;
const key = first.columnId;
rows = [...rows].sort((a, b) => typeof a[key] === 'number'
? sign * (a[key] - b[key])
: sign * String(a[key]).localeCompare(String(b[key]), 'ko'));
}
resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
}, delay);
// 더 새로운 요청이 오면 그리드가 이전 요청을 취소해요.
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('aborted', 'AbortError'));
});
});
}
const options = {
columns: [
{ id: 'customer', title: '고객사', width: 130 },
{ id: 'country', title: '국가', width: 90 },
{ id: 'product', title: '상품', width: 160 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
pagination: {
mode: 'server',
pageSize: 10,
pageSizes: [10, 20],
loadPage: fetchPage,
jump: true,
},
};
function setup(api, log) {
delay = 400;
failNext = false;
state.query = '';
state.country = 'all';
const offPage = api.on('pageChanged', ({ page, reason }) => log({
ko: `${page}페이지를 서버에 요청 (${reason})`,
en: `Requested page ${page} from the server (${reason})`,
}));
const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
if (error)
log({
ko: '불러오기 실패 — 페이지 막대의 "다시 시도"를 눌러 보세요',
en: 'Load failed — press "Retry" in the pager',
});
else if (!loading)
log({
ko: `도착: 조건에 맞는 ${api.getPageInfo().totalRows}건`,
en: `Arrived: ${api.getPageInfo().totalRows} matching rows`,
});
});
return () => {
offPage();
offLoad();
};
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 표의 값으로 바꿔 써요.
const COUNTRY_BY_KEY = {
kr: '한국',
us: '미국',
jp: '일본',
cn: '중국',
gb: '영국',
fr: '프랑스',
};
const actions = {
query: (api, value) => {
state.query = (value ?? '').trim();
api.reloadPage();
},
country: (api, value) => {
state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
api.reloadPage();
},
// 다음 요청 한 번을 일부러 실패시켜요.
failOnce: (api) => {
failNext = true;
api.reloadPage();
},
};
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('query').addEventListener('input', (event) => actions.query(api, event.target.value));
document.getElementById('country').addEventListener('change', (event) => actions.country(api, event.target.value));
document.getElementById('failOnce').addEventListener('click', () => actions.failOnce(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">
<input
type="text"
aria-label="고객사·상품 검색"
placeholder="예: 한빛"
disabled={!api}
onChange={(event) => api && actions.query(api, event.target.value)}
/>
<select
aria-label="국가"
disabled={!api}
onChange={(event) => api && actions.country(api, event.target.value)}
>
<option value="all">전체</option>
<option value="kr">한국</option>
<option value="us">미국</option>
<option value="jp">일본</option>
<option value="cn">중국</option>
<option value="gb">영국</option>
<option value="fr">프랑스</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.failOnce(api)}
>다음 요청 한 번 실패시키기</button>
</div>
<Grid style={{ height: 460 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, PageQuery, PageResult } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
country: string;
product: string;
amount: number;
}
const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'해든전자',
];
const countries = ['한국', '미국', '일본', '중국', '영국', '프랑스'];
const products = ['무선 이어폰', '스마트 워치', '노트북 거치대', '보조배터리', '블루투스 스피커'];
// 서버에 주문 2,000건이 있다고 가정해요. 이 예제는 서버 대신 메모리에서 0.4초 뒤에 답을 돌려줘요.
const ALL: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
customer: customers[i % 7] as string,
country: countries[(i * 5) % 6] as string,
product: products[(i * 7) % 5] as string,
amount: 29000 + ((i * 7919) % 480000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// 실제 서비스라면 GET /orders?page=3&size=10&sort=amount,desc&q=… 같은 요청이에요.
// 그리드는 "몇 쪽, 몇 건, 어떤 정렬·필터"인지만 넘기고, 서버는 그 쪽 행과 전체 건수를 돌려줘요.
function fetchPage({ page, pageSize, sort, signal }: PageQuery): Promise<PageResult<Row>> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (failNext) {
failNext = false;
reject(new Error('서버가 응답하지 않아요'));
return;
}
let rows = ALL.filter(
(r) =>
(!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
(state.country === 'all' || r.country === state.country),
);
const first = sort[0];
if (first) {
const sign = first.direction === 'desc' ? -1 : 1;
const key = first.columnId as keyof Row;
rows = [...rows].sort((a, b) =>
typeof a[key] === 'number'
? sign * ((a[key] as number) - (b[key] as number))
: sign * String(a[key]).localeCompare(String(b[key]), 'ko'),
);
}
resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
}, delay);
// 더 새로운 요청이 오면 그리드가 이전 요청을 취소해요.
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('aborted', 'AbortError'));
});
});
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객사', width: 130 },
{ id: 'country', title: '국가', width: 90 },
{ id: 'product', title: '상품', width: 160 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
pagination: {
mode: 'server',
pageSize: 10,
pageSizes: [10, 20],
loadPage: fetchPage,
jump: true,
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
delay = 400;
failNext = false;
state.query = '';
state.country = 'all';
const offPage = api.on('pageChanged', ({ page, reason }) =>
log({
ko: `${page}페이지를 서버에 요청 (${reason})`,
en: `Requested page ${page} from the server (${reason})`,
}),
);
const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
if (error)
log({
ko: '불러오기 실패 — 페이지 막대의 "다시 시도"를 눌러 보세요',
en: 'Load failed — press "Retry" in the pager',
});
else if (!loading)
log({
ko: `도착: 조건에 맞는 ${api.getPageInfo().totalRows}건`,
en: `Arrived: ${api.getPageInfo().totalRows} matching rows`,
});
});
return () => {
offPage();
offLoad();
};
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 표의 값으로 바꿔 써요.
const COUNTRY_BY_KEY: Record<string, string> = {
kr: '한국',
us: '미국',
jp: '일본',
cn: '중국',
gb: '영국',
fr: '프랑스',
};
export const actions = {
query: (api: GridApi<Row>, value?: string) => {
state.query = (value ?? '').trim();
api.reloadPage();
},
country: (api: GridApi<Row>, value?: string) => {
state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
api.reloadPage();
},
// 다음 요청 한 번을 일부러 실패시켜요.
failOnce: (api: GridApi<Row>) => {
failNext = true;
api.reloadPage();
},
};버튼을 누르면 이 예제의 코드가 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">
<input
type="text"
aria-label="고객사·상품 검색"
placeholder="예: 한빛"
:disabled="!api"
@input="api && actions.query(api, ($event.target as HTMLInputElement).value)"
/>
<select
aria-label="국가"
:disabled="!api"
@change="api && actions.country(api, ($event.target as HTMLSelectElement).value)"
>
<option value="all" selected>전체</option>
<option value="kr">한국</option>
<option value="us">미국</option>
<option value="jp">일본</option>
<option value="cn">중국</option>
<option value="gb">영국</option>
<option value="fr">프랑스</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.failOnce(api)"
>다음 요청 한 번 실패시키기</button>
</div>
<Grid style="height: 460px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, PageQuery, PageResult } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
country: string;
product: string;
amount: number;
}
const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'해든전자',
];
const countries = ['한국', '미국', '일본', '중국', '영국', '프랑스'];
const products = ['무선 이어폰', '스마트 워치', '노트북 거치대', '보조배터리', '블루투스 스피커'];
// 서버에 주문 2,000건이 있다고 가정해요. 이 예제는 서버 대신 메모리에서 0.4초 뒤에 답을 돌려줘요.
const ALL: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
customer: customers[i % 7] as string,
country: countries[(i * 5) % 6] as string,
product: products[(i * 7) % 5] as string,
amount: 29000 + ((i * 7919) % 480000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// 실제 서비스라면 GET /orders?page=3&size=10&sort=amount,desc&q=… 같은 요청이에요.
// 그리드는 "몇 쪽, 몇 건, 어떤 정렬·필터"인지만 넘기고, 서버는 그 쪽 행과 전체 건수를 돌려줘요.
function fetchPage({ page, pageSize, sort, signal }: PageQuery): Promise<PageResult<Row>> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (failNext) {
failNext = false;
reject(new Error('서버가 응답하지 않아요'));
return;
}
let rows = ALL.filter(
(r) =>
(!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
(state.country === 'all' || r.country === state.country),
);
const first = sort[0];
if (first) {
const sign = first.direction === 'desc' ? -1 : 1;
const key = first.columnId as keyof Row;
rows = [...rows].sort((a, b) =>
typeof a[key] === 'number'
? sign * ((a[key] as number) - (b[key] as number))
: sign * String(a[key]).localeCompare(String(b[key]), 'ko'),
);
}
resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
}, delay);
// 더 새로운 요청이 오면 그리드가 이전 요청을 취소해요.
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('aborted', 'AbortError'));
});
});
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객사', width: 130 },
{ id: 'country', title: '국가', width: 90 },
{ id: 'product', title: '상품', width: 160 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
pagination: {
mode: 'server',
pageSize: 10,
pageSizes: [10, 20],
loadPage: fetchPage,
jump: true,
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
delay = 400;
failNext = false;
state.query = '';
state.country = 'all';
const offPage = api.on('pageChanged', ({ page, reason }) =>
log({
ko: `${page}페이지를 서버에 요청 (${reason})`,
en: `Requested page ${page} from the server (${reason})`,
}),
);
const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
if (error)
log({
ko: '불러오기 실패 — 페이지 막대의 "다시 시도"를 눌러 보세요',
en: 'Load failed — press "Retry" in the pager',
});
else if (!loading)
log({
ko: `도착: 조건에 맞는 ${api.getPageInfo().totalRows}건`,
en: `Arrived: ${api.getPageInfo().totalRows} matching rows`,
});
});
return () => {
offPage();
offLoad();
};
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 표의 값으로 바꿔 써요.
const COUNTRY_BY_KEY: Record<string, string> = {
kr: '한국',
us: '미국',
jp: '일본',
cn: '중국',
gb: '영국',
fr: '프랑스',
};
export const actions = {
query: (api: GridApi<Row>, value?: string) => {
state.query = (value ?? '').trim();
api.reloadPage();
},
country: (api: GridApi<Row>, value?: string) => {
state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
api.reloadPage();
},
// 다음 요청 한 번을 일부러 실패시켜요.
failOnce: (api: GridApi<Row>) => {
failNext = true;
api.reloadPage();
},
};버튼을 누르면 이 예제의 코드가 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">
<input
type="text"
aria-label="고객사·상품 검색"
placeholder="예: 한빛"
[disabled]="!api"
(input)="api && actions.query(api, $any($event.target).value)"
/>
<select
aria-label="국가"
[disabled]="!api"
(change)="api && actions.country(api, $any($event.target).value)"
>
<option value="all" selected>전체</option>
<option value="kr">한국</option>
<option value="us">미국</option>
<option value="jp">일본</option>
<option value="cn">중국</option>
<option value="gb">영국</option>
<option value="fr">프랑스</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.failOnce(api)"
>다음 요청 한 번 실패시키기</button>
</div>
<mx-grid style="height: 460px" [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, PageQuery, PageResult } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
country: string;
product: string;
amount: number;
}
const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'해든전자',
];
const countries = ['한국', '미국', '일본', '중국', '영국', '프랑스'];
const products = ['무선 이어폰', '스마트 워치', '노트북 거치대', '보조배터리', '블루투스 스피커'];
// 서버에 주문 2,000건이 있다고 가정해요. 이 예제는 서버 대신 메모리에서 0.4초 뒤에 답을 돌려줘요.
const ALL: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
customer: customers[i % 7] as string,
country: countries[(i * 5) % 6] as string,
product: products[(i * 7) % 5] as string,
amount: 29000 + ((i * 7919) % 480000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// 실제 서비스라면 GET /orders?page=3&size=10&sort=amount,desc&q=… 같은 요청이에요.
// 그리드는 "몇 쪽, 몇 건, 어떤 정렬·필터"인지만 넘기고, 서버는 그 쪽 행과 전체 건수를 돌려줘요.
function fetchPage({ page, pageSize, sort, signal }: PageQuery): Promise<PageResult<Row>> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (failNext) {
failNext = false;
reject(new Error('서버가 응답하지 않아요'));
return;
}
let rows = ALL.filter(
(r) =>
(!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
(state.country === 'all' || r.country === state.country),
);
const first = sort[0];
if (first) {
const sign = first.direction === 'desc' ? -1 : 1;
const key = first.columnId as keyof Row;
rows = [...rows].sort((a, b) =>
typeof a[key] === 'number'
? sign * ((a[key] as number) - (b[key] as number))
: sign * String(a[key]).localeCompare(String(b[key]), 'ko'),
);
}
resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
}, delay);
// 더 새로운 요청이 오면 그리드가 이전 요청을 취소해요.
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('aborted', 'AbortError'));
});
});
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객사', width: 130 },
{ id: 'country', title: '국가', width: 90 },
{ id: 'product', title: '상품', width: 160 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
pagination: {
mode: 'server',
pageSize: 10,
pageSizes: [10, 20],
loadPage: fetchPage,
jump: true,
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
delay = 400;
failNext = false;
state.query = '';
state.country = 'all';
const offPage = api.on('pageChanged', ({ page, reason }) =>
log({
ko: `${page}페이지를 서버에 요청 (${reason})`,
en: `Requested page ${page} from the server (${reason})`,
}),
);
const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
if (error)
log({
ko: '불러오기 실패 — 페이지 막대의 "다시 시도"를 눌러 보세요',
en: 'Load failed — press "Retry" in the pager',
});
else if (!loading)
log({
ko: `도착: 조건에 맞는 ${api.getPageInfo().totalRows}건`,
en: `Arrived: ${api.getPageInfo().totalRows} matching rows`,
});
});
return () => {
offPage();
offLoad();
};
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 표의 값으로 바꿔 써요.
const COUNTRY_BY_KEY: Record<string, string> = {
kr: '한국',
us: '미국',
jp: '일본',
cn: '중국',
gb: '영국',
fr: '프랑스',
};
export const actions = {
query: (api: GridApi<Row>, value?: string) => {
state.query = (value ?? '').trim();
api.reloadPage();
},
country: (api: GridApi<Row>, value?: string) => {
state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
api.reloadPage();
},
// 다음 요청 한 번을 일부러 실패시켜요.
failOnce: (api: GridApi<Row>) => {
failNext = true;
api.reloadPage();
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<input
type="text"
aria-label="Search"
placeholder="e.g. Wireless"
id="query"
/>
<select aria-label="Country" id="country">
<option value="all" selected>All</option>
<option value="kr">Korea</option>
<option value="us">USA</option>
<option value="jp">Japan</option>
<option value="cn">China</option>
<option value="gb">UK</option>
<option value="fr">France</option>
</select>
<button type="button" id="failOnce">Fail the next request</button>
</div>
<div id="grid" style="height: 460px"></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('query').addEventListener('input', (event) => actions.query(api, event.target.value));
document.getElementById('country').addEventListener('change', (event) => actions.country(api, event.target.value));
document.getElementById('failOnce').addEventListener('click', () => actions.failOnce(api));const customers = [
'Harbor Logistics',
'Blue Sky Foods',
'Polaris Trading',
'Dawn Commerce',
'Sunrise Farm',
'Moda Fashion',
'Bright Electronics',
];
const countries = ['Korea', 'USA', 'Japan', 'China', 'UK', 'France'];
const products = [
'Wireless earbuds',
'Smart watch',
'Laptop stand',
'Power bank',
'Bluetooth speaker',
];
// Pretend the server holds 2,000 orders. Instead of a server, this example answers from memory after 0.4 seconds.
const ALL = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
customer: customers[i % 7],
country: countries[(i * 5) % 6],
product: products[(i * 7) % 5],
amount: 29 + Math.round(((i * 7919) % 480000) / 1000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// In a real service this is a request like GET /orders?page=3&size=10&sort=amount,desc&q=...
// The grid only passes "which page, how many rows, what sort and filter", and the server returns that page's rows and the total count.
function fetchPage({ page, pageSize, sort, signal }) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (failNext) {
failNext = false;
reject(new Error('The server is not responding'));
return;
}
let rows = ALL.filter((r) => (!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
(state.country === 'all' || r.country === state.country));
const first = sort[0];
if (first) {
const sign = first.direction === 'desc' ? -1 : 1;
const key = first.columnId;
rows = [...rows].sort((a, b) => typeof a[key] === 'number'
? sign * (a[key] - b[key])
: sign * String(a[key]).localeCompare(String(b[key]), 'en'));
}
resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
}, delay);
// When a newer request arrives, the grid cancels the previous one.
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('aborted', 'AbortError'));
});
});
}
export const options = {
columns: [
{ id: 'customer', title: 'Customer', width: 150 },
{ id: 'country', title: 'Country', width: 100 },
{ id: 'product', title: 'Product', width: 170 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
pagination: {
mode: 'server',
pageSize: 10,
pageSizes: [10, 20],
loadPage: fetchPage,
jump: true,
},
};
export function setup(api, log) {
delay = 400;
failNext = false;
state.query = '';
state.country = 'all';
const offPage = api.on('pageChanged', ({ page, reason }) => log(`Requested page ${page} from the server (${reason})`));
const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
if (error)
log('Load failed — press "Retry" in the pager');
else if (!loading)
log(`Arrived: ${api.getPageInfo().totalRows} matching rows`);
});
return () => {
offPage();
offLoad();
};
}
// The control values are language-neutral keys; map them to the values in the table.
const COUNTRY_BY_KEY = {
kr: 'Korea',
us: 'USA',
jp: 'Japan',
cn: 'China',
gb: 'UK',
fr: 'France',
};
export const actions = {
query: (api, value) => {
state.query = (value ?? '').trim();
api.reloadPage();
},
country: (api, value) => {
state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
api.reloadPage();
},
// Deliberately fail the next request once.
failOnce: (api) => {
failNext = true;
api.reloadPage();
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Fetch one page at a time from a server</title>
</head>
<body>
<div class="toolbar">
<input
type="text"
aria-label="Search"
placeholder="e.g. Wireless"
id="query"
/>
<select aria-label="Country" id="country">
<option value="all" selected>All</option>
<option value="kr">Korea</option>
<option value="us">USA</option>
<option value="jp">Japan</option>
<option value="cn">China</option>
<option value="gb">UK</option>
<option value="fr">France</option>
</select>
<button type="button" id="failOnce">Fail the next request</button>
</div>
<div id="grid" style="height: 460px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const customers = [
'Harbor Logistics',
'Blue Sky Foods',
'Polaris Trading',
'Dawn Commerce',
'Sunrise Farm',
'Moda Fashion',
'Bright Electronics',
];
const countries = ['Korea', 'USA', 'Japan', 'China', 'UK', 'France'];
const products = [
'Wireless earbuds',
'Smart watch',
'Laptop stand',
'Power bank',
'Bluetooth speaker',
];
// Pretend the server holds 2,000 orders. Instead of a server, this example answers from memory after 0.4 seconds.
const ALL = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
customer: customers[i % 7],
country: countries[(i * 5) % 6],
product: products[(i * 7) % 5],
amount: 29 + Math.round(((i * 7919) % 480000) / 1000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// In a real service this is a request like GET /orders?page=3&size=10&sort=amount,desc&q=...
// The grid only passes "which page, how many rows, what sort and filter", and the server returns that page's rows and the total count.
function fetchPage({ page, pageSize, sort, signal }) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (failNext) {
failNext = false;
reject(new Error('The server is not responding'));
return;
}
let rows = ALL.filter((r) => (!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
(state.country === 'all' || r.country === state.country));
const first = sort[0];
if (first) {
const sign = first.direction === 'desc' ? -1 : 1;
const key = first.columnId;
rows = [...rows].sort((a, b) => typeof a[key] === 'number'
? sign * (a[key] - b[key])
: sign * String(a[key]).localeCompare(String(b[key]), 'en'));
}
resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
}, delay);
// When a newer request arrives, the grid cancels the previous one.
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('aborted', 'AbortError'));
});
});
}
const options = {
columns: [
{ id: 'customer', title: 'Customer', width: 150 },
{ id: 'country', title: 'Country', width: 100 },
{ id: 'product', title: 'Product', width: 170 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
pagination: {
mode: 'server',
pageSize: 10,
pageSizes: [10, 20],
loadPage: fetchPage,
jump: true,
},
};
function setup(api, log) {
delay = 400;
failNext = false;
state.query = '';
state.country = 'all';
const offPage = api.on('pageChanged', ({ page, reason }) => log(`Requested page ${page} from the server (${reason})`));
const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
if (error)
log('Load failed — press "Retry" in the pager');
else if (!loading)
log(`Arrived: ${api.getPageInfo().totalRows} matching rows`);
});
return () => {
offPage();
offLoad();
};
}
// The control values are language-neutral keys; map them to the values in the table.
const COUNTRY_BY_KEY = {
kr: 'Korea',
us: 'USA',
jp: 'Japan',
cn: 'China',
gb: 'UK',
fr: 'France',
};
const actions = {
query: (api, value) => {
state.query = (value ?? '').trim();
api.reloadPage();
},
country: (api, value) => {
state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
api.reloadPage();
},
// Deliberately fail the next request once.
failOnce: (api) => {
failNext = true;
api.reloadPage();
},
};
options.ariaLabel = "Fetch one page at a time from a server";
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('query').addEventListener('input', (event) => actions.query(api, event.target.value));
document.getElementById('country').addEventListener('change', (event) => actions.country(api, event.target.value));
document.getElementById('failOnce').addEventListener('click', () => actions.failOnce(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">
<input
type="text"
aria-label="Search"
placeholder="e.g. Wireless"
disabled={!api}
onChange={(event) => api && actions.query(api, event.target.value)}
/>
<select
aria-label="Country"
disabled={!api}
onChange={(event) => api && actions.country(api, event.target.value)}
>
<option value="all">All</option>
<option value="kr">Korea</option>
<option value="us">USA</option>
<option value="jp">Japan</option>
<option value="cn">China</option>
<option value="gb">UK</option>
<option value="fr">France</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.failOnce(api)}
>Fail the next request</button>
</div>
<Grid style={{ height: 460 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, PageQuery, PageResult } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
customer: string;
country: string;
product: string;
amount: number;
}
const customers = [
'Harbor Logistics',
'Blue Sky Foods',
'Polaris Trading',
'Dawn Commerce',
'Sunrise Farm',
'Moda Fashion',
'Bright Electronics',
];
const countries = ['Korea', 'USA', 'Japan', 'China', 'UK', 'France'];
const products = [
'Wireless earbuds',
'Smart watch',
'Laptop stand',
'Power bank',
'Bluetooth speaker',
];
// Pretend the server holds 2,000 orders. Instead of a server, this example answers from memory after 0.4 seconds.
const ALL: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
customer: customers[i % 7] as string,
country: countries[(i * 5) % 6] as string,
product: products[(i * 7) % 5] as string,
amount: 29 + Math.round(((i * 7919) % 480000) / 1000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// In a real service this is a request like GET /orders?page=3&size=10&sort=amount,desc&q=...
// The grid only passes "which page, how many rows, what sort and filter", and the server returns that page's rows and the total count.
function fetchPage({ page, pageSize, sort, signal }: PageQuery): Promise<PageResult<Row>> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (failNext) {
failNext = false;
reject(new Error('The server is not responding'));
return;
}
let rows = ALL.filter(
(r) =>
(!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
(state.country === 'all' || r.country === state.country),
);
const first = sort[0];
if (first) {
const sign = first.direction === 'desc' ? -1 : 1;
const key = first.columnId as keyof Row;
rows = [...rows].sort((a, b) =>
typeof a[key] === 'number'
? sign * ((a[key] as number) - (b[key] as number))
: sign * String(a[key]).localeCompare(String(b[key]), 'en'),
);
}
resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
}, delay);
// When a newer request arrives, the grid cancels the previous one.
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('aborted', 'AbortError'));
});
});
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 150 },
{ id: 'country', title: 'Country', width: 100 },
{ id: 'product', title: 'Product', width: 170 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
pagination: {
mode: 'server',
pageSize: 10,
pageSizes: [10, 20],
loadPage: fetchPage,
jump: true,
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
delay = 400;
failNext = false;
state.query = '';
state.country = 'all';
const offPage = api.on('pageChanged', ({ page, reason }) =>
log(`Requested page ${page} from the server (${reason})`),
);
const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
if (error) log('Load failed — press "Retry" in the pager');
else if (!loading) log(`Arrived: ${api.getPageInfo().totalRows} matching rows`);
});
return () => {
offPage();
offLoad();
};
}
// The control values are language-neutral keys; map them to the values in the table.
const COUNTRY_BY_KEY: Record<string, string> = {
kr: 'Korea',
us: 'USA',
jp: 'Japan',
cn: 'China',
gb: 'UK',
fr: 'France',
};
export const actions = {
query: (api: GridApi<Row>, value?: string) => {
state.query = (value ?? '').trim();
api.reloadPage();
},
country: (api: GridApi<Row>, value?: string) => {
state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
api.reloadPage();
},
// Deliberately fail the next request once.
failOnce: (api: GridApi<Row>) => {
failNext = true;
api.reloadPage();
},
};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">
<input
type="text"
aria-label="Search"
placeholder="e.g. Wireless"
:disabled="!api"
@input="api && actions.query(api, ($event.target as HTMLInputElement).value)"
/>
<select
aria-label="Country"
:disabled="!api"
@change="api && actions.country(api, ($event.target as HTMLSelectElement).value)"
>
<option value="all" selected>All</option>
<option value="kr">Korea</option>
<option value="us">USA</option>
<option value="jp">Japan</option>
<option value="cn">China</option>
<option value="gb">UK</option>
<option value="fr">France</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.failOnce(api)"
>Fail the next request</button>
</div>
<Grid style="height: 460px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, PageQuery, PageResult } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
customer: string;
country: string;
product: string;
amount: number;
}
const customers = [
'Harbor Logistics',
'Blue Sky Foods',
'Polaris Trading',
'Dawn Commerce',
'Sunrise Farm',
'Moda Fashion',
'Bright Electronics',
];
const countries = ['Korea', 'USA', 'Japan', 'China', 'UK', 'France'];
const products = [
'Wireless earbuds',
'Smart watch',
'Laptop stand',
'Power bank',
'Bluetooth speaker',
];
// Pretend the server holds 2,000 orders. Instead of a server, this example answers from memory after 0.4 seconds.
const ALL: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
customer: customers[i % 7] as string,
country: countries[(i * 5) % 6] as string,
product: products[(i * 7) % 5] as string,
amount: 29 + Math.round(((i * 7919) % 480000) / 1000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// In a real service this is a request like GET /orders?page=3&size=10&sort=amount,desc&q=...
// The grid only passes "which page, how many rows, what sort and filter", and the server returns that page's rows and the total count.
function fetchPage({ page, pageSize, sort, signal }: PageQuery): Promise<PageResult<Row>> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (failNext) {
failNext = false;
reject(new Error('The server is not responding'));
return;
}
let rows = ALL.filter(
(r) =>
(!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
(state.country === 'all' || r.country === state.country),
);
const first = sort[0];
if (first) {
const sign = first.direction === 'desc' ? -1 : 1;
const key = first.columnId as keyof Row;
rows = [...rows].sort((a, b) =>
typeof a[key] === 'number'
? sign * ((a[key] as number) - (b[key] as number))
: sign * String(a[key]).localeCompare(String(b[key]), 'en'),
);
}
resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
}, delay);
// When a newer request arrives, the grid cancels the previous one.
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('aborted', 'AbortError'));
});
});
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 150 },
{ id: 'country', title: 'Country', width: 100 },
{ id: 'product', title: 'Product', width: 170 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
pagination: {
mode: 'server',
pageSize: 10,
pageSizes: [10, 20],
loadPage: fetchPage,
jump: true,
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
delay = 400;
failNext = false;
state.query = '';
state.country = 'all';
const offPage = api.on('pageChanged', ({ page, reason }) =>
log(`Requested page ${page} from the server (${reason})`),
);
const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
if (error) log('Load failed — press "Retry" in the pager');
else if (!loading) log(`Arrived: ${api.getPageInfo().totalRows} matching rows`);
});
return () => {
offPage();
offLoad();
};
}
// The control values are language-neutral keys; map them to the values in the table.
const COUNTRY_BY_KEY: Record<string, string> = {
kr: 'Korea',
us: 'USA',
jp: 'Japan',
cn: 'China',
gb: 'UK',
fr: 'France',
};
export const actions = {
query: (api: GridApi<Row>, value?: string) => {
state.query = (value ?? '').trim();
api.reloadPage();
},
country: (api: GridApi<Row>, value?: string) => {
state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
api.reloadPage();
},
// Deliberately fail the next request once.
failOnce: (api: GridApi<Row>) => {
failNext = true;
api.reloadPage();
},
};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">
<input
type="text"
aria-label="Search"
placeholder="e.g. Wireless"
[disabled]="!api"
(input)="api && actions.query(api, $any($event.target).value)"
/>
<select
aria-label="Country"
[disabled]="!api"
(change)="api && actions.country(api, $any($event.target).value)"
>
<option value="all" selected>All</option>
<option value="kr">Korea</option>
<option value="us">USA</option>
<option value="jp">Japan</option>
<option value="cn">China</option>
<option value="gb">UK</option>
<option value="fr">France</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.failOnce(api)"
>Fail the next request</button>
</div>
<mx-grid style="height: 460px" [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, PageQuery, PageResult } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
customer: string;
country: string;
product: string;
amount: number;
}
const customers = [
'Harbor Logistics',
'Blue Sky Foods',
'Polaris Trading',
'Dawn Commerce',
'Sunrise Farm',
'Moda Fashion',
'Bright Electronics',
];
const countries = ['Korea', 'USA', 'Japan', 'China', 'UK', 'France'];
const products = [
'Wireless earbuds',
'Smart watch',
'Laptop stand',
'Power bank',
'Bluetooth speaker',
];
// Pretend the server holds 2,000 orders. Instead of a server, this example answers from memory after 0.4 seconds.
const ALL: Row[] = Array.from({ length: 2000 }, (_, i) => ({
id: i + 1,
customer: customers[i % 7] as string,
country: countries[(i * 5) % 6] as string,
product: products[(i * 7) % 5] as string,
amount: 29 + Math.round(((i * 7919) % 480000) / 1000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// In a real service this is a request like GET /orders?page=3&size=10&sort=amount,desc&q=...
// The grid only passes "which page, how many rows, what sort and filter", and the server returns that page's rows and the total count.
function fetchPage({ page, pageSize, sort, signal }: PageQuery): Promise<PageResult<Row>> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (failNext) {
failNext = false;
reject(new Error('The server is not responding'));
return;
}
let rows = ALL.filter(
(r) =>
(!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
(state.country === 'all' || r.country === state.country),
);
const first = sort[0];
if (first) {
const sign = first.direction === 'desc' ? -1 : 1;
const key = first.columnId as keyof Row;
rows = [...rows].sort((a, b) =>
typeof a[key] === 'number'
? sign * ((a[key] as number) - (b[key] as number))
: sign * String(a[key]).localeCompare(String(b[key]), 'en'),
);
}
resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
}, delay);
// When a newer request arrives, the grid cancels the previous one.
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('aborted', 'AbortError'));
});
});
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 150 },
{ id: 'country', title: 'Country', width: 100 },
{ id: 'product', title: 'Product', width: 170 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
pagination: {
mode: 'server',
pageSize: 10,
pageSizes: [10, 20],
loadPage: fetchPage,
jump: true,
},
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
delay = 400;
failNext = false;
state.query = '';
state.country = 'all';
const offPage = api.on('pageChanged', ({ page, reason }) =>
log(`Requested page ${page} from the server (${reason})`),
);
const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
if (error) log('Load failed — press "Retry" in the pager');
else if (!loading) log(`Arrived: ${api.getPageInfo().totalRows} matching rows`);
});
return () => {
offPage();
offLoad();
};
}
// The control values are language-neutral keys; map them to the values in the table.
const COUNTRY_BY_KEY: Record<string, string> = {
kr: 'Korea',
us: 'USA',
jp: 'Japan',
cn: 'China',
gb: 'UK',
fr: 'France',
};
export const actions = {
query: (api: GridApi<Row>, value?: string) => {
state.query = (value ?? '').trim();
api.reloadPage();
},
country: (api: GridApi<Row>, value?: string) => {
state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
api.reloadPage();
},
// Deliberately fail the next request once.
failOnce: (api: GridApi<Row>) => {
failNext = true;
api.reloadPage();
},
};