내가 맞춘 표 모양 기억해 두기Remember the table layout you set
컬럼 순서·너비·숨김·고정과 정렬, 보고 있던 위치를 저장했다가 다시 열 때 그대로 되돌려요. 이 예제는 브라우저 안에 저장하지만 서버 DB에 저장해도 같은 방식이에요.Save column order, width, visibility and pinning plus sorting and scroll position, and restore them next time. This demo uses localStorage, but a server database works the same way.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="hideCity">지역 숨기기</button>
<button type="button" id="pinName">이름 왼쪽 고정</button>
<button type="button" id="sortPrice">가격 높은 순</button>
<button type="button" id="save">상태 저장</button>
<button type="button" id="load">저장한 상태로</button>
<button type="button" id="clear">저장 지우고 처음으로</button>
</div>
<div id="grid" style="height: 340px"></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('hideCity').addEventListener('click', () => actions.hideCity(api));
document.getElementById('pinName').addEventListener('click', () => actions.pinName(api));
document.getElementById('sortPrice').addEventListener('click', () => actions.sortPrice(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('load').addEventListener('click', () => actions.load(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const names = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후', '윤서아', '임태민'];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전'];
const products = ['무선 이어폰', '노트북 14형', '스마트워치', '태블릿 11형', '보조배터리'];
const colors = ['블랙', '화이트', '실버', '네이비', '핑크'];
const rows = Array.from({ length: 60 }, (_, i) => ({
id: i + 1,
name: names[(i * 3) % names.length],
city: cities[(i * 5) % cities.length],
product: products[(i * 2 + (i >> 2)) % products.length],
color: colors[(i * 7) % colors.length],
quantity: 1 + ((i * 7) % 9),
price: 29000 + ((i * 7919) % 40) * 10000,
}));
export const options = {
columns: [
{ id: 'name', title: '이름', width: 100 },
{ id: 'city', title: '지역', width: 90 },
{ id: 'product', title: '상품', width: 140 },
{ id: 'color', title: '색상', width: 90 },
{ id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
{
id: 'price',
title: '가격',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
],
rows,
rowKey: 'id',
rowHeight: 32,
};
const KEY = 'maxgrid-example-grid-state';
let say = () => { };
let initial = [];
let memory = null; // 브라우저 저장소를 못 쓰는 환경(미리보기 화면 등)에서는 메모리에 둬요.
function read() {
try {
return localStorage.getItem(KEY) ?? memory;
}
catch {
return memory;
}
}
function write(text) {
memory = text;
try {
if (text === null)
localStorage.removeItem(KEY);
else
localStorage.setItem(KEY, text);
}
catch {
say({
ko: '이 화면에서는 브라우저 저장소를 못 써서, 페이지를 닫기 전까지만 기억해요.',
en: 'Browser storage is unavailable here, so the state is remembered only until you close the page.',
});
}
}
function restore(api) {
const text = read();
if (!text)
return false;
try {
const state = JSON.parse(text);
api.setColumnState(state.columns);
api.setSortModel(state.sort);
// 컬럼과 정렬을 먼저 적용한 뒤, 화면이 다시 그려진 다음에 스크롤 위치를 되돌려요.
requestAnimationFrame(() => requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })));
return true;
}
catch (error) {
// 깨진 값 때문에 화면이 멈추면 안 돼요. 알리고 기본 상태로 둬요.
say({
ko: `저장된 상태가 올바르지 않아 무시했어요: ${String(error)}`,
en: `Ignored the saved state because it is not valid: ${String(error)}`,
});
return false;
}
}
export function setup(api, log) {
say = log;
initial = api.getColumnState();
log({
ko: restore(api)
? '저장된 상태를 불러왔어요.'
: '저장된 상태가 없어요. 컬럼을 끌어 옮기거나 너비를 바꾼 뒤 "상태 저장"을 눌러 보세요.',
en: restore(api)
? 'Saved state restored.'
: 'No saved state. Drag a column or change a width, then press "Save state".',
});
}
export const actions = {
save: (api) => {
const state = {
columns: api.getColumnState(),
sort: api.getSortModel(),
scroll: api.getScroll(),
};
write(JSON.stringify(state));
say({
ko: `저장했어요: 컬럼 ${state.columns.length}개, 정렬 ${state.sort.length}개, 스크롤 ${Math.round(state.scroll.top)}px`,
en: `Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`,
});
},
load: (api) => say({
ko: restore(api) ? '저장된 상태로 되돌렸어요.' : '저장된 상태가 없어요.',
en: restore(api) ? 'Went back to the saved state.' : 'No saved state.',
}),
clear: (api) => {
write(null);
api.setColumnState(initial);
api.setSortModel([]);
api.setScroll({ top: 0, left: 0 });
say({
ko: '저장된 상태를 지우고 처음 모양으로 되돌렸어요.',
en: 'Cleared the saved state and went back to the starting layout.',
});
},
hideCity: (api) => api.setColumnVisible('city', false),
pinName: (api) => api.pinColumn('name', 'start'),
sortPrice: (api) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>내가 맞춘 표 모양 기억해 두기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="hideCity">지역 숨기기</button>
<button type="button" id="pinName">이름 왼쪽 고정</button>
<button type="button" id="sortPrice">가격 높은 순</button>
<button type="button" id="save">상태 저장</button>
<button type="button" id="load">저장한 상태로</button>
<button type="button" id="clear">저장 지우고 처음으로</button>
</div>
<div id="grid" style="height: 340px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후', '윤서아', '임태민'];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전'];
const products = ['무선 이어폰', '노트북 14형', '스마트워치', '태블릿 11형', '보조배터리'];
const colors = ['블랙', '화이트', '실버', '네이비', '핑크'];
const rows = Array.from({ length: 60 }, (_, i) => ({
id: i + 1,
name: names[(i * 3) % names.length],
city: cities[(i * 5) % cities.length],
product: products[(i * 2 + (i >> 2)) % products.length],
color: colors[(i * 7) % colors.length],
quantity: 1 + ((i * 7) % 9),
price: 29000 + ((i * 7919) % 40) * 10000,
}));
const options = {
columns: [
{ id: 'name', title: '이름', width: 100 },
{ id: 'city', title: '지역', width: 90 },
{ id: 'product', title: '상품', width: 140 },
{ id: 'color', title: '색상', width: 90 },
{ id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
{
id: 'price',
title: '가격',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
],
rows,
rowKey: 'id',
rowHeight: 32,
};
const KEY = 'maxgrid-example-grid-state';
let say = () => { };
let initial = [];
let memory = null; // 브라우저 저장소를 못 쓰는 환경(미리보기 화면 등)에서는 메모리에 둬요.
function read() {
try {
return localStorage.getItem(KEY) ?? memory;
}
catch {
return memory;
}
}
function write(text) {
memory = text;
try {
if (text === null)
localStorage.removeItem(KEY);
else
localStorage.setItem(KEY, text);
}
catch {
say({
ko: '이 화면에서는 브라우저 저장소를 못 써서, 페이지를 닫기 전까지만 기억해요.',
en: 'Browser storage is unavailable here, so the state is remembered only until you close the page.',
});
}
}
function restore(api) {
const text = read();
if (!text)
return false;
try {
const state = JSON.parse(text);
api.setColumnState(state.columns);
api.setSortModel(state.sort);
// 컬럼과 정렬을 먼저 적용한 뒤, 화면이 다시 그려진 다음에 스크롤 위치를 되돌려요.
requestAnimationFrame(() => requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })));
return true;
}
catch (error) {
// 깨진 값 때문에 화면이 멈추면 안 돼요. 알리고 기본 상태로 둬요.
say({
ko: `저장된 상태가 올바르지 않아 무시했어요: ${String(error)}`,
en: `Ignored the saved state because it is not valid: ${String(error)}`,
});
return false;
}
}
function setup(api, log) {
say = log;
initial = api.getColumnState();
log({
ko: restore(api)
? '저장된 상태를 불러왔어요.'
: '저장된 상태가 없어요. 컬럼을 끌어 옮기거나 너비를 바꾼 뒤 "상태 저장"을 눌러 보세요.',
en: restore(api)
? 'Saved state restored.'
: 'No saved state. Drag a column or change a width, then press "Save state".',
});
}
const actions = {
save: (api) => {
const state = {
columns: api.getColumnState(),
sort: api.getSortModel(),
scroll: api.getScroll(),
};
write(JSON.stringify(state));
say({
ko: `저장했어요: 컬럼 ${state.columns.length}개, 정렬 ${state.sort.length}개, 스크롤 ${Math.round(state.scroll.top)}px`,
en: `Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`,
});
},
load: (api) => say({
ko: restore(api) ? '저장된 상태로 되돌렸어요.' : '저장된 상태가 없어요.',
en: restore(api) ? 'Went back to the saved state.' : 'No saved state.',
}),
clear: (api) => {
write(null);
api.setColumnState(initial);
api.setSortModel([]);
api.setScroll({ top: 0, left: 0 });
say({
ko: '저장된 상태를 지우고 처음 모양으로 되돌렸어요.',
en: 'Cleared the saved state and went back to the starting layout.',
});
},
hideCity: (api) => api.setColumnVisible('city', false),
pinName: (api) => api.pinColumn('name', 'start'),
sortPrice: (api) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};
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('hideCity').addEventListener('click', () => actions.hideCity(api));
document.getElementById('pinName').addEventListener('click', () => actions.pinName(api));
document.getElementById('sortPrice').addEventListener('click', () => actions.sortPrice(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('load').addEventListener('click', () => actions.load(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.hideCity(api)}
>지역 숨기기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pinName(api)}
>이름 왼쪽 고정</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.sortPrice(api)}
>가격 높은 순</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>상태 저장</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.load(api)}
>저장한 상태로</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>저장 지우고 처음으로</button>
</div>
<Grid style={{ height: 340 }} ref={gridRef} options={options} />
</>
);
}import type { ColumnState, GridApi, GridOptions, SortItem } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
city: string;
product: string;
color: string;
quantity: number;
price: number;
}
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후', '윤서아', '임태민'];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전'];
const products = ['무선 이어폰', '노트북 14형', '스마트워치', '태블릿 11형', '보조배터리'];
const colors = ['블랙', '화이트', '실버', '네이비', '핑크'];
const rows: Row[] = Array.from({ length: 60 }, (_, i) => ({
id: i + 1,
name: names[(i * 3) % names.length],
city: cities[(i * 5) % cities.length],
product: products[(i * 2 + (i >> 2)) % products.length],
color: colors[(i * 7) % colors.length],
quantity: 1 + ((i * 7) % 9),
price: 29000 + ((i * 7919) % 40) * 10000,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 100 },
{ id: 'city', title: '지역', width: 90 },
{ id: 'product', title: '상품', width: 140 },
{ id: 'color', title: '색상', width: 90 },
{ id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
{
id: 'price',
title: '가격',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
],
rows,
rowKey: 'id',
rowHeight: 32,
};
// 저장하는 것: 컬럼 순서·너비·숨김·고정(getColumnState), 정렬, 스크롤 위치(getScroll).
interface SavedState {
columns: ColumnState[];
sort: SortItem[];
scroll: { top: number; left: number }; // 스크롤 위치(px)
}
const KEY = 'maxgrid-example-grid-state';
let say: (message: LogText) => void = () => {};
let initial: ColumnState[] = [];
let memory: string | null = null; // 브라우저 저장소를 못 쓰는 환경(미리보기 화면 등)에서는 메모리에 둬요.
function read(): string | null {
try {
return localStorage.getItem(KEY) ?? memory;
} catch {
return memory;
}
}
function write(text: string | null): void {
memory = text;
try {
if (text === null) localStorage.removeItem(KEY);
else localStorage.setItem(KEY, text);
} catch {
say({
ko: '이 화면에서는 브라우저 저장소를 못 써서, 페이지를 닫기 전까지만 기억해요.',
en: 'Browser storage is unavailable here, so the state is remembered only until you close the page.',
});
}
}
function restore(api: GridApi<Row>): boolean {
const text = read();
if (!text) return false;
try {
const state = JSON.parse(text) as SavedState;
api.setColumnState(state.columns);
api.setSortModel(state.sort);
// 컬럼과 정렬을 먼저 적용한 뒤, 화면이 다시 그려진 다음에 스크롤 위치를 되돌려요.
requestAnimationFrame(() =>
requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })),
);
return true;
} catch (error) {
// 깨진 값 때문에 화면이 멈추면 안 돼요. 알리고 기본 상태로 둬요.
say({
ko: `저장된 상태가 올바르지 않아 무시했어요: ${String(error)}`,
en: `Ignored the saved state because it is not valid: ${String(error)}`,
});
return false;
}
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
initial = api.getColumnState();
log({
ko: restore(api)
? '저장된 상태를 불러왔어요.'
: '저장된 상태가 없어요. 컬럼을 끌어 옮기거나 너비를 바꾼 뒤 "상태 저장"을 눌러 보세요.',
en: restore(api)
? 'Saved state restored.'
: 'No saved state. Drag a column or change a width, then press "Save state".',
});
}
export const actions = {
save: (api: GridApi<Row>) => {
const state: SavedState = {
columns: api.getColumnState(),
sort: api.getSortModel(),
scroll: api.getScroll(),
};
write(JSON.stringify(state));
say({
ko: `저장했어요: 컬럼 ${state.columns.length}개, 정렬 ${state.sort.length}개, 스크롤 ${Math.round(state.scroll.top)}px`,
en: `Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`,
});
},
load: (api: GridApi<Row>) =>
say({
ko: restore(api) ? '저장된 상태로 되돌렸어요.' : '저장된 상태가 없어요.',
en: restore(api) ? 'Went back to the saved state.' : 'No saved state.',
}),
clear: (api: GridApi<Row>) => {
write(null);
api.setColumnState(initial);
api.setSortModel([]);
api.setScroll({ top: 0, left: 0 });
say({
ko: '저장된 상태를 지우고 처음 모양으로 되돌렸어요.',
en: 'Cleared the saved state and went back to the starting layout.',
});
},
hideCity: (api: GridApi<Row>) => api.setColumnVisible('city', false),
pinName: (api: GridApi<Row>) => api.pinColumn('name', 'start'),
sortPrice: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};버튼을 누르면 이 예제의 코드가 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.hideCity(api)"
>지역 숨기기</button>
<button type="button" :disabled="!api" @click="api && actions.pinName(api)">이름 왼쪽 고정</button>
<button
type="button"
:disabled="!api"
@click="api && actions.sortPrice(api)"
>가격 높은 순</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">상태 저장</button>
<button type="button" :disabled="!api" @click="api && actions.load(api)">저장한 상태로</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">저장 지우고 처음으로</button>
</div>
<Grid style="height: 340px" :options="options" @ready="onReady" />
</template>import type { ColumnState, GridApi, GridOptions, SortItem } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
city: string;
product: string;
color: string;
quantity: number;
price: number;
}
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후', '윤서아', '임태민'];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전'];
const products = ['무선 이어폰', '노트북 14형', '스마트워치', '태블릿 11형', '보조배터리'];
const colors = ['블랙', '화이트', '실버', '네이비', '핑크'];
const rows: Row[] = Array.from({ length: 60 }, (_, i) => ({
id: i + 1,
name: names[(i * 3) % names.length],
city: cities[(i * 5) % cities.length],
product: products[(i * 2 + (i >> 2)) % products.length],
color: colors[(i * 7) % colors.length],
quantity: 1 + ((i * 7) % 9),
price: 29000 + ((i * 7919) % 40) * 10000,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 100 },
{ id: 'city', title: '지역', width: 90 },
{ id: 'product', title: '상품', width: 140 },
{ id: 'color', title: '색상', width: 90 },
{ id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
{
id: 'price',
title: '가격',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
],
rows,
rowKey: 'id',
rowHeight: 32,
};
// 저장하는 것: 컬럼 순서·너비·숨김·고정(getColumnState), 정렬, 스크롤 위치(getScroll).
interface SavedState {
columns: ColumnState[];
sort: SortItem[];
scroll: { top: number; left: number }; // 스크롤 위치(px)
}
const KEY = 'maxgrid-example-grid-state';
let say: (message: LogText) => void = () => {};
let initial: ColumnState[] = [];
let memory: string | null = null; // 브라우저 저장소를 못 쓰는 환경(미리보기 화면 등)에서는 메모리에 둬요.
function read(): string | null {
try {
return localStorage.getItem(KEY) ?? memory;
} catch {
return memory;
}
}
function write(text: string | null): void {
memory = text;
try {
if (text === null) localStorage.removeItem(KEY);
else localStorage.setItem(KEY, text);
} catch {
say({
ko: '이 화면에서는 브라우저 저장소를 못 써서, 페이지를 닫기 전까지만 기억해요.',
en: 'Browser storage is unavailable here, so the state is remembered only until you close the page.',
});
}
}
function restore(api: GridApi<Row>): boolean {
const text = read();
if (!text) return false;
try {
const state = JSON.parse(text) as SavedState;
api.setColumnState(state.columns);
api.setSortModel(state.sort);
// 컬럼과 정렬을 먼저 적용한 뒤, 화면이 다시 그려진 다음에 스크롤 위치를 되돌려요.
requestAnimationFrame(() =>
requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })),
);
return true;
} catch (error) {
// 깨진 값 때문에 화면이 멈추면 안 돼요. 알리고 기본 상태로 둬요.
say({
ko: `저장된 상태가 올바르지 않아 무시했어요: ${String(error)}`,
en: `Ignored the saved state because it is not valid: ${String(error)}`,
});
return false;
}
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
initial = api.getColumnState();
log({
ko: restore(api)
? '저장된 상태를 불러왔어요.'
: '저장된 상태가 없어요. 컬럼을 끌어 옮기거나 너비를 바꾼 뒤 "상태 저장"을 눌러 보세요.',
en: restore(api)
? 'Saved state restored.'
: 'No saved state. Drag a column or change a width, then press "Save state".',
});
}
export const actions = {
save: (api: GridApi<Row>) => {
const state: SavedState = {
columns: api.getColumnState(),
sort: api.getSortModel(),
scroll: api.getScroll(),
};
write(JSON.stringify(state));
say({
ko: `저장했어요: 컬럼 ${state.columns.length}개, 정렬 ${state.sort.length}개, 스크롤 ${Math.round(state.scroll.top)}px`,
en: `Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`,
});
},
load: (api: GridApi<Row>) =>
say({
ko: restore(api) ? '저장된 상태로 되돌렸어요.' : '저장된 상태가 없어요.',
en: restore(api) ? 'Went back to the saved state.' : 'No saved state.',
}),
clear: (api: GridApi<Row>) => {
write(null);
api.setColumnState(initial);
api.setSortModel([]);
api.setScroll({ top: 0, left: 0 });
say({
ko: '저장된 상태를 지우고 처음 모양으로 되돌렸어요.',
en: 'Cleared the saved state and went back to the starting layout.',
});
},
hideCity: (api: GridApi<Row>) => api.setColumnVisible('city', false),
pinName: (api: GridApi<Row>) => api.pinColumn('name', 'start'),
sortPrice: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};버튼을 누르면 이 예제의 코드가 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.hideCity(api)"
>지역 숨기기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pinName(api)"
>이름 왼쪽 고정</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.sortPrice(api)"
>가격 높은 순</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>상태 저장</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.load(api)"
>저장한 상태로</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>저장 지우고 처음으로</button>
</div>
<mx-grid style="height: 340px" [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 { ColumnState, GridApi, GridOptions, SortItem } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
city: string;
product: string;
color: string;
quantity: number;
price: number;
}
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후', '윤서아', '임태민'];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전'];
const products = ['무선 이어폰', '노트북 14형', '스마트워치', '태블릿 11형', '보조배터리'];
const colors = ['블랙', '화이트', '실버', '네이비', '핑크'];
const rows: Row[] = Array.from({ length: 60 }, (_, i) => ({
id: i + 1,
name: names[(i * 3) % names.length],
city: cities[(i * 5) % cities.length],
product: products[(i * 2 + (i >> 2)) % products.length],
color: colors[(i * 7) % colors.length],
quantity: 1 + ((i * 7) % 9),
price: 29000 + ((i * 7919) % 40) * 10000,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 100 },
{ id: 'city', title: '지역', width: 90 },
{ id: 'product', title: '상품', width: 140 },
{ id: 'color', title: '색상', width: 90 },
{ id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
{
id: 'price',
title: '가격',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
],
rows,
rowKey: 'id',
rowHeight: 32,
};
// 저장하는 것: 컬럼 순서·너비·숨김·고정(getColumnState), 정렬, 스크롤 위치(getScroll).
interface SavedState {
columns: ColumnState[];
sort: SortItem[];
scroll: { top: number; left: number }; // 스크롤 위치(px)
}
const KEY = 'maxgrid-example-grid-state';
let say: (message: LogText) => void = () => {};
let initial: ColumnState[] = [];
let memory: string | null = null; // 브라우저 저장소를 못 쓰는 환경(미리보기 화면 등)에서는 메모리에 둬요.
function read(): string | null {
try {
return localStorage.getItem(KEY) ?? memory;
} catch {
return memory;
}
}
function write(text: string | null): void {
memory = text;
try {
if (text === null) localStorage.removeItem(KEY);
else localStorage.setItem(KEY, text);
} catch {
say({
ko: '이 화면에서는 브라우저 저장소를 못 써서, 페이지를 닫기 전까지만 기억해요.',
en: 'Browser storage is unavailable here, so the state is remembered only until you close the page.',
});
}
}
function restore(api: GridApi<Row>): boolean {
const text = read();
if (!text) return false;
try {
const state = JSON.parse(text) as SavedState;
api.setColumnState(state.columns);
api.setSortModel(state.sort);
// 컬럼과 정렬을 먼저 적용한 뒤, 화면이 다시 그려진 다음에 스크롤 위치를 되돌려요.
requestAnimationFrame(() =>
requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })),
);
return true;
} catch (error) {
// 깨진 값 때문에 화면이 멈추면 안 돼요. 알리고 기본 상태로 둬요.
say({
ko: `저장된 상태가 올바르지 않아 무시했어요: ${String(error)}`,
en: `Ignored the saved state because it is not valid: ${String(error)}`,
});
return false;
}
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
initial = api.getColumnState();
log({
ko: restore(api)
? '저장된 상태를 불러왔어요.'
: '저장된 상태가 없어요. 컬럼을 끌어 옮기거나 너비를 바꾼 뒤 "상태 저장"을 눌러 보세요.',
en: restore(api)
? 'Saved state restored.'
: 'No saved state. Drag a column or change a width, then press "Save state".',
});
}
export const actions = {
save: (api: GridApi<Row>) => {
const state: SavedState = {
columns: api.getColumnState(),
sort: api.getSortModel(),
scroll: api.getScroll(),
};
write(JSON.stringify(state));
say({
ko: `저장했어요: 컬럼 ${state.columns.length}개, 정렬 ${state.sort.length}개, 스크롤 ${Math.round(state.scroll.top)}px`,
en: `Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`,
});
},
load: (api: GridApi<Row>) =>
say({
ko: restore(api) ? '저장된 상태로 되돌렸어요.' : '저장된 상태가 없어요.',
en: restore(api) ? 'Went back to the saved state.' : 'No saved state.',
}),
clear: (api: GridApi<Row>) => {
write(null);
api.setColumnState(initial);
api.setSortModel([]);
api.setScroll({ top: 0, left: 0 });
say({
ko: '저장된 상태를 지우고 처음 모양으로 되돌렸어요.',
en: 'Cleared the saved state and went back to the starting layout.',
});
},
hideCity: (api: GridApi<Row>) => api.setColumnVisible('city', false),
pinName: (api: GridApi<Row>) => api.pinColumn('name', 'start'),
sortPrice: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};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="hideCity">Hide city</button>
<button type="button" id="pinName">Pin name left</button>
<button type="button" id="sortPrice">Price high to low</button>
<button type="button" id="save">Save state</button>
<button type="button" id="load">Restore saved</button>
<button type="button" id="clear">Clear and reset</button>
</div>
<div id="grid" style="height: 340px"></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('hideCity').addEventListener('click', () => actions.hideCity(api));
document.getElementById('pinName').addEventListener('click', () => actions.pinName(api));
document.getElementById('sortPrice').addEventListener('click', () => actions.sortPrice(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('load').addEventListener('click', () => actions.load(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const names = [
'Liam Carter',
'Emma Stone',
'Noah Brooks',
'Olivia Reed',
'Ethan Hayes',
'Ava Morgan',
'Mason Clark',
'Sophia Bell',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon'];
const products = ['Wireless Earbuds', 'Laptop 14"', 'Smartwatch', 'Tablet 11"', 'Power Bank'];
const colors = ['Black', 'White', 'Silver', 'Navy', 'Pink'];
const rows = Array.from({ length: 60 }, (_, i) => ({
id: i + 1,
name: names[(i * 3) % names.length],
city: cities[(i * 5) % cities.length],
product: products[(i * 2 + (i >> 2)) % products.length],
color: colors[(i * 7) % colors.length],
quantity: 1 + ((i * 7) % 9),
price: 29 + ((i * 7919) % 40) * 10,
}));
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 120 },
{ id: 'city', title: 'City', width: 90 },
{ id: 'product', title: 'Product', width: 150 },
{ id: 'color', title: 'Color', width: 90 },
{ id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
],
rows,
rowKey: 'id',
rowHeight: 32,
};
const KEY = 'maxgrid-example-grid-state';
let say = () => { };
let initial = [];
let memory = null; // Where browser storage is unavailable (such as a preview), keep it in memory.
function read() {
try {
return localStorage.getItem(KEY) ?? memory;
}
catch {
return memory;
}
}
function write(text) {
memory = text;
try {
if (text === null)
localStorage.removeItem(KEY);
else
localStorage.setItem(KEY, text);
}
catch {
say('Browser storage is unavailable here, so the state is remembered only until you close the page.');
}
}
function restore(api) {
const text = read();
if (!text)
return false;
try {
const state = JSON.parse(text);
api.setColumnState(state.columns);
api.setSortModel(state.sort);
// Apply columns and sort first, then restore the scroll position after the screen has been redrawn.
requestAnimationFrame(() => requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })));
return true;
}
catch (error) {
// A corrupt value must not freeze the screen. Report it and keep the default state.
say(`Ignored the saved state because it is not valid: ${String(error)}`);
return false;
}
}
export function setup(api, log) {
say = log;
initial = api.getColumnState();
log(restore(api)
? 'Saved state restored.'
: 'No saved state. Drag a column or change a width, then press "Save state".');
}
export const actions = {
save: (api) => {
const state = {
columns: api.getColumnState(),
sort: api.getSortModel(),
scroll: api.getScroll(),
};
write(JSON.stringify(state));
say(`Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`);
},
load: (api) => say(restore(api) ? 'Went back to the saved state.' : 'No saved state.'),
clear: (api) => {
write(null);
api.setColumnState(initial);
api.setSortModel([]);
api.setScroll({ top: 0, left: 0 });
say('Cleared the saved state and went back to the starting layout.');
},
hideCity: (api) => api.setColumnVisible('city', false),
pinName: (api) => api.pinColumn('name', 'start'),
sortPrice: (api) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Remember the table layout you set</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="hideCity">Hide city</button>
<button type="button" id="pinName">Pin name left</button>
<button type="button" id="sortPrice">Price high to low</button>
<button type="button" id="save">Save state</button>
<button type="button" id="load">Restore saved</button>
<button type="button" id="clear">Clear and reset</button>
</div>
<div id="grid" style="height: 340px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = [
'Liam Carter',
'Emma Stone',
'Noah Brooks',
'Olivia Reed',
'Ethan Hayes',
'Ava Morgan',
'Mason Clark',
'Sophia Bell',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon'];
const products = ['Wireless Earbuds', 'Laptop 14"', 'Smartwatch', 'Tablet 11"', 'Power Bank'];
const colors = ['Black', 'White', 'Silver', 'Navy', 'Pink'];
const rows = Array.from({ length: 60 }, (_, i) => ({
id: i + 1,
name: names[(i * 3) % names.length],
city: cities[(i * 5) % cities.length],
product: products[(i * 2 + (i >> 2)) % products.length],
color: colors[(i * 7) % colors.length],
quantity: 1 + ((i * 7) % 9),
price: 29 + ((i * 7919) % 40) * 10,
}));
const options = {
columns: [
{ id: 'name', title: 'Name', width: 120 },
{ id: 'city', title: 'City', width: 90 },
{ id: 'product', title: 'Product', width: 150 },
{ id: 'color', title: 'Color', width: 90 },
{ id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
],
rows,
rowKey: 'id',
rowHeight: 32,
};
const KEY = 'maxgrid-example-grid-state';
let say = () => { };
let initial = [];
let memory = null; // Where browser storage is unavailable (such as a preview), keep it in memory.
function read() {
try {
return localStorage.getItem(KEY) ?? memory;
}
catch {
return memory;
}
}
function write(text) {
memory = text;
try {
if (text === null)
localStorage.removeItem(KEY);
else
localStorage.setItem(KEY, text);
}
catch {
say('Browser storage is unavailable here, so the state is remembered only until you close the page.');
}
}
function restore(api) {
const text = read();
if (!text)
return false;
try {
const state = JSON.parse(text);
api.setColumnState(state.columns);
api.setSortModel(state.sort);
// Apply columns and sort first, then restore the scroll position after the screen has been redrawn.
requestAnimationFrame(() => requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })));
return true;
}
catch (error) {
// A corrupt value must not freeze the screen. Report it and keep the default state.
say(`Ignored the saved state because it is not valid: ${String(error)}`);
return false;
}
}
function setup(api, log) {
say = log;
initial = api.getColumnState();
log(restore(api)
? 'Saved state restored.'
: 'No saved state. Drag a column or change a width, then press "Save state".');
}
const actions = {
save: (api) => {
const state = {
columns: api.getColumnState(),
sort: api.getSortModel(),
scroll: api.getScroll(),
};
write(JSON.stringify(state));
say(`Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`);
},
load: (api) => say(restore(api) ? 'Went back to the saved state.' : 'No saved state.'),
clear: (api) => {
write(null);
api.setColumnState(initial);
api.setSortModel([]);
api.setScroll({ top: 0, left: 0 });
say('Cleared the saved state and went back to the starting layout.');
},
hideCity: (api) => api.setColumnVisible('city', false),
pinName: (api) => api.pinColumn('name', 'start'),
sortPrice: (api) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};
options.ariaLabel = "Remember the table layout you set";
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('hideCity').addEventListener('click', () => actions.hideCity(api));
document.getElementById('pinName').addEventListener('click', () => actions.pinName(api));
document.getElementById('sortPrice').addEventListener('click', () => actions.sortPrice(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('load').addEventListener('click', () => actions.load(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.hideCity(api)}
>Hide city</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pinName(api)}
>Pin name left</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.sortPrice(api)}
>Price high to low</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>Save state</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.load(api)}
>Restore saved</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear and reset</button>
</div>
<Grid style={{ height: 340 }} ref={gridRef} options={options} />
</>
);
}import type { ColumnState, GridApi, GridOptions, SortItem } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
city: string;
product: string;
color: string;
quantity: number;
price: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Brooks',
'Olivia Reed',
'Ethan Hayes',
'Ava Morgan',
'Mason Clark',
'Sophia Bell',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon'];
const products = ['Wireless Earbuds', 'Laptop 14"', 'Smartwatch', 'Tablet 11"', 'Power Bank'];
const colors = ['Black', 'White', 'Silver', 'Navy', 'Pink'];
const rows: Row[] = Array.from({ length: 60 }, (_, i) => ({
id: i + 1,
name: names[(i * 3) % names.length],
city: cities[(i * 5) % cities.length],
product: products[(i * 2 + (i >> 2)) % products.length],
color: colors[(i * 7) % colors.length],
quantity: 1 + ((i * 7) % 9),
price: 29 + ((i * 7919) % 40) * 10,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 120 },
{ id: 'city', title: 'City', width: 90 },
{ id: 'product', title: 'Product', width: 150 },
{ id: 'color', title: 'Color', width: 90 },
{ id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
],
rows,
rowKey: 'id',
rowHeight: 32,
};
// What is saved: column order, width, hidden and pinned state (getColumnState), sort, and scroll position (getScroll).
interface SavedState {
columns: ColumnState[];
sort: SortItem[];
scroll: { top: number; left: number }; // Scroll position (px)
}
const KEY = 'maxgrid-example-grid-state';
let say: (message: LogText) => void = () => {};
let initial: ColumnState[] = [];
let memory: string | null = null; // Where browser storage is unavailable (such as a preview), keep it in memory.
function read(): string | null {
try {
return localStorage.getItem(KEY) ?? memory;
} catch {
return memory;
}
}
function write(text: string | null): void {
memory = text;
try {
if (text === null) localStorage.removeItem(KEY);
else localStorage.setItem(KEY, text);
} catch {
say(
'Browser storage is unavailable here, so the state is remembered only until you close the page.',
);
}
}
function restore(api: GridApi<Row>): boolean {
const text = read();
if (!text) return false;
try {
const state = JSON.parse(text) as SavedState;
api.setColumnState(state.columns);
api.setSortModel(state.sort);
// Apply columns and sort first, then restore the scroll position after the screen has been redrawn.
requestAnimationFrame(() =>
requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })),
);
return true;
} catch (error) {
// A corrupt value must not freeze the screen. Report it and keep the default state.
say(`Ignored the saved state because it is not valid: ${String(error)}`);
return false;
}
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
initial = api.getColumnState();
log(
restore(api)
? 'Saved state restored.'
: 'No saved state. Drag a column or change a width, then press "Save state".',
);
}
export const actions = {
save: (api: GridApi<Row>) => {
const state: SavedState = {
columns: api.getColumnState(),
sort: api.getSortModel(),
scroll: api.getScroll(),
};
write(JSON.stringify(state));
say(
`Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`,
);
},
load: (api: GridApi<Row>) =>
say(restore(api) ? 'Went back to the saved state.' : 'No saved state.'),
clear: (api: GridApi<Row>) => {
write(null);
api.setColumnState(initial);
api.setSortModel([]);
api.setScroll({ top: 0, left: 0 });
say('Cleared the saved state and went back to the starting layout.');
},
hideCity: (api: GridApi<Row>) => api.setColumnVisible('city', false),
pinName: (api: GridApi<Row>) => api.pinColumn('name', 'start'),
sortPrice: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};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.hideCity(api)"
>Hide city</button>
<button type="button" :disabled="!api" @click="api && actions.pinName(api)">Pin name left</button>
<button
type="button"
:disabled="!api"
@click="api && actions.sortPrice(api)"
>Price high to low</button>
<button type="button" :disabled="!api" @click="api && actions.save(api)">Save state</button>
<button type="button" :disabled="!api" @click="api && actions.load(api)">Restore saved</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear and reset</button>
</div>
<Grid style="height: 340px" :options="options" @ready="onReady" />
</template>import type { ColumnState, GridApi, GridOptions, SortItem } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
city: string;
product: string;
color: string;
quantity: number;
price: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Brooks',
'Olivia Reed',
'Ethan Hayes',
'Ava Morgan',
'Mason Clark',
'Sophia Bell',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon'];
const products = ['Wireless Earbuds', 'Laptop 14"', 'Smartwatch', 'Tablet 11"', 'Power Bank'];
const colors = ['Black', 'White', 'Silver', 'Navy', 'Pink'];
const rows: Row[] = Array.from({ length: 60 }, (_, i) => ({
id: i + 1,
name: names[(i * 3) % names.length],
city: cities[(i * 5) % cities.length],
product: products[(i * 2 + (i >> 2)) % products.length],
color: colors[(i * 7) % colors.length],
quantity: 1 + ((i * 7) % 9),
price: 29 + ((i * 7919) % 40) * 10,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 120 },
{ id: 'city', title: 'City', width: 90 },
{ id: 'product', title: 'Product', width: 150 },
{ id: 'color', title: 'Color', width: 90 },
{ id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
],
rows,
rowKey: 'id',
rowHeight: 32,
};
// What is saved: column order, width, hidden and pinned state (getColumnState), sort, and scroll position (getScroll).
interface SavedState {
columns: ColumnState[];
sort: SortItem[];
scroll: { top: number; left: number }; // Scroll position (px)
}
const KEY = 'maxgrid-example-grid-state';
let say: (message: LogText) => void = () => {};
let initial: ColumnState[] = [];
let memory: string | null = null; // Where browser storage is unavailable (such as a preview), keep it in memory.
function read(): string | null {
try {
return localStorage.getItem(KEY) ?? memory;
} catch {
return memory;
}
}
function write(text: string | null): void {
memory = text;
try {
if (text === null) localStorage.removeItem(KEY);
else localStorage.setItem(KEY, text);
} catch {
say(
'Browser storage is unavailable here, so the state is remembered only until you close the page.',
);
}
}
function restore(api: GridApi<Row>): boolean {
const text = read();
if (!text) return false;
try {
const state = JSON.parse(text) as SavedState;
api.setColumnState(state.columns);
api.setSortModel(state.sort);
// Apply columns and sort first, then restore the scroll position after the screen has been redrawn.
requestAnimationFrame(() =>
requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })),
);
return true;
} catch (error) {
// A corrupt value must not freeze the screen. Report it and keep the default state.
say(`Ignored the saved state because it is not valid: ${String(error)}`);
return false;
}
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
initial = api.getColumnState();
log(
restore(api)
? 'Saved state restored.'
: 'No saved state. Drag a column or change a width, then press "Save state".',
);
}
export const actions = {
save: (api: GridApi<Row>) => {
const state: SavedState = {
columns: api.getColumnState(),
sort: api.getSortModel(),
scroll: api.getScroll(),
};
write(JSON.stringify(state));
say(
`Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`,
);
},
load: (api: GridApi<Row>) =>
say(restore(api) ? 'Went back to the saved state.' : 'No saved state.'),
clear: (api: GridApi<Row>) => {
write(null);
api.setColumnState(initial);
api.setSortModel([]);
api.setScroll({ top: 0, left: 0 });
say('Cleared the saved state and went back to the starting layout.');
},
hideCity: (api: GridApi<Row>) => api.setColumnVisible('city', false),
pinName: (api: GridApi<Row>) => api.pinColumn('name', 'start'),
sortPrice: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};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.hideCity(api)"
>Hide city</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pinName(api)"
>Pin name left</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.sortPrice(api)"
>Price high to low</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>Save state</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.load(api)"
>Restore saved</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear and reset</button>
</div>
<mx-grid style="height: 340px" [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 { ColumnState, GridApi, GridOptions, SortItem } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
city: string;
product: string;
color: string;
quantity: number;
price: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Brooks',
'Olivia Reed',
'Ethan Hayes',
'Ava Morgan',
'Mason Clark',
'Sophia Bell',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon'];
const products = ['Wireless Earbuds', 'Laptop 14"', 'Smartwatch', 'Tablet 11"', 'Power Bank'];
const colors = ['Black', 'White', 'Silver', 'Navy', 'Pink'];
const rows: Row[] = Array.from({ length: 60 }, (_, i) => ({
id: i + 1,
name: names[(i * 3) % names.length],
city: cities[(i * 5) % cities.length],
product: products[(i * 2 + (i >> 2)) % products.length],
color: colors[(i * 7) % colors.length],
quantity: 1 + ((i * 7) % 9),
price: 29 + ((i * 7919) % 40) * 10,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 120 },
{ id: 'city', title: 'City', width: 90 },
{ id: 'product', title: 'Product', width: 150 },
{ id: 'color', title: 'Color', width: 90 },
{ id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 110,
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
],
rows,
rowKey: 'id',
rowHeight: 32,
};
// What is saved: column order, width, hidden and pinned state (getColumnState), sort, and scroll position (getScroll).
interface SavedState {
columns: ColumnState[];
sort: SortItem[];
scroll: { top: number; left: number }; // Scroll position (px)
}
const KEY = 'maxgrid-example-grid-state';
let say: (message: LogText) => void = () => {};
let initial: ColumnState[] = [];
let memory: string | null = null; // Where browser storage is unavailable (such as a preview), keep it in memory.
function read(): string | null {
try {
return localStorage.getItem(KEY) ?? memory;
} catch {
return memory;
}
}
function write(text: string | null): void {
memory = text;
try {
if (text === null) localStorage.removeItem(KEY);
else localStorage.setItem(KEY, text);
} catch {
say(
'Browser storage is unavailable here, so the state is remembered only until you close the page.',
);
}
}
function restore(api: GridApi<Row>): boolean {
const text = read();
if (!text) return false;
try {
const state = JSON.parse(text) as SavedState;
api.setColumnState(state.columns);
api.setSortModel(state.sort);
// Apply columns and sort first, then restore the scroll position after the screen has been redrawn.
requestAnimationFrame(() =>
requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })),
);
return true;
} catch (error) {
// A corrupt value must not freeze the screen. Report it and keep the default state.
say(`Ignored the saved state because it is not valid: ${String(error)}`);
return false;
}
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
initial = api.getColumnState();
log(
restore(api)
? 'Saved state restored.'
: 'No saved state. Drag a column or change a width, then press "Save state".',
);
}
export const actions = {
save: (api: GridApi<Row>) => {
const state: SavedState = {
columns: api.getColumnState(),
sort: api.getSortModel(),
scroll: api.getScroll(),
};
write(JSON.stringify(state));
say(
`Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`,
);
},
load: (api: GridApi<Row>) =>
say(restore(api) ? 'Went back to the saved state.' : 'No saved state.'),
clear: (api: GridApi<Row>) => {
write(null);
api.setColumnState(initial);
api.setSortModel([]);
api.setScroll({ top: 0, left: 0 });
say('Cleared the saved state and went back to the starting layout.');
},
hideCity: (api: GridApi<Row>) => api.setColumnVisible('city', false),
pinName: (api: GridApi<Row>) => api.pinColumn('name', 'start'),
sortPrice: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};