주소에서 받아 행으로 넣기(loadUrl)Load rows from an address (loadUrl)
loadUrl(url, options)는 주소의 JSON·CSV·XML을 받아 행으로 바꿔 넣어요. 형식은 Content-Type, 확장자 순으로 정하고 mode로 바꾸기·붙이기를 골라요. http·https만 받고 주소에 사용자 정보가 있거나 다른 출처이면(allowCrossOrigin 없이) 거절해요. 제한 시간·크기 상한·취소를 지원하고, 받는 동안 로딩 안내를 보이며 loadStarted·loadFinished·loadFailed 이벤트를 내요.loadUrl(url, options) fetches JSON, CSV or XML from an address and puts the rows into the grid. The format comes from Content-Type, then the extension, and mode picks replace or append. Only http and https are accepted, and an address with credentials or a cross-origin one (without allowCrossOrigin) is refused. It supports a timeout, a size limit and cancellation, shows the loading overlay while waiting, and emits loadStarted, loadFinished and loadFailed.
코드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)
이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="json">JSON 받기</button>
<button type="button" id="csv">CSV 붙이기</button>
<button type="button" id="html">HTML 응답</button>
<button type="button" id="missing">없는 주소</button>
<button type="button" id="size">크기 상한</button>
<button type="button" id="abort">중간에 취소</button>
<button type="button" id="cross">다른 출처</button>
</div>
<div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('json').addEventListener('click', () => actions.json(api));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('html').addEventListener('click', () => actions.html(api));
document.getElementById('missing').addEventListener('click', () => actions.missing(api));
document.getElementById('size').addEventListener('click', () => actions.size(api));
document.getElementById('abort').addEventListener('click', () => actions.abort(api));
document.getElementById('cross').addEventListener('click', () => actions.cross(api));import { withExport } from '@maxgrid/export';
const rows = [{ id: 0, name: '(예전 행)', dept: 'dev', joined: null, active: false }];
export const options = {
columns: [
{ id: 'id', title: '번호', kind: 'number', width: 70 },
{ id: 'name', title: '이름', width: 150 },
{
id: 'dept',
title: '부서',
kind: 'select',
width: 100,
editorOptions: [
{ value: 'dev', label: '개발' },
{ value: 'ops', label: '운영' },
],
optionLabel: (v) => (v === 'dev' ? '개발' : '운영'),
},
{ id: 'joined', title: '입사일', kind: 'date', width: 110 },
{ id: 'active', title: '재직', kind: 'boolean', width: 70 },
],
rows,
rowKey: 'id',
};
// 이 예제는 서버 대신 가짜 fetch를 loadUrl의 `fetch` 옵션으로 넘겨요(전역 fetch는 건드리지 않아요). 실제 앱에서는 옵션 없이 서버 주소를 쓰면 돼요.
// 미리보기 틀 안에서는 상대 주소를 풀 수 없으니 절대 주소를 쓰고 `allowCrossOrigin`을 켜요.
const BASE = 'https://demo.example';
const FAKE = {
'/people.json': {
type: 'application/json',
body: '[{"id":1,"name":"김하늘","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"이도윤","dept":"ops","joined":"2023-11-20","active":false}]',
},
'/people.csv': {
type: 'text/csv',
body: '번호,이름,부서,입사일,재직\n3,박서연,개발,2025.1.15,예\n4,최지우,운영,,아니오\n',
},
'/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
'/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input, init) => {
const hit = FAKE[new URL(String(input)).pathname];
await new Promise((resolve) => setTimeout(resolve, 600)); // 느린 서버
if (init?.signal?.aborted)
throw new DOMException('aborted', 'AbortError');
if (hit === undefined)
return new Response('', { status: 404 });
return new Response(hit.body, {
status: hit.status ?? 200,
headers: { 'content-type': hit.type },
});
});
let say = () => { };
let ex;
let pending;
export function setup(api, log) {
say = log;
ex = withExport(api);
const offs = [
api.on('loadStarted', (e) => log({ ko: `loadStarted ${e.url}`, en: `loadStarted ${e.url}` })),
api.on('loadFinished', (e) => log({ ko: `loadFinished ${e.count}행`, en: `loadFinished ${e.count} rows` })),
api.on('loadFailed', (e) => log({ ko: `loadFailed: ${e.message}`, en: `loadFailed: ${e.message}` })),
];
log({
ko: 'loadUrl(url)은 주소의 데이터를 받아 그리드에 넣어요. 받는 동안 "불러오는 중" 안내가 보여요.',
en: 'loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.',
});
return () => {
offs.forEach((off) => off());
pending?.abort();
};
}
async function run(url, opts = {}) {
try {
await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
}
catch (error) {
const e = error;
say({ ko: `실패(${e.code}): ${e.message}`, en: `Failed (${e.code}): ${e.message}` });
}
}
export const actions = {
json: () => run(`${BASE}/people.json`),
csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
html: () => run(`${BASE}/page.html`, { format: 'json' }),
missing: () => run(`${BASE}/missing.json`),
size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
abort: () => {
pending = new AbortController();
setTimeout(() => pending?.abort(), 250);
return run(`${BASE}/people.json`, { signal: pending.signal });
},
cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
}; 이 HTML은 추가 번들(위 script 태그)도 함께 불러오고 전역 변수로 써요. 별도 설치는 필요 없어요.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>주소에서 받아 행으로 넣기(loadUrl)</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="json">JSON 받기</button>
<button type="button" id="csv">CSV 붙이기</button>
<button type="button" id="html">HTML 응답</button>
<button type="button" id="missing">없는 주소</button>
<button type="button" id="size">크기 상한</button>
<button type="button" id="abort">중간에 취소</button>
<button type="button" id="cross">다른 출처</button>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script>
const { withExport } = MaxGridExport;
const rows = [{ id: 0, name: '(예전 행)', dept: 'dev', joined: null, active: false }];
const options = {
columns: [
{ id: 'id', title: '번호', kind: 'number', width: 70 },
{ id: 'name', title: '이름', width: 150 },
{
id: 'dept',
title: '부서',
kind: 'select',
width: 100,
editorOptions: [
{ value: 'dev', label: '개발' },
{ value: 'ops', label: '운영' },
],
optionLabel: (v) => (v === 'dev' ? '개발' : '운영'),
},
{ id: 'joined', title: '입사일', kind: 'date', width: 110 },
{ id: 'active', title: '재직', kind: 'boolean', width: 70 },
],
rows,
rowKey: 'id',
};
// 이 예제는 서버 대신 가짜 fetch를 loadUrl의 `fetch` 옵션으로 넘겨요(전역 fetch는 건드리지 않아요). 실제 앱에서는 옵션 없이 서버 주소를 쓰면 돼요.
// 미리보기 틀 안에서는 상대 주소를 풀 수 없으니 절대 주소를 쓰고 `allowCrossOrigin`을 켜요.
const BASE = 'https://demo.example';
const FAKE = {
'/people.json': {
type: 'application/json',
body: '[{"id":1,"name":"김하늘","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"이도윤","dept":"ops","joined":"2023-11-20","active":false}]',
},
'/people.csv': {
type: 'text/csv',
body: '번호,이름,부서,입사일,재직\n3,박서연,개발,2025.1.15,예\n4,최지우,운영,,아니오\n',
},
'/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
'/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input, init) => {
const hit = FAKE[new URL(String(input)).pathname];
await new Promise((resolve) => setTimeout(resolve, 600)); // 느린 서버
if (init?.signal?.aborted)
throw new DOMException('aborted', 'AbortError');
if (hit === undefined)
return new Response('', { status: 404 });
return new Response(hit.body, {
status: hit.status ?? 200,
headers: { 'content-type': hit.type },
});
});
let say = () => { };
let ex;
let pending;
function setup(api, log) {
say = log;
ex = withExport(api);
const offs = [
api.on('loadStarted', (e) => log({ ko: `loadStarted ${e.url}`, en: `loadStarted ${e.url}` })),
api.on('loadFinished', (e) => log({ ko: `loadFinished ${e.count}행`, en: `loadFinished ${e.count} rows` })),
api.on('loadFailed', (e) => log({ ko: `loadFailed: ${e.message}`, en: `loadFailed: ${e.message}` })),
];
log({
ko: 'loadUrl(url)은 주소의 데이터를 받아 그리드에 넣어요. 받는 동안 "불러오는 중" 안내가 보여요.',
en: 'loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.',
});
return () => {
offs.forEach((off) => off());
pending?.abort();
};
}
async function run(url, opts = {}) {
try {
await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
}
catch (error) {
const e = error;
say({ ko: `실패(${e.code}): ${e.message}`, en: `Failed (${e.code}): ${e.message}` });
}
}
const actions = {
json: () => run(`${BASE}/people.json`),
csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
html: () => run(`${BASE}/page.html`, { format: 'json' }),
missing: () => run(`${BASE}/missing.json`),
size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
abort: () => {
pending = new AbortController();
setTimeout(() => pending?.abort(), 250);
return run(`${BASE}/people.json`, { signal: pending.signal });
},
cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
};
options.ariaLabel = "주소에서 받아 행으로 넣기(loadUrl)";
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('json').addEventListener('click', () => actions.json(api));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('html').addEventListener('click', () => actions.html(api));
document.getElementById('missing').addEventListener('click', () => actions.missing(api));
document.getElementById('size').addEventListener('click', () => actions.size(api));
document.getElementById('abort').addEventListener('click', () => actions.abort(api));
document.getElementById('cross').addEventListener('click', () => actions.cross(api));
</script>
</body>
</html> 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/react @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 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.json(api)}
>JSON 받기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.csv(api)}
>CSV 붙이기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.html(api)}
>HTML 응답</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.missing(api)}
>없는 주소</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.size(api)}
>크기 상한</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.abort(api)}
>중간에 취소</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.cross(api)}
>다른 출처</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(예전 행)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '번호', kind: 'number', width: 70 },
{ id: 'name', title: '이름', width: 150 },
{
id: 'dept',
title: '부서',
kind: 'select',
width: 100,
editorOptions: [
{ value: 'dev', label: '개발' },
{ value: 'ops', label: '운영' },
],
optionLabel: (v) => (v === 'dev' ? '개발' : '운영'),
},
{ id: 'joined', title: '입사일', kind: 'date', width: 110 },
{ id: 'active', title: '재직', kind: 'boolean', width: 70 },
],
rows,
rowKey: 'id',
};
// 이 예제는 서버 대신 가짜 fetch를 loadUrl의 `fetch` 옵션으로 넘겨요(전역 fetch는 건드리지 않아요). 실제 앱에서는 옵션 없이 서버 주소를 쓰면 돼요.
// 미리보기 틀 안에서는 상대 주소를 풀 수 없으니 절대 주소를 쓰고 `allowCrossOrigin`을 켜요.
const BASE = 'https://demo.example';
const FAKE: Record<string, { type: string; body: string; status?: number }> = {
'/people.json': {
type: 'application/json',
body: '[{"id":1,"name":"김하늘","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"이도윤","dept":"ops","joined":"2023-11-20","active":false}]',
},
'/people.csv': {
type: 'text/csv',
body: '번호,이름,부서,입사일,재직\n3,박서연,개발,2025.1.15,예\n4,최지우,운영,,아니오\n',
},
'/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
'/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const hit = FAKE[new URL(String(input)).pathname];
await new Promise((resolve) => setTimeout(resolve, 600)); // 느린 서버
if (init?.signal?.aborted) throw new DOMException('aborted', 'AbortError');
if (hit === undefined) return new Response('', { status: 404 });
return new Response(hit.body, {
status: hit.status ?? 200,
headers: { 'content-type': hit.type },
});
}) as typeof fetch;
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let pending: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const offs = [
api.on('loadStarted', (e) => log({ ko: `loadStarted ${e.url}`, en: `loadStarted ${e.url}` })),
api.on('loadFinished', (e) =>
log({ ko: `loadFinished ${e.count}행`, en: `loadFinished ${e.count} rows` }),
),
api.on('loadFailed', (e) =>
log({ ko: `loadFailed: ${e.message}`, en: `loadFailed: ${e.message}` }),
),
];
log({
ko: 'loadUrl(url)은 주소의 데이터를 받아 그리드에 넣어요. 받는 동안 "불러오는 중" 안내가 보여요.',
en: 'loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.',
});
return () => {
offs.forEach((off) => off());
pending?.abort();
};
}
async function run(
url: string,
opts: Parameters<NonNullable<typeof ex>['loadUrl']>[1] = {},
): Promise<void> {
try {
await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
} catch (error) {
const e = error as Error & { code?: string };
say({ ko: `실패(${e.code}): ${e.message}`, en: `Failed (${e.code}): ${e.message}` });
}
}
export const actions = {
json: () => run(`${BASE}/people.json`),
csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
html: () => run(`${BASE}/page.html`, { format: 'json' }),
missing: () => run(`${BASE}/missing.json`),
size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
abort: () => {
pending = new AbortController();
setTimeout(() => pending?.abort(), 250);
return run(`${BASE}/people.json`, { signal: pending.signal });
},
cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/vue @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 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.json(api)">JSON 받기</button>
<button type="button" :disabled="!api" @click="api && actions.csv(api)">CSV 붙이기</button>
<button type="button" :disabled="!api" @click="api && actions.html(api)">HTML 응답</button>
<button type="button" :disabled="!api" @click="api && actions.missing(api)">없는 주소</button>
<button type="button" :disabled="!api" @click="api && actions.size(api)">크기 상한</button>
<button type="button" :disabled="!api" @click="api && actions.abort(api)">중간에 취소</button>
<button type="button" :disabled="!api" @click="api && actions.cross(api)">다른 출처</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(예전 행)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '번호', kind: 'number', width: 70 },
{ id: 'name', title: '이름', width: 150 },
{
id: 'dept',
title: '부서',
kind: 'select',
width: 100,
editorOptions: [
{ value: 'dev', label: '개발' },
{ value: 'ops', label: '운영' },
],
optionLabel: (v) => (v === 'dev' ? '개발' : '운영'),
},
{ id: 'joined', title: '입사일', kind: 'date', width: 110 },
{ id: 'active', title: '재직', kind: 'boolean', width: 70 },
],
rows,
rowKey: 'id',
};
// 이 예제는 서버 대신 가짜 fetch를 loadUrl의 `fetch` 옵션으로 넘겨요(전역 fetch는 건드리지 않아요). 실제 앱에서는 옵션 없이 서버 주소를 쓰면 돼요.
// 미리보기 틀 안에서는 상대 주소를 풀 수 없으니 절대 주소를 쓰고 `allowCrossOrigin`을 켜요.
const BASE = 'https://demo.example';
const FAKE: Record<string, { type: string; body: string; status?: number }> = {
'/people.json': {
type: 'application/json',
body: '[{"id":1,"name":"김하늘","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"이도윤","dept":"ops","joined":"2023-11-20","active":false}]',
},
'/people.csv': {
type: 'text/csv',
body: '번호,이름,부서,입사일,재직\n3,박서연,개발,2025.1.15,예\n4,최지우,운영,,아니오\n',
},
'/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
'/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const hit = FAKE[new URL(String(input)).pathname];
await new Promise((resolve) => setTimeout(resolve, 600)); // 느린 서버
if (init?.signal?.aborted) throw new DOMException('aborted', 'AbortError');
if (hit === undefined) return new Response('', { status: 404 });
return new Response(hit.body, {
status: hit.status ?? 200,
headers: { 'content-type': hit.type },
});
}) as typeof fetch;
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let pending: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const offs = [
api.on('loadStarted', (e) => log({ ko: `loadStarted ${e.url}`, en: `loadStarted ${e.url}` })),
api.on('loadFinished', (e) =>
log({ ko: `loadFinished ${e.count}행`, en: `loadFinished ${e.count} rows` }),
),
api.on('loadFailed', (e) =>
log({ ko: `loadFailed: ${e.message}`, en: `loadFailed: ${e.message}` }),
),
];
log({
ko: 'loadUrl(url)은 주소의 데이터를 받아 그리드에 넣어요. 받는 동안 "불러오는 중" 안내가 보여요.',
en: 'loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.',
});
return () => {
offs.forEach((off) => off());
pending?.abort();
};
}
async function run(
url: string,
opts: Parameters<NonNullable<typeof ex>['loadUrl']>[1] = {},
): Promise<void> {
try {
await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
} catch (error) {
const e = error as Error & { code?: string };
say({ ko: `실패(${e.code}): ${e.message}`, en: `Failed (${e.code}): ${e.message}` });
}
}
export const actions = {
json: () => run(`${BASE}/people.json`),
csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
html: () => run(`${BASE}/page.html`, { format: 'json' }),
missing: () => run(`${BASE}/missing.json`),
size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
abort: () => {
pending = new AbortController();
setTimeout(() => pending?.abort(), 250);
return run(`${BASE}/people.json`, { signal: pending.signal });
},
cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/angular @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 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.json(api)"
>JSON 받기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.csv(api)"
>CSV 붙이기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.html(api)"
>HTML 응답</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.missing(api)"
>없는 주소</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.size(api)"
>크기 상한</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.abort(api)"
>중간에 취소</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.cross(api)"
>다른 출처</button>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(예전 행)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '번호', kind: 'number', width: 70 },
{ id: 'name', title: '이름', width: 150 },
{
id: 'dept',
title: '부서',
kind: 'select',
width: 100,
editorOptions: [
{ value: 'dev', label: '개발' },
{ value: 'ops', label: '운영' },
],
optionLabel: (v) => (v === 'dev' ? '개발' : '운영'),
},
{ id: 'joined', title: '입사일', kind: 'date', width: 110 },
{ id: 'active', title: '재직', kind: 'boolean', width: 70 },
],
rows,
rowKey: 'id',
};
// 이 예제는 서버 대신 가짜 fetch를 loadUrl의 `fetch` 옵션으로 넘겨요(전역 fetch는 건드리지 않아요). 실제 앱에서는 옵션 없이 서버 주소를 쓰면 돼요.
// 미리보기 틀 안에서는 상대 주소를 풀 수 없으니 절대 주소를 쓰고 `allowCrossOrigin`을 켜요.
const BASE = 'https://demo.example';
const FAKE: Record<string, { type: string; body: string; status?: number }> = {
'/people.json': {
type: 'application/json',
body: '[{"id":1,"name":"김하늘","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"이도윤","dept":"ops","joined":"2023-11-20","active":false}]',
},
'/people.csv': {
type: 'text/csv',
body: '번호,이름,부서,입사일,재직\n3,박서연,개발,2025.1.15,예\n4,최지우,운영,,아니오\n',
},
'/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
'/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const hit = FAKE[new URL(String(input)).pathname];
await new Promise((resolve) => setTimeout(resolve, 600)); // 느린 서버
if (init?.signal?.aborted) throw new DOMException('aborted', 'AbortError');
if (hit === undefined) return new Response('', { status: 404 });
return new Response(hit.body, {
status: hit.status ?? 200,
headers: { 'content-type': hit.type },
});
}) as typeof fetch;
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let pending: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const offs = [
api.on('loadStarted', (e) => log({ ko: `loadStarted ${e.url}`, en: `loadStarted ${e.url}` })),
api.on('loadFinished', (e) =>
log({ ko: `loadFinished ${e.count}행`, en: `loadFinished ${e.count} rows` }),
),
api.on('loadFailed', (e) =>
log({ ko: `loadFailed: ${e.message}`, en: `loadFailed: ${e.message}` }),
),
];
log({
ko: 'loadUrl(url)은 주소의 데이터를 받아 그리드에 넣어요. 받는 동안 "불러오는 중" 안내가 보여요.',
en: 'loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.',
});
return () => {
offs.forEach((off) => off());
pending?.abort();
};
}
async function run(
url: string,
opts: Parameters<NonNullable<typeof ex>['loadUrl']>[1] = {},
): Promise<void> {
try {
await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
} catch (error) {
const e = error as Error & { code?: string };
say({ ko: `실패(${e.code}): ${e.message}`, en: `Failed (${e.code}): ${e.message}` });
}
}
export const actions = {
json: () => run(`${BASE}/people.json`),
csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
html: () => run(`${BASE}/page.html`, { format: 'json' }),
missing: () => run(`${BASE}/missing.json`),
size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
abort: () => {
pending = new AbortController();
setTimeout(() => pending?.abort(), 250);
return run(`${BASE}/people.json`, { signal: pending.signal });
},
cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
}; This example needs an extra package. To run it locally, install with npm i maxgrid @maxgrid/export.
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="json">Load JSON</button>
<button type="button" id="csv">Append CSV</button>
<button type="button" id="html">HTML response</button>
<button type="button" id="missing">Missing address</button>
<button type="button" id="size">Size limit</button>
<button type="button" id="abort">Cancel midway</button>
<button type="button" id="cross">Cross-origin</button>
</div>
<div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('json').addEventListener('click', () => actions.json(api));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('html').addEventListener('click', () => actions.html(api));
document.getElementById('missing').addEventListener('click', () => actions.missing(api));
document.getElementById('size').addEventListener('click', () => actions.size(api));
document.getElementById('abort').addEventListener('click', () => actions.abort(api));
document.getElementById('cross').addEventListener('click', () => actions.cross(api));import { withExport } from '@maxgrid/export';
const rows = [{ id: 0, name: '(old row)', dept: 'dev', joined: null, active: false }];
export const options = {
columns: [
{ id: 'id', title: 'No.', kind: 'number', width: 70 },
{ id: 'name', title: 'Name', width: 150 },
{
id: 'dept',
title: 'Department',
kind: 'select',
width: 120,
editorOptions: [
{ value: 'dev', label: 'Dev' },
{ value: 'ops', label: 'Ops' },
],
optionLabel: (v) => (v === 'dev' ? 'Dev' : 'Ops'),
},
{ id: 'joined', title: 'Joined', kind: 'date', width: 110 },
{ id: 'active', title: 'Active', kind: 'boolean', width: 80 },
],
rows,
rowKey: 'id',
};
// This example passes a fake fetch to loadUrl through its `fetch` option instead of a server (the global fetch is untouched). A real app uses a server address without the option.
// A relative address cannot be resolved inside the preview frame, so use an absolute address and turn on `allowCrossOrigin`.
const BASE = 'https://demo.example';
const FAKE = {
'/people.json': {
type: 'application/json',
body: '[{"id":1,"name":"Emma Stone","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"Liam Carter","dept":"ops","joined":"2023-11-20","active":false}]',
},
'/people.csv': {
type: 'text/csv',
body: 'No.,Name,Department,Joined,Active\n3,Noah Reed,Dev,2025.1.15,Yes\n4,Olivia Hayes,Ops,,No\n',
},
'/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
'/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input, init) => {
const hit = FAKE[new URL(String(input)).pathname];
await new Promise((resolve) => setTimeout(resolve, 600)); // a slow server
if (init?.signal?.aborted)
throw new DOMException('aborted', 'AbortError');
if (hit === undefined)
return new Response('', { status: 404 });
return new Response(hit.body, {
status: hit.status ?? 200,
headers: { 'content-type': hit.type },
});
});
let say = () => { };
let ex;
let pending;
export function setup(api, log) {
say = log;
ex = withExport(api);
const offs = [
api.on('loadStarted', (e) => log(`loadStarted ${e.url}`)),
api.on('loadFinished', (e) => log(`loadFinished ${e.count} rows`)),
api.on('loadFailed', (e) => log(`loadFailed: ${e.message}`)),
];
log('loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.');
return () => {
offs.forEach((off) => off());
pending?.abort();
};
}
async function run(url, opts = {}) {
try {
await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
}
catch (error) {
const e = error;
say(`Failed (${e.code}): ${e.message}`);
}
}
export const actions = {
json: () => run(`${BASE}/people.json`),
csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
html: () => run(`${BASE}/page.html`, { format: 'json' }),
missing: () => run(`${BASE}/missing.json`),
size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
abort: () => {
pending = new AbortController();
setTimeout(() => pending?.abort(), 250);
return run(`${BASE}/people.json`, { signal: pending.signal });
},
cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
};This HTML also loads an extra bundle (the extra script tag above) and uses it as a global. No install is needed.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Load rows from an address (loadUrl)</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="json">Load JSON</button>
<button type="button" id="csv">Append CSV</button>
<button type="button" id="html">HTML response</button>
<button type="button" id="missing">Missing address</button>
<button type="button" id="size">Size limit</button>
<button type="button" id="abort">Cancel midway</button>
<button type="button" id="cross">Cross-origin</button>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script>
const { withExport } = MaxGridExport;
const rows = [{ id: 0, name: '(old row)', dept: 'dev', joined: null, active: false }];
const options = {
columns: [
{ id: 'id', title: 'No.', kind: 'number', width: 70 },
{ id: 'name', title: 'Name', width: 150 },
{
id: 'dept',
title: 'Department',
kind: 'select',
width: 120,
editorOptions: [
{ value: 'dev', label: 'Dev' },
{ value: 'ops', label: 'Ops' },
],
optionLabel: (v) => (v === 'dev' ? 'Dev' : 'Ops'),
},
{ id: 'joined', title: 'Joined', kind: 'date', width: 110 },
{ id: 'active', title: 'Active', kind: 'boolean', width: 80 },
],
rows,
rowKey: 'id',
};
// This example passes a fake fetch to loadUrl through its `fetch` option instead of a server (the global fetch is untouched). A real app uses a server address without the option.
// A relative address cannot be resolved inside the preview frame, so use an absolute address and turn on `allowCrossOrigin`.
const BASE = 'https://demo.example';
const FAKE = {
'/people.json': {
type: 'application/json',
body: '[{"id":1,"name":"Emma Stone","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"Liam Carter","dept":"ops","joined":"2023-11-20","active":false}]',
},
'/people.csv': {
type: 'text/csv',
body: 'No.,Name,Department,Joined,Active\n3,Noah Reed,Dev,2025.1.15,Yes\n4,Olivia Hayes,Ops,,No\n',
},
'/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
'/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input, init) => {
const hit = FAKE[new URL(String(input)).pathname];
await new Promise((resolve) => setTimeout(resolve, 600)); // a slow server
if (init?.signal?.aborted)
throw new DOMException('aborted', 'AbortError');
if (hit === undefined)
return new Response('', { status: 404 });
return new Response(hit.body, {
status: hit.status ?? 200,
headers: { 'content-type': hit.type },
});
});
let say = () => { };
let ex;
let pending;
function setup(api, log) {
say = log;
ex = withExport(api);
const offs = [
api.on('loadStarted', (e) => log(`loadStarted ${e.url}`)),
api.on('loadFinished', (e) => log(`loadFinished ${e.count} rows`)),
api.on('loadFailed', (e) => log(`loadFailed: ${e.message}`)),
];
log('loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.');
return () => {
offs.forEach((off) => off());
pending?.abort();
};
}
async function run(url, opts = {}) {
try {
await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
}
catch (error) {
const e = error;
say(`Failed (${e.code}): ${e.message}`);
}
}
const actions = {
json: () => run(`${BASE}/people.json`),
csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
html: () => run(`${BASE}/page.html`, { format: 'json' }),
missing: () => run(`${BASE}/missing.json`),
size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
abort: () => {
pending = new AbortController();
setTimeout(() => pending?.abort(), 250);
return run(`${BASE}/people.json`, { signal: pending.signal });
},
cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
};
options.ariaLabel = "Load rows from an address (loadUrl)";
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('json').addEventListener('click', () => actions.json(api));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('html').addEventListener('click', () => actions.html(api));
document.getElementById('missing').addEventListener('click', () => actions.missing(api));
document.getElementById('size').addEventListener('click', () => actions.size(api));
document.getElementById('abort').addEventListener('click', () => actions.abort(api));
document.getElementById('cross').addEventListener('click', () => actions.cross(api));
</script>
</body>
</html> This example needs an extra package. To run it locally, install with npm i @maxgrid/react @maxgrid/export.
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.json(api)}
>Load JSON</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.csv(api)}
>Append CSV</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.html(api)}
>HTML response</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.missing(api)}
>Missing address</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.size(api)}
>Size limit</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.abort(api)}
>Cancel midway</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.cross(api)}
>Cross-origin</button>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(old row)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'No.', kind: 'number', width: 70 },
{ id: 'name', title: 'Name', width: 150 },
{
id: 'dept',
title: 'Department',
kind: 'select',
width: 120,
editorOptions: [
{ value: 'dev', label: 'Dev' },
{ value: 'ops', label: 'Ops' },
],
optionLabel: (v) => (v === 'dev' ? 'Dev' : 'Ops'),
},
{ id: 'joined', title: 'Joined', kind: 'date', width: 110 },
{ id: 'active', title: 'Active', kind: 'boolean', width: 80 },
],
rows,
rowKey: 'id',
};
// This example passes a fake fetch to loadUrl through its `fetch` option instead of a server (the global fetch is untouched). A real app uses a server address without the option.
// A relative address cannot be resolved inside the preview frame, so use an absolute address and turn on `allowCrossOrigin`.
const BASE = 'https://demo.example';
const FAKE: Record<string, { type: string; body: string; status?: number }> = {
'/people.json': {
type: 'application/json',
body: '[{"id":1,"name":"Emma Stone","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"Liam Carter","dept":"ops","joined":"2023-11-20","active":false}]',
},
'/people.csv': {
type: 'text/csv',
body: 'No.,Name,Department,Joined,Active\n3,Noah Reed,Dev,2025.1.15,Yes\n4,Olivia Hayes,Ops,,No\n',
},
'/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
'/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const hit = FAKE[new URL(String(input)).pathname];
await new Promise((resolve) => setTimeout(resolve, 600)); // a slow server
if (init?.signal?.aborted) throw new DOMException('aborted', 'AbortError');
if (hit === undefined) return new Response('', { status: 404 });
return new Response(hit.body, {
status: hit.status ?? 200,
headers: { 'content-type': hit.type },
});
}) as typeof fetch;
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let pending: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const offs = [
api.on('loadStarted', (e) => log(`loadStarted ${e.url}`)),
api.on('loadFinished', (e) => log(`loadFinished ${e.count} rows`)),
api.on('loadFailed', (e) => log(`loadFailed: ${e.message}`)),
];
log(
'loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.',
);
return () => {
offs.forEach((off) => off());
pending?.abort();
};
}
async function run(
url: string,
opts: Parameters<NonNullable<typeof ex>['loadUrl']>[1] = {},
): Promise<void> {
try {
await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
} catch (error) {
const e = error as Error & { code?: string };
say(`Failed (${e.code}): ${e.message}`);
}
}
export const actions = {
json: () => run(`${BASE}/people.json`),
csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
html: () => run(`${BASE}/page.html`, { format: 'json' }),
missing: () => run(`${BASE}/missing.json`),
size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
abort: () => {
pending = new AbortController();
setTimeout(() => pending?.abort(), 250);
return run(`${BASE}/people.json`, { signal: pending.signal });
},
cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/vue @maxgrid/export.
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.json(api)">Load JSON</button>
<button type="button" :disabled="!api" @click="api && actions.csv(api)">Append CSV</button>
<button type="button" :disabled="!api" @click="api && actions.html(api)">HTML response</button>
<button type="button" :disabled="!api" @click="api && actions.missing(api)">Missing address</button>
<button type="button" :disabled="!api" @click="api && actions.size(api)">Size limit</button>
<button type="button" :disabled="!api" @click="api && actions.abort(api)">Cancel midway</button>
<button type="button" :disabled="!api" @click="api && actions.cross(api)">Cross-origin</button>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(old row)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'No.', kind: 'number', width: 70 },
{ id: 'name', title: 'Name', width: 150 },
{
id: 'dept',
title: 'Department',
kind: 'select',
width: 120,
editorOptions: [
{ value: 'dev', label: 'Dev' },
{ value: 'ops', label: 'Ops' },
],
optionLabel: (v) => (v === 'dev' ? 'Dev' : 'Ops'),
},
{ id: 'joined', title: 'Joined', kind: 'date', width: 110 },
{ id: 'active', title: 'Active', kind: 'boolean', width: 80 },
],
rows,
rowKey: 'id',
};
// This example passes a fake fetch to loadUrl through its `fetch` option instead of a server (the global fetch is untouched). A real app uses a server address without the option.
// A relative address cannot be resolved inside the preview frame, so use an absolute address and turn on `allowCrossOrigin`.
const BASE = 'https://demo.example';
const FAKE: Record<string, { type: string; body: string; status?: number }> = {
'/people.json': {
type: 'application/json',
body: '[{"id":1,"name":"Emma Stone","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"Liam Carter","dept":"ops","joined":"2023-11-20","active":false}]',
},
'/people.csv': {
type: 'text/csv',
body: 'No.,Name,Department,Joined,Active\n3,Noah Reed,Dev,2025.1.15,Yes\n4,Olivia Hayes,Ops,,No\n',
},
'/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
'/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const hit = FAKE[new URL(String(input)).pathname];
await new Promise((resolve) => setTimeout(resolve, 600)); // a slow server
if (init?.signal?.aborted) throw new DOMException('aborted', 'AbortError');
if (hit === undefined) return new Response('', { status: 404 });
return new Response(hit.body, {
status: hit.status ?? 200,
headers: { 'content-type': hit.type },
});
}) as typeof fetch;
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let pending: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const offs = [
api.on('loadStarted', (e) => log(`loadStarted ${e.url}`)),
api.on('loadFinished', (e) => log(`loadFinished ${e.count} rows`)),
api.on('loadFailed', (e) => log(`loadFailed: ${e.message}`)),
];
log(
'loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.',
);
return () => {
offs.forEach((off) => off());
pending?.abort();
};
}
async function run(
url: string,
opts: Parameters<NonNullable<typeof ex>['loadUrl']>[1] = {},
): Promise<void> {
try {
await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
} catch (error) {
const e = error as Error & { code?: string };
say(`Failed (${e.code}): ${e.message}`);
}
}
export const actions = {
json: () => run(`${BASE}/people.json`),
csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
html: () => run(`${BASE}/page.html`, { format: 'json' }),
missing: () => run(`${BASE}/missing.json`),
size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
abort: () => {
pending = new AbortController();
setTimeout(() => pending?.abort(), 250);
return run(`${BASE}/people.json`, { signal: pending.signal });
},
cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/angular @maxgrid/export.
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.json(api)"
>Load JSON</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.csv(api)"
>Append CSV</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.html(api)"
>HTML response</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.missing(api)"
>Missing address</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.size(api)"
>Size limit</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.abort(api)"
>Cancel midway</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.cross(api)"
>Cross-origin</button>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import { withExport, type ExportableGridApi } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
joined: string | null;
active: boolean;
}
const rows: Row[] = [{ id: 0, name: '(old row)', dept: 'dev', joined: null, active: false }];
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'No.', kind: 'number', width: 70 },
{ id: 'name', title: 'Name', width: 150 },
{
id: 'dept',
title: 'Department',
kind: 'select',
width: 120,
editorOptions: [
{ value: 'dev', label: 'Dev' },
{ value: 'ops', label: 'Ops' },
],
optionLabel: (v) => (v === 'dev' ? 'Dev' : 'Ops'),
},
{ id: 'joined', title: 'Joined', kind: 'date', width: 110 },
{ id: 'active', title: 'Active', kind: 'boolean', width: 80 },
],
rows,
rowKey: 'id',
};
// This example passes a fake fetch to loadUrl through its `fetch` option instead of a server (the global fetch is untouched). A real app uses a server address without the option.
// A relative address cannot be resolved inside the preview frame, so use an absolute address and turn on `allowCrossOrigin`.
const BASE = 'https://demo.example';
const FAKE: Record<string, { type: string; body: string; status?: number }> = {
'/people.json': {
type: 'application/json',
body: '[{"id":1,"name":"Emma Stone","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"Liam Carter","dept":"ops","joined":"2023-11-20","active":false}]',
},
'/people.csv': {
type: 'text/csv',
body: 'No.,Name,Department,Joined,Active\n3,Noah Reed,Dev,2025.1.15,Yes\n4,Olivia Hayes,Ops,,No\n',
},
'/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
'/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const hit = FAKE[new URL(String(input)).pathname];
await new Promise((resolve) => setTimeout(resolve, 600)); // a slow server
if (init?.signal?.aborted) throw new DOMException('aborted', 'AbortError');
if (hit === undefined) return new Response('', { status: 404 });
return new Response(hit.body, {
status: hit.status ?? 200,
headers: { 'content-type': hit.type },
});
}) as typeof fetch;
let say: (message: LogText) => void = () => {};
let ex: ExportableGridApi<Row> | undefined;
let pending: AbortController | undefined;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
ex = withExport(api);
const offs = [
api.on('loadStarted', (e) => log(`loadStarted ${e.url}`)),
api.on('loadFinished', (e) => log(`loadFinished ${e.count} rows`)),
api.on('loadFailed', (e) => log(`loadFailed: ${e.message}`)),
];
log(
'loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.',
);
return () => {
offs.forEach((off) => off());
pending?.abort();
};
}
async function run(
url: string,
opts: Parameters<NonNullable<typeof ex>['loadUrl']>[1] = {},
): Promise<void> {
try {
await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
} catch (error) {
const e = error as Error & { code?: string };
say(`Failed (${e.code}): ${e.message}`);
}
}
export const actions = {
json: () => run(`${BASE}/people.json`),
csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
html: () => run(`${BASE}/page.html`, { format: 'json' }),
missing: () => run(`${BASE}/missing.json`),
size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
abort: () => {
pending = new AbortController();
setTimeout(() => pending?.abort(), 250);
return run(`${BASE}/people.json`, { signal: pending.signal });
},
cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
};