정렬 상태를 코드로 바꾸고 저장해 두기Set and save the sort state from code
정렬 상태는 그냥 목록이에요(어느 컬럼을 어느 방향으로, 우선순위 순서로). 코드로 바로 정해 주고, 지금 정렬을 저장해 두었다가 나중에 그대로 불러올 수 있어요. 저장 위치는 브라우저 저장소나 서버, 저장된 보기 어디든 돼요.The sort state is a plain list of columns and directions in priority order. Set it from code, save the current sort and bring it back later; store it in browser storage, a server or a saved view.
코드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">
<select aria-label="정렬 설정" id="preset">
<option value="none" selected>정렬 없음</option>
<option value="cheapest">가격 싼 순</option>
<option value="byCategory">분류 → 가격 높은 순</option>
</select>
<button type="button" id="save">지금 정렬 저장</button>
<button type="button" id="restore">저장한 정렬 불러오기</button>
</div>
<div id="grid" style="height: 330px"></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('preset').addEventListener('change', (event) => actions.preset(api, event.target.value));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));export const options = {
columns: [
{ id: 'name', title: '상품', width: 170 },
{ id: 'category', title: '분류', width: 130 },
{
id: 'price',
title: '가격(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [
{ id: 1, name: '스탠드 조명', category: '조명', price: 39000 },
{ id: 2, name: '높이조절 책상', category: '가구', price: 520000 },
{ id: 3, name: '모니터 암', category: '액세서리', price: 85000 },
{ id: 4, name: '사무용 의자', category: '가구', price: 310000 },
{ id: 5, name: '케이블 트레이', category: '액세서리', price: 18000 },
{ id: 6, name: '플로어 조명', category: '조명', price: 95000 },
],
rowKey: 'id',
};
// 정렬 상태(sortModel)는 그리드 밖에서도 다룰 수 있어요. 사용자가 고른 정렬을 저장해 두었다가(예: localStorage,
// 저장된 보기) 나중에 setSortModel로 돌려주면 돼요. 아래는 '저장'과 '불러오기'를 직접 해 보는 예제예요.
const PRESETS = {
none: [],
cheapest: [{ columnId: 'price', direction: 'asc' }],
byCategory: [
{ columnId: 'category', direction: 'asc' },
{ columnId: 'price', direction: 'desc' },
],
};
let saved = [];
let say = () => { };
const TITLE = { name: '상품', category: '분류', price: '가격' };
const describe = (model, none) => model.length === 0
? none
: model
.map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(' → ');
export function setup(api, log) {
say = log;
saved = [];
const off = api.on('sortChanged', ({ sortModel }) => log({
ko: `지금 정렬: ${describe(sortModel, '정렬 없음')}`,
en: `Sort now: ${describe(sortModel, 'no sort')}`,
}));
return () => off();
}
export const actions = {
preset: (api, value) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
save: (api) => {
saved = api.getSortModel();
say({
ko: `저장했어요: ${describe(saved, '정렬 없음')}`,
en: `Saved: ${describe(saved, 'no sort')}`,
});
},
restore: (api) => {
api.setSortModel(saved);
say({
ko: `불러왔어요: ${describe(saved, '정렬 없음')}`,
en: `Loaded: ${describe(saved, 'no sort')}`,
});
},
};<!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">
<select aria-label="정렬 설정" id="preset">
<option value="none" selected>정렬 없음</option>
<option value="cheapest">가격 싼 순</option>
<option value="byCategory">분류 → 가격 높은 순</option>
</select>
<button type="button" id="save">지금 정렬 저장</button>
<button type="button" id="restore">저장한 정렬 불러오기</button>
</div>
<div id="grid" style="height: 330px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const options = {
columns: [
{ id: 'name', title: '상품', width: 170 },
{ id: 'category', title: '분류', width: 130 },
{
id: 'price',
title: '가격(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [
{ id: 1, name: '스탠드 조명', category: '조명', price: 39000 },
{ id: 2, name: '높이조절 책상', category: '가구', price: 520000 },
{ id: 3, name: '모니터 암', category: '액세서리', price: 85000 },
{ id: 4, name: '사무용 의자', category: '가구', price: 310000 },
{ id: 5, name: '케이블 트레이', category: '액세서리', price: 18000 },
{ id: 6, name: '플로어 조명', category: '조명', price: 95000 },
],
rowKey: 'id',
};
// 정렬 상태(sortModel)는 그리드 밖에서도 다룰 수 있어요. 사용자가 고른 정렬을 저장해 두었다가(예: localStorage,
// 저장된 보기) 나중에 setSortModel로 돌려주면 돼요. 아래는 '저장'과 '불러오기'를 직접 해 보는 예제예요.
const PRESETS = {
none: [],
cheapest: [{ columnId: 'price', direction: 'asc' }],
byCategory: [
{ columnId: 'category', direction: 'asc' },
{ columnId: 'price', direction: 'desc' },
],
};
let saved = [];
let say = () => { };
const TITLE = { name: '상품', category: '분류', price: '가격' };
const describe = (model, none) => model.length === 0
? none
: model
.map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(' → ');
function setup(api, log) {
say = log;
saved = [];
const off = api.on('sortChanged', ({ sortModel }) => log({
ko: `지금 정렬: ${describe(sortModel, '정렬 없음')}`,
en: `Sort now: ${describe(sortModel, 'no sort')}`,
}));
return () => off();
}
const actions = {
preset: (api, value) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
save: (api) => {
saved = api.getSortModel();
say({
ko: `저장했어요: ${describe(saved, '정렬 없음')}`,
en: `Saved: ${describe(saved, 'no sort')}`,
});
},
restore: (api) => {
api.setSortModel(saved);
say({
ko: `불러왔어요: ${describe(saved, '정렬 없음')}`,
en: `Loaded: ${describe(saved, 'no sort')}`,
});
},
};
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('preset').addEventListener('change', (event) => actions.preset(api, event.target.value));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(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">
<select
aria-label="정렬 설정"
disabled={!api}
onChange={(event) => api && actions.preset(api, event.target.value)}
>
<option value="none">정렬 없음</option>
<option value="cheapest">가격 싼 순</option>
<option value="byCategory">분류 → 가격 높은 순</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>지금 정렬 저장</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.restore(api)}
>저장한 정렬 불러오기</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, SortItem } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
category: string;
price: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '상품', width: 170 },
{ id: 'category', title: '분류', width: 130 },
{
id: 'price',
title: '가격(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [
{ id: 1, name: '스탠드 조명', category: '조명', price: 39000 },
{ id: 2, name: '높이조절 책상', category: '가구', price: 520000 },
{ id: 3, name: '모니터 암', category: '액세서리', price: 85000 },
{ id: 4, name: '사무용 의자', category: '가구', price: 310000 },
{ id: 5, name: '케이블 트레이', category: '액세서리', price: 18000 },
{ id: 6, name: '플로어 조명', category: '조명', price: 95000 },
],
rowKey: 'id',
};
// 정렬 상태(sortModel)는 그리드 밖에서도 다룰 수 있어요. 사용자가 고른 정렬을 저장해 두었다가(예: localStorage,
// 저장된 보기) 나중에 setSortModel로 돌려주면 돼요. 아래는 '저장'과 '불러오기'를 직접 해 보는 예제예요.
const PRESETS: Record<string, SortItem[]> = {
none: [],
cheapest: [{ columnId: 'price', direction: 'asc' }],
byCategory: [
{ columnId: 'category', direction: 'asc' },
{ columnId: 'price', direction: 'desc' },
],
};
let saved: SortItem[] = [];
let say: (message: LogText) => void = () => {};
const TITLE: Record<string, string> = { name: '상품', category: '분류', price: '가격' };
const describe = (model: SortItem[], none: string): string =>
model.length === 0
? none
: model
.map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(' → ');
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
saved = [];
const off = api.on('sortChanged', ({ sortModel }) =>
log({
ko: `지금 정렬: ${describe(sortModel, '정렬 없음')}`,
en: `Sort now: ${describe(sortModel, 'no sort')}`,
}),
);
return () => off();
}
export const actions = {
preset: (api: GridApi<Row>, value?: string) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
save: (api: GridApi<Row>) => {
saved = api.getSortModel();
say({
ko: `저장했어요: ${describe(saved, '정렬 없음')}`,
en: `Saved: ${describe(saved, 'no sort')}`,
});
},
restore: (api: GridApi<Row>) => {
api.setSortModel(saved);
say({
ko: `불러왔어요: ${describe(saved, '정렬 없음')}`,
en: `Loaded: ${describe(saved, 'no sort')}`,
});
},
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="정렬 설정"
:disabled="!api"
@change="api && actions.preset(api, ($event.target as HTMLSelectElement).value)"
>
<option value="none" selected>정렬 없음</option>
<option value="cheapest">가격 싼 순</option>
<option value="byCategory">분류 → 가격 높은 순</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.save(api)">지금 정렬 저장</button>
<button type="button" :disabled="!api" @click="api && actions.restore(api)">저장한 정렬 불러오기</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, SortItem } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
category: string;
price: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '상품', width: 170 },
{ id: 'category', title: '분류', width: 130 },
{
id: 'price',
title: '가격(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [
{ id: 1, name: '스탠드 조명', category: '조명', price: 39000 },
{ id: 2, name: '높이조절 책상', category: '가구', price: 520000 },
{ id: 3, name: '모니터 암', category: '액세서리', price: 85000 },
{ id: 4, name: '사무용 의자', category: '가구', price: 310000 },
{ id: 5, name: '케이블 트레이', category: '액세서리', price: 18000 },
{ id: 6, name: '플로어 조명', category: '조명', price: 95000 },
],
rowKey: 'id',
};
// 정렬 상태(sortModel)는 그리드 밖에서도 다룰 수 있어요. 사용자가 고른 정렬을 저장해 두었다가(예: localStorage,
// 저장된 보기) 나중에 setSortModel로 돌려주면 돼요. 아래는 '저장'과 '불러오기'를 직접 해 보는 예제예요.
const PRESETS: Record<string, SortItem[]> = {
none: [],
cheapest: [{ columnId: 'price', direction: 'asc' }],
byCategory: [
{ columnId: 'category', direction: 'asc' },
{ columnId: 'price', direction: 'desc' },
],
};
let saved: SortItem[] = [];
let say: (message: LogText) => void = () => {};
const TITLE: Record<string, string> = { name: '상품', category: '분류', price: '가격' };
const describe = (model: SortItem[], none: string): string =>
model.length === 0
? none
: model
.map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(' → ');
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
saved = [];
const off = api.on('sortChanged', ({ sortModel }) =>
log({
ko: `지금 정렬: ${describe(sortModel, '정렬 없음')}`,
en: `Sort now: ${describe(sortModel, 'no sort')}`,
}),
);
return () => off();
}
export const actions = {
preset: (api: GridApi<Row>, value?: string) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
save: (api: GridApi<Row>) => {
saved = api.getSortModel();
say({
ko: `저장했어요: ${describe(saved, '정렬 없음')}`,
en: `Saved: ${describe(saved, 'no sort')}`,
});
},
restore: (api: GridApi<Row>) => {
api.setSortModel(saved);
say({
ko: `불러왔어요: ${describe(saved, '정렬 없음')}`,
en: `Loaded: ${describe(saved, 'no sort')}`,
});
},
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="정렬 설정"
[disabled]="!api"
(change)="api && actions.preset(api, $any($event.target).value)"
>
<option value="none" selected>정렬 없음</option>
<option value="cheapest">가격 싼 순</option>
<option value="byCategory">분류 → 가격 높은 순</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>지금 정렬 저장</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.restore(api)"
>저장한 정렬 불러오기</button>
</div>
<mx-grid style="height: 330px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions, SortItem } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
category: string;
price: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '상품', width: 170 },
{ id: 'category', title: '분류', width: 130 },
{
id: 'price',
title: '가격(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [
{ id: 1, name: '스탠드 조명', category: '조명', price: 39000 },
{ id: 2, name: '높이조절 책상', category: '가구', price: 520000 },
{ id: 3, name: '모니터 암', category: '액세서리', price: 85000 },
{ id: 4, name: '사무용 의자', category: '가구', price: 310000 },
{ id: 5, name: '케이블 트레이', category: '액세서리', price: 18000 },
{ id: 6, name: '플로어 조명', category: '조명', price: 95000 },
],
rowKey: 'id',
};
// 정렬 상태(sortModel)는 그리드 밖에서도 다룰 수 있어요. 사용자가 고른 정렬을 저장해 두었다가(예: localStorage,
// 저장된 보기) 나중에 setSortModel로 돌려주면 돼요. 아래는 '저장'과 '불러오기'를 직접 해 보는 예제예요.
const PRESETS: Record<string, SortItem[]> = {
none: [],
cheapest: [{ columnId: 'price', direction: 'asc' }],
byCategory: [
{ columnId: 'category', direction: 'asc' },
{ columnId: 'price', direction: 'desc' },
],
};
let saved: SortItem[] = [];
let say: (message: LogText) => void = () => {};
const TITLE: Record<string, string> = { name: '상품', category: '분류', price: '가격' };
const describe = (model: SortItem[], none: string): string =>
model.length === 0
? none
: model
.map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(' → ');
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
saved = [];
const off = api.on('sortChanged', ({ sortModel }) =>
log({
ko: `지금 정렬: ${describe(sortModel, '정렬 없음')}`,
en: `Sort now: ${describe(sortModel, 'no sort')}`,
}),
);
return () => off();
}
export const actions = {
preset: (api: GridApi<Row>, value?: string) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
save: (api: GridApi<Row>) => {
saved = api.getSortModel();
say({
ko: `저장했어요: ${describe(saved, '정렬 없음')}`,
en: `Saved: ${describe(saved, 'no sort')}`,
});
},
restore: (api: GridApi<Row>) => {
api.setSortModel(saved);
say({
ko: `불러왔어요: ${describe(saved, '정렬 없음')}`,
en: `Loaded: ${describe(saved, 'no sort')}`,
});
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<select aria-label="Set sort" id="preset">
<option value="none" selected>No sort</option>
<option value="cheapest">Cheapest first</option>
<option value="byCategory">Category, then price descending</option>
</select>
<button type="button" id="save">Save current sort</button>
<button type="button" id="restore">Restore saved sort</button>
</div>
<div id="grid" style="height: 330px"></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('preset').addEventListener('change', (event) => actions.preset(api, event.target.value));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));export const options = {
columns: [
{ id: 'name', title: 'Product', width: 170 },
{ id: 'category', title: 'Category', width: 130 },
{
id: 'price',
title: 'Price ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [
{ id: 1, name: 'Desk lamp', category: 'Lighting', price: 39 },
{ id: 2, name: 'Height-adjustable desk', category: 'Furniture', price: 520 },
{ id: 3, name: 'Monitor arm', category: 'Accessories', price: 85 },
{ id: 4, name: 'Office chair', category: 'Furniture', price: 310 },
{ id: 5, name: 'Cable tray', category: 'Accessories', price: 18 },
{ id: 6, name: 'Floor lamp', category: 'Lighting', price: 95 },
],
rowKey: 'id',
};
// The sort state (sortModel) can be handled outside the grid too. Store the sort the user picked (for example in localStorage
// or a saved view) and give it back later with setSortModel. This example lets you try "save" and "load" by hand.
const PRESETS = {
none: [],
cheapest: [{ columnId: 'price', direction: 'asc' }],
byCategory: [
{ columnId: 'category', direction: 'asc' },
{ columnId: 'price', direction: 'desc' },
],
};
let saved = [];
let say = () => { };
const TITLE = { name: 'Product', category: 'Category', price: 'Price' };
const describe = (model, none) => model.length === 0
? none
: model
.map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(' → ');
export function setup(api, log) {
say = log;
saved = [];
const off = api.on('sortChanged', ({ sortModel }) => log(`Sort now: ${describe(sortModel, 'no sort')}`));
return () => off();
}
export const actions = {
preset: (api, value) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
save: (api) => {
saved = api.getSortModel();
say(`Saved: ${describe(saved, 'no sort')}`);
},
restore: (api) => {
api.setSortModel(saved);
say(`Loaded: ${describe(saved, 'no sort')}`);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Set and save the sort state from code</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Set sort" id="preset">
<option value="none" selected>No sort</option>
<option value="cheapest">Cheapest first</option>
<option value="byCategory">Category, then price descending</option>
</select>
<button type="button" id="save">Save current sort</button>
<button type="button" id="restore">Restore saved sort</button>
</div>
<div id="grid" style="height: 330px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const options = {
columns: [
{ id: 'name', title: 'Product', width: 170 },
{ id: 'category', title: 'Category', width: 130 },
{
id: 'price',
title: 'Price ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [
{ id: 1, name: 'Desk lamp', category: 'Lighting', price: 39 },
{ id: 2, name: 'Height-adjustable desk', category: 'Furniture', price: 520 },
{ id: 3, name: 'Monitor arm', category: 'Accessories', price: 85 },
{ id: 4, name: 'Office chair', category: 'Furniture', price: 310 },
{ id: 5, name: 'Cable tray', category: 'Accessories', price: 18 },
{ id: 6, name: 'Floor lamp', category: 'Lighting', price: 95 },
],
rowKey: 'id',
};
// The sort state (sortModel) can be handled outside the grid too. Store the sort the user picked (for example in localStorage
// or a saved view) and give it back later with setSortModel. This example lets you try "save" and "load" by hand.
const PRESETS = {
none: [],
cheapest: [{ columnId: 'price', direction: 'asc' }],
byCategory: [
{ columnId: 'category', direction: 'asc' },
{ columnId: 'price', direction: 'desc' },
],
};
let saved = [];
let say = () => { };
const TITLE = { name: 'Product', category: 'Category', price: 'Price' };
const describe = (model, none) => model.length === 0
? none
: model
.map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(' → ');
function setup(api, log) {
say = log;
saved = [];
const off = api.on('sortChanged', ({ sortModel }) => log(`Sort now: ${describe(sortModel, 'no sort')}`));
return () => off();
}
const actions = {
preset: (api, value) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
save: (api) => {
saved = api.getSortModel();
say(`Saved: ${describe(saved, 'no sort')}`);
},
restore: (api) => {
api.setSortModel(saved);
say(`Loaded: ${describe(saved, 'no sort')}`);
},
};
options.ariaLabel = "Set and save the sort state from code";
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('preset').addEventListener('change', (event) => actions.preset(api, event.target.value));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(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">
<select
aria-label="Set sort"
disabled={!api}
onChange={(event) => api && actions.preset(api, event.target.value)}
>
<option value="none">No sort</option>
<option value="cheapest">Cheapest first</option>
<option value="byCategory">Category, then price descending</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.save(api)}
>Save current sort</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.restore(api)}
>Restore saved sort</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, SortItem } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
category: string;
price: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Product', width: 170 },
{ id: 'category', title: 'Category', width: 130 },
{
id: 'price',
title: 'Price ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [
{ id: 1, name: 'Desk lamp', category: 'Lighting', price: 39 },
{ id: 2, name: 'Height-adjustable desk', category: 'Furniture', price: 520 },
{ id: 3, name: 'Monitor arm', category: 'Accessories', price: 85 },
{ id: 4, name: 'Office chair', category: 'Furniture', price: 310 },
{ id: 5, name: 'Cable tray', category: 'Accessories', price: 18 },
{ id: 6, name: 'Floor lamp', category: 'Lighting', price: 95 },
],
rowKey: 'id',
};
// The sort state (sortModel) can be handled outside the grid too. Store the sort the user picked (for example in localStorage
// or a saved view) and give it back later with setSortModel. This example lets you try "save" and "load" by hand.
const PRESETS: Record<string, SortItem[]> = {
none: [],
cheapest: [{ columnId: 'price', direction: 'asc' }],
byCategory: [
{ columnId: 'category', direction: 'asc' },
{ columnId: 'price', direction: 'desc' },
],
};
let saved: SortItem[] = [];
let say: (message: LogText) => void = () => {};
const TITLE: Record<string, string> = { name: 'Product', category: 'Category', price: 'Price' };
const describe = (model: SortItem[], none: string): string =>
model.length === 0
? none
: model
.map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(' → ');
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
saved = [];
const off = api.on('sortChanged', ({ sortModel }) =>
log(`Sort now: ${describe(sortModel, 'no sort')}`),
);
return () => off();
}
export const actions = {
preset: (api: GridApi<Row>, value?: string) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
save: (api: GridApi<Row>) => {
saved = api.getSortModel();
say(`Saved: ${describe(saved, 'no sort')}`);
},
restore: (api: GridApi<Row>) => {
api.setSortModel(saved);
say(`Loaded: ${describe(saved, 'no sort')}`);
},
};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">
<select
aria-label="Set sort"
:disabled="!api"
@change="api && actions.preset(api, ($event.target as HTMLSelectElement).value)"
>
<option value="none" selected>No sort</option>
<option value="cheapest">Cheapest first</option>
<option value="byCategory">Category, then price descending</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.save(api)">Save current sort</button>
<button type="button" :disabled="!api" @click="api && actions.restore(api)">Restore saved sort</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, SortItem } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
category: string;
price: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Product', width: 170 },
{ id: 'category', title: 'Category', width: 130 },
{
id: 'price',
title: 'Price ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [
{ id: 1, name: 'Desk lamp', category: 'Lighting', price: 39 },
{ id: 2, name: 'Height-adjustable desk', category: 'Furniture', price: 520 },
{ id: 3, name: 'Monitor arm', category: 'Accessories', price: 85 },
{ id: 4, name: 'Office chair', category: 'Furniture', price: 310 },
{ id: 5, name: 'Cable tray', category: 'Accessories', price: 18 },
{ id: 6, name: 'Floor lamp', category: 'Lighting', price: 95 },
],
rowKey: 'id',
};
// The sort state (sortModel) can be handled outside the grid too. Store the sort the user picked (for example in localStorage
// or a saved view) and give it back later with setSortModel. This example lets you try "save" and "load" by hand.
const PRESETS: Record<string, SortItem[]> = {
none: [],
cheapest: [{ columnId: 'price', direction: 'asc' }],
byCategory: [
{ columnId: 'category', direction: 'asc' },
{ columnId: 'price', direction: 'desc' },
],
};
let saved: SortItem[] = [];
let say: (message: LogText) => void = () => {};
const TITLE: Record<string, string> = { name: 'Product', category: 'Category', price: 'Price' };
const describe = (model: SortItem[], none: string): string =>
model.length === 0
? none
: model
.map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(' → ');
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
saved = [];
const off = api.on('sortChanged', ({ sortModel }) =>
log(`Sort now: ${describe(sortModel, 'no sort')}`),
);
return () => off();
}
export const actions = {
preset: (api: GridApi<Row>, value?: string) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
save: (api: GridApi<Row>) => {
saved = api.getSortModel();
say(`Saved: ${describe(saved, 'no sort')}`);
},
restore: (api: GridApi<Row>) => {
api.setSortModel(saved);
say(`Loaded: ${describe(saved, 'no sort')}`);
},
};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">
<select
aria-label="Set sort"
[disabled]="!api"
(change)="api && actions.preset(api, $any($event.target).value)"
>
<option value="none" selected>No sort</option>
<option value="cheapest">Cheapest first</option>
<option value="byCategory">Category, then price descending</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.save(api)"
>Save current sort</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.restore(api)"
>Restore saved sort</button>
</div>
<mx-grid style="height: 330px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions, SortItem } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
category: string;
price: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Product', width: 170 },
{ id: 'category', title: 'Category', width: 130 },
{
id: 'price',
title: 'Price ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [
{ id: 1, name: 'Desk lamp', category: 'Lighting', price: 39 },
{ id: 2, name: 'Height-adjustable desk', category: 'Furniture', price: 520 },
{ id: 3, name: 'Monitor arm', category: 'Accessories', price: 85 },
{ id: 4, name: 'Office chair', category: 'Furniture', price: 310 },
{ id: 5, name: 'Cable tray', category: 'Accessories', price: 18 },
{ id: 6, name: 'Floor lamp', category: 'Lighting', price: 95 },
],
rowKey: 'id',
};
// The sort state (sortModel) can be handled outside the grid too. Store the sort the user picked (for example in localStorage
// or a saved view) and give it back later with setSortModel. This example lets you try "save" and "load" by hand.
const PRESETS: Record<string, SortItem[]> = {
none: [],
cheapest: [{ columnId: 'price', direction: 'asc' }],
byCategory: [
{ columnId: 'category', direction: 'asc' },
{ columnId: 'price', direction: 'desc' },
],
};
let saved: SortItem[] = [];
let say: (message: LogText) => void = () => {};
const TITLE: Record<string, string> = { name: 'Product', category: 'Category', price: 'Price' };
const describe = (model: SortItem[], none: string): string =>
model.length === 0
? none
: model
.map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(' → ');
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
saved = [];
const off = api.on('sortChanged', ({ sortModel }) =>
log(`Sort now: ${describe(sortModel, 'no sort')}`),
);
return () => off();
}
export const actions = {
preset: (api: GridApi<Row>, value?: string) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
save: (api: GridApi<Row>) => {
saved = api.getSortModel();
say(`Saved: ${describe(saved, 'no sort')}`);
},
restore: (api: GridApi<Row>) => {
api.setSortModel(saved);
say(`Loaded: ${describe(saved, 'no sort')}`);
},
};