걸어 둔 필터를 저장했다가 다시 불러오기Save a filter and bring it back later
필터 칸에 입력해 둔 조건을 그대로 저장했다가, 나중에 한 번에 다시 채워 넣어요. 저장하는 값은 그냥 글자(JSON)라서 브라우저 저장소에 넣어도, 서버나 DB에 보관해도 돼요.Store the conditions typed into the filter cells and refill them later in one step. The saved value is plain JSON, so it fits browser storage, a server or a database.
코드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="save">필터 저장</button>
<button type="button" id="restore">저장한 필터 불러오기</button>
<button type="button" id="clear">필터 지우기</button>
<button type="button" id="forget">저장된 값 지우기</button>
</div>
<div id="grid" style="height: 500px"></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('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('forget').addEventListener('click', () => actions.forget(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '윤지아'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
export const options = {
filterRow: true,
columns: [
{
id: 'name',
title: '이름',
width: 130,
filter: { placeholder: L('이름 일부', 'part of the name') },
},
{ id: 'team', title: '팀', kind: 'select', width: 140 },
{
id: 'salary',
title: '연봉(만원)',
kind: 'number',
width: 140,
align: 'end',
filter: { placeholder: L('예: >=5000', 'e.g. >=5000') },
},
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i % 8],
team: teams[(i * 3) % 4],
salary: 3800 + ((i * 530) % 4200),
})),
rowKey: 'id',
};
// 필터 모델은 그냥 JSON이라 그대로 저장할 수 있어요. 여기서는 브라우저 저장소(localStorage)에 넣어요.
// 저장 공간을 못 쓰는 환경(시크릿 창 등)에서도 오류 없이 안내만 하도록 try/catch로 감싸요.
const KEY = 'gallery-filter-save-restore';
let say = () => { };
const read = () => {
try {
return localStorage.getItem(KEY);
}
catch {
return null;
}
};
export function setup(api, log) {
say = log;
const off = api.on('filterChanged', ({ filterModel }) => log({
ko: filterModel && filterModel.items.length
? `지금 조건 ${filterModel.items.length}개`
: '지금 조건 없음',
en: filterModel && filterModel.items.length
? `${filterModel.items.length} conditions now`
: 'No conditions now',
}));
return () => off();
}
export const actions = {
save: (api) => {
const model = api.getFilterModel();
try {
if (!model || model.items.length === 0) {
localStorage.removeItem(KEY);
say({
ko: '걸린 필터가 없어서 저장된 값을 비웠어요',
en: 'No filter applied, so the saved value was emptied',
});
}
else {
localStorage.setItem(KEY, JSON.stringify(model));
say({
ko: `저장했어요: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`,
en: `Saved: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`,
});
}
}
catch {
say({ ko: '이 브라우저에서는 저장할 수 없어요', en: 'Cannot save in this browser' });
}
},
restore: (api) => {
const raw = read();
if (raw === null)
return say({
ko: '저장된 필터가 없어요. 먼저 필터를 걸고 저장해 보세요',
en: 'No saved filter. Apply a filter first, then save',
});
try {
api.setFilterModel(JSON.parse(raw));
say({ ko: '저장한 필터를 불러왔어요', en: 'Loaded the saved filter' });
}
catch {
say({
ko: '저장된 값을 읽을 수 없어서 불러오지 못했어요',
en: 'Could not read the saved value, so nothing was loaded',
});
}
},
clear: (api) => api.setFilterModel(null),
forget: () => {
try {
localStorage.removeItem(KEY);
say({ ko: '저장된 값을 지웠어요', en: 'Deleted the saved value' });
}
catch {
say({
ko: '이 브라우저에서는 저장 공간을 쓸 수 없어요',
en: 'Storage is not available in this browser',
});
}
},
};<!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="save">필터 저장</button>
<button type="button" id="restore">저장한 필터 불러오기</button>
<button type="button" id="clear">필터 지우기</button>
<button type="button" id="forget">저장된 값 지우기</button>
</div>
<div id="grid" style="height: 500px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '윤지아'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const options = {
filterRow: true,
columns: [
{
id: 'name',
title: '이름',
width: 130,
filter: { placeholder: L('이름 일부', 'part of the name') },
},
{ id: 'team', title: '팀', kind: 'select', width: 140 },
{
id: 'salary',
title: '연봉(만원)',
kind: 'number',
width: 140,
align: 'end',
filter: { placeholder: L('예: >=5000', 'e.g. >=5000') },
},
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i % 8],
team: teams[(i * 3) % 4],
salary: 3800 + ((i * 530) % 4200),
})),
rowKey: 'id',
};
// 필터 모델은 그냥 JSON이라 그대로 저장할 수 있어요. 여기서는 브라우저 저장소(localStorage)에 넣어요.
// 저장 공간을 못 쓰는 환경(시크릿 창 등)에서도 오류 없이 안내만 하도록 try/catch로 감싸요.
const KEY = 'gallery-filter-save-restore';
let say = () => { };
const read = () => {
try {
return localStorage.getItem(KEY);
}
catch {
return null;
}
};
function setup(api, log) {
say = log;
const off = api.on('filterChanged', ({ filterModel }) => log({
ko: filterModel && filterModel.items.length
? `지금 조건 ${filterModel.items.length}개`
: '지금 조건 없음',
en: filterModel && filterModel.items.length
? `${filterModel.items.length} conditions now`
: 'No conditions now',
}));
return () => off();
}
const actions = {
save: (api) => {
const model = api.getFilterModel();
try {
if (!model || model.items.length === 0) {
localStorage.removeItem(KEY);
say({
ko: '걸린 필터가 없어서 저장된 값을 비웠어요',
en: 'No filter applied, so the saved value was emptied',
});
}
else {
localStorage.setItem(KEY, JSON.stringify(model));
say({
ko: `저장했어요: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`,
en: `Saved: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`,
});
}
}
catch {
say({ ko: '이 브라우저에서는 저장할 수 없어요', en: 'Cannot save in this browser' });
}
},
restore: (api) => {
const raw = read();
if (raw === null)
return say({
ko: '저장된 필터가 없어요. 먼저 필터를 걸고 저장해 보세요',
en: 'No saved filter. Apply a filter first, then save',
});
try {
api.setFilterModel(JSON.parse(raw));
say({ ko: '저장한 필터를 불러왔어요', en: 'Loaded the saved filter' });
}
catch {
say({
ko: '저장된 값을 읽을 수 없어서 불러오지 못했어요',
en: 'Could not read the saved value, so nothing was loaded',
});
}
},
clear: (api) => api.setFilterModel(null),
forget: () => {
try {
localStorage.removeItem(KEY);
say({ ko: '저장된 값을 지웠어요', en: 'Deleted the saved value' });
}
catch {
say({
ko: '이 브라우저에서는 저장 공간을 쓸 수 없어요',
en: 'Storage is not available in this browser',
});
}
},
};
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('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('forget').addEventListener('click', () => actions.forget(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.save(api)}
>필터 저장</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.restore(api)}
>저장한 필터 불러오기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>필터 지우기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.forget(api)}
>저장된 값 지우기</button>
</div>
<Grid style={{ height: 500 }} ref={gridRef} options={options} />
</>
);
}import type { FilterModel, GridApi, GridOptions } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
salary: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '윤지아'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
export const options: GridOptions<Row> = {
filterRow: true,
columns: [
{
id: 'name',
title: '이름',
width: 130,
filter: { placeholder: L('이름 일부', 'part of the name') },
},
{ id: 'team', title: '팀', kind: 'select', width: 140 },
{
id: 'salary',
title: '연봉(만원)',
kind: 'number',
width: 140,
align: 'end',
filter: { placeholder: L('예: >=5000', 'e.g. >=5000') },
},
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i % 8] as string,
team: teams[(i * 3) % 4] as string,
salary: 3800 + ((i * 530) % 4200),
})),
rowKey: 'id',
};
// 필터 모델은 그냥 JSON이라 그대로 저장할 수 있어요. 여기서는 브라우저 저장소(localStorage)에 넣어요.
// 저장 공간을 못 쓰는 환경(시크릿 창 등)에서도 오류 없이 안내만 하도록 try/catch로 감싸요.
const KEY = 'gallery-filter-save-restore';
let say: (message: LogText) => void = () => {};
const read = (): string | null => {
try {
return localStorage.getItem(KEY);
} catch {
return null;
}
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('filterChanged', ({ filterModel }) =>
log({
ko:
filterModel && filterModel.items.length
? `지금 조건 ${filterModel.items.length}개`
: '지금 조건 없음',
en:
filterModel && filterModel.items.length
? `${filterModel.items.length} conditions now`
: 'No conditions now',
}),
);
return () => off();
}
export const actions = {
save: (api: GridApi<Row>) => {
const model = api.getFilterModel();
try {
if (!model || model.items.length === 0) {
localStorage.removeItem(KEY);
say({
ko: '걸린 필터가 없어서 저장된 값을 비웠어요',
en: 'No filter applied, so the saved value was emptied',
});
} else {
localStorage.setItem(KEY, JSON.stringify(model));
say({
ko: `저장했어요: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`,
en: `Saved: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`,
});
}
} catch {
say({ ko: '이 브라우저에서는 저장할 수 없어요', en: 'Cannot save in this browser' });
}
},
restore: (api: GridApi<Row>) => {
const raw = read();
if (raw === null)
return say({
ko: '저장된 필터가 없어요. 먼저 필터를 걸고 저장해 보세요',
en: 'No saved filter. Apply a filter first, then save',
});
try {
api.setFilterModel(JSON.parse(raw) as FilterModel);
say({ ko: '저장한 필터를 불러왔어요', en: 'Loaded the saved filter' });
} catch {
say({
ko: '저장된 값을 읽을 수 없어서 불러오지 못했어요',
en: 'Could not read the saved value, so nothing was loaded',
});
}
},
clear: (api: GridApi<Row>) => api.setFilterModel(null),
forget: () => {
try {
localStorage.removeItem(KEY);
say({ ko: '저장된 값을 지웠어요', en: 'Deleted the saved value' });
} catch {
say({
ko: '이 브라우저에서는 저장 공간을 쓸 수 없어요',
en: 'Storage is not available in this browser',
});
}
},
};버튼을 누르면 이 예제의 코드가 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.save(api)">필터 저장</button>
<button type="button" :disabled="!api" @click="api && actions.restore(api)">저장한 필터 불러오기</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">필터 지우기</button>
<button type="button" :disabled="!api" @click="api && actions.forget(api)">저장된 값 지우기</button>
</div>
<Grid style="height: 500px" :options="options" @ready="onReady" />
</template>import type { FilterModel, GridApi, GridOptions } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
salary: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '윤지아'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
export const options: GridOptions<Row> = {
filterRow: true,
columns: [
{
id: 'name',
title: '이름',
width: 130,
filter: { placeholder: L('이름 일부', 'part of the name') },
},
{ id: 'team', title: '팀', kind: 'select', width: 140 },
{
id: 'salary',
title: '연봉(만원)',
kind: 'number',
width: 140,
align: 'end',
filter: { placeholder: L('예: >=5000', 'e.g. >=5000') },
},
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i % 8] as string,
team: teams[(i * 3) % 4] as string,
salary: 3800 + ((i * 530) % 4200),
})),
rowKey: 'id',
};
// 필터 모델은 그냥 JSON이라 그대로 저장할 수 있어요. 여기서는 브라우저 저장소(localStorage)에 넣어요.
// 저장 공간을 못 쓰는 환경(시크릿 창 등)에서도 오류 없이 안내만 하도록 try/catch로 감싸요.
const KEY = 'gallery-filter-save-restore';
let say: (message: LogText) => void = () => {};
const read = (): string | null => {
try {
return localStorage.getItem(KEY);
} catch {
return null;
}
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('filterChanged', ({ filterModel }) =>
log({
ko:
filterModel && filterModel.items.length
? `지금 조건 ${filterModel.items.length}개`
: '지금 조건 없음',
en:
filterModel && filterModel.items.length
? `${filterModel.items.length} conditions now`
: 'No conditions now',
}),
);
return () => off();
}
export const actions = {
save: (api: GridApi<Row>) => {
const model = api.getFilterModel();
try {
if (!model || model.items.length === 0) {
localStorage.removeItem(KEY);
say({
ko: '걸린 필터가 없어서 저장된 값을 비웠어요',
en: 'No filter applied, so the saved value was emptied',
});
} else {
localStorage.setItem(KEY, JSON.stringify(model));
say({
ko: `저장했어요: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`,
en: `Saved: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`,
});
}
} catch {
say({ ko: '이 브라우저에서는 저장할 수 없어요', en: 'Cannot save in this browser' });
}
},
restore: (api: GridApi<Row>) => {
const raw = read();
if (raw === null)
return say({
ko: '저장된 필터가 없어요. 먼저 필터를 걸고 저장해 보세요',
en: 'No saved filter. Apply a filter first, then save',
});
try {
api.setFilterModel(JSON.parse(raw) as FilterModel);
say({ ko: '저장한 필터를 불러왔어요', en: 'Loaded the saved filter' });
} catch {
say({
ko: '저장된 값을 읽을 수 없어서 불러오지 못했어요',
en: 'Could not read the saved value, so nothing was loaded',
});
}
},
clear: (api: GridApi<Row>) => api.setFilterModel(null),
forget: () => {
try {
localStorage.removeItem(KEY);
say({ ko: '저장된 값을 지웠어요', en: 'Deleted the saved value' });
} catch {
say({
ko: '이 브라우저에서는 저장 공간을 쓸 수 없어요',
en: 'Storage is not available in this browser',
});
}
},
};버튼을 누르면 이 예제의 코드가 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.save(api)"
>필터 저장</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.restore(api)"
>저장한 필터 불러오기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>필터 지우기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.forget(api)"
>저장된 값 지우기</button>
</div>
<mx-grid style="height: 500px" [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 { FilterModel, GridApi, GridOptions } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
salary: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '윤지아'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
export const options: GridOptions<Row> = {
filterRow: true,
columns: [
{
id: 'name',
title: '이름',
width: 130,
filter: { placeholder: L('이름 일부', 'part of the name') },
},
{ id: 'team', title: '팀', kind: 'select', width: 140 },
{
id: 'salary',
title: '연봉(만원)',
kind: 'number',
width: 140,
align: 'end',
filter: { placeholder: L('예: >=5000', 'e.g. >=5000') },
},
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i % 8] as string,
team: teams[(i * 3) % 4] as string,
salary: 3800 + ((i * 530) % 4200),
})),
rowKey: 'id',
};
// 필터 모델은 그냥 JSON이라 그대로 저장할 수 있어요. 여기서는 브라우저 저장소(localStorage)에 넣어요.
// 저장 공간을 못 쓰는 환경(시크릿 창 등)에서도 오류 없이 안내만 하도록 try/catch로 감싸요.
const KEY = 'gallery-filter-save-restore';
let say: (message: LogText) => void = () => {};
const read = (): string | null => {
try {
return localStorage.getItem(KEY);
} catch {
return null;
}
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('filterChanged', ({ filterModel }) =>
log({
ko:
filterModel && filterModel.items.length
? `지금 조건 ${filterModel.items.length}개`
: '지금 조건 없음',
en:
filterModel && filterModel.items.length
? `${filterModel.items.length} conditions now`
: 'No conditions now',
}),
);
return () => off();
}
export const actions = {
save: (api: GridApi<Row>) => {
const model = api.getFilterModel();
try {
if (!model || model.items.length === 0) {
localStorage.removeItem(KEY);
say({
ko: '걸린 필터가 없어서 저장된 값을 비웠어요',
en: 'No filter applied, so the saved value was emptied',
});
} else {
localStorage.setItem(KEY, JSON.stringify(model));
say({
ko: `저장했어요: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`,
en: `Saved: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`,
});
}
} catch {
say({ ko: '이 브라우저에서는 저장할 수 없어요', en: 'Cannot save in this browser' });
}
},
restore: (api: GridApi<Row>) => {
const raw = read();
if (raw === null)
return say({
ko: '저장된 필터가 없어요. 먼저 필터를 걸고 저장해 보세요',
en: 'No saved filter. Apply a filter first, then save',
});
try {
api.setFilterModel(JSON.parse(raw) as FilterModel);
say({ ko: '저장한 필터를 불러왔어요', en: 'Loaded the saved filter' });
} catch {
say({
ko: '저장된 값을 읽을 수 없어서 불러오지 못했어요',
en: 'Could not read the saved value, so nothing was loaded',
});
}
},
clear: (api: GridApi<Row>) => api.setFilterModel(null),
forget: () => {
try {
localStorage.removeItem(KEY);
say({ ko: '저장된 값을 지웠어요', en: 'Deleted the saved value' });
} catch {
say({
ko: '이 브라우저에서는 저장 공간을 쓸 수 없어요',
en: 'Storage is not available in this browser',
});
}
},
};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="save">Save filter</button>
<button type="button" id="restore">Restore saved filter</button>
<button type="button" id="clear">Clear filter</button>
<button type="button" id="forget">Delete saved value</button>
</div>
<div id="grid" style="height: 500px"></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('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('forget').addEventListener('click', () => actions.forget(api));const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
export const options = {
filterRow: true,
columns: [
{
id: 'name',
title: 'Name',
width: 140,
filter: { placeholder: 'part of the name' },
},
{ id: 'team', title: 'Team', kind: 'select', width: 140 },
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 140,
align: 'end',
filter: { placeholder: 'e.g. >=50000' },
},
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i % 8],
team: teams[(i * 3) % 4],
salary: 38000 + ((i * 5300) % 42000),
})),
rowKey: 'id',
};
// A filter model is plain JSON, so it can be stored as is. Here it goes into browser storage (localStorage).
// It is wrapped in try/catch so environments without storage (private windows and so on) only get a message, not an error.
const KEY = 'gallery-filter-save-restore';
let say = () => { };
const read = () => {
try {
return localStorage.getItem(KEY);
}
catch {
return null;
}
};
export function setup(api, log) {
say = log;
const off = api.on('filterChanged', ({ filterModel }) => log(filterModel && filterModel.items.length
? `${filterModel.items.length} conditions now`
: 'No conditions now'));
return () => off();
}
export const actions = {
save: (api) => {
const model = api.getFilterModel();
try {
if (!model || model.items.length === 0) {
localStorage.removeItem(KEY);
say('No filter applied, so the saved value was emptied');
}
else {
localStorage.setItem(KEY, JSON.stringify(model));
say(`Saved: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`);
}
}
catch {
say('Cannot save in this browser');
}
},
restore: (api) => {
const raw = read();
if (raw === null)
return say('No saved filter. Apply a filter first, then save');
try {
api.setFilterModel(JSON.parse(raw));
say('Loaded the saved filter');
}
catch {
say('Could not read the saved value, so nothing was loaded');
}
},
clear: (api) => api.setFilterModel(null),
forget: () => {
try {
localStorage.removeItem(KEY);
say('Deleted the saved value');
}
catch {
say('Storage is not available in this browser');
}
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Save a filter and bring it back later</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="save">Save filter</button>
<button type="button" id="restore">Restore saved filter</button>
<button type="button" id="clear">Clear filter</button>
<button type="button" id="forget">Delete saved value</button>
</div>
<div id="grid" style="height: 500px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const options = {
filterRow: true,
columns: [
{
id: 'name',
title: 'Name',
width: 140,
filter: { placeholder: 'part of the name' },
},
{ id: 'team', title: 'Team', kind: 'select', width: 140 },
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 140,
align: 'end',
filter: { placeholder: 'e.g. >=50000' },
},
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i % 8],
team: teams[(i * 3) % 4],
salary: 38000 + ((i * 5300) % 42000),
})),
rowKey: 'id',
};
// A filter model is plain JSON, so it can be stored as is. Here it goes into browser storage (localStorage).
// It is wrapped in try/catch so environments without storage (private windows and so on) only get a message, not an error.
const KEY = 'gallery-filter-save-restore';
let say = () => { };
const read = () => {
try {
return localStorage.getItem(KEY);
}
catch {
return null;
}
};
function setup(api, log) {
say = log;
const off = api.on('filterChanged', ({ filterModel }) => log(filterModel && filterModel.items.length
? `${filterModel.items.length} conditions now`
: 'No conditions now'));
return () => off();
}
const actions = {
save: (api) => {
const model = api.getFilterModel();
try {
if (!model || model.items.length === 0) {
localStorage.removeItem(KEY);
say('No filter applied, so the saved value was emptied');
}
else {
localStorage.setItem(KEY, JSON.stringify(model));
say(`Saved: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`);
}
}
catch {
say('Cannot save in this browser');
}
},
restore: (api) => {
const raw = read();
if (raw === null)
return say('No saved filter. Apply a filter first, then save');
try {
api.setFilterModel(JSON.parse(raw));
say('Loaded the saved filter');
}
catch {
say('Could not read the saved value, so nothing was loaded');
}
},
clear: (api) => api.setFilterModel(null),
forget: () => {
try {
localStorage.removeItem(KEY);
say('Deleted the saved value');
}
catch {
say('Storage is not available in this browser');
}
},
};
options.ariaLabel = "Save a filter and bring it back later";
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('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('forget').addEventListener('click', () => actions.forget(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.save(api)}
>Save filter</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.restore(api)}
>Restore saved filter</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear filter</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.forget(api)}
>Delete saved value</button>
</div>
<Grid style={{ height: 500 }} ref={gridRef} options={options} />
</>
);
}import type { FilterModel, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
team: string;
salary: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
export const options: GridOptions<Row> = {
filterRow: true,
columns: [
{
id: 'name',
title: 'Name',
width: 140,
filter: { placeholder: 'part of the name' },
},
{ id: 'team', title: 'Team', kind: 'select', width: 140 },
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 140,
align: 'end',
filter: { placeholder: 'e.g. >=50000' },
},
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i % 8] as string,
team: teams[(i * 3) % 4] as string,
salary: 38000 + ((i * 5300) % 42000),
})),
rowKey: 'id',
};
// A filter model is plain JSON, so it can be stored as is. Here it goes into browser storage (localStorage).
// It is wrapped in try/catch so environments without storage (private windows and so on) only get a message, not an error.
const KEY = 'gallery-filter-save-restore';
let say: (message: LogText) => void = () => {};
const read = (): string | null => {
try {
return localStorage.getItem(KEY);
} catch {
return null;
}
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('filterChanged', ({ filterModel }) =>
log(
filterModel && filterModel.items.length
? `${filterModel.items.length} conditions now`
: 'No conditions now',
),
);
return () => off();
}
export const actions = {
save: (api: GridApi<Row>) => {
const model = api.getFilterModel();
try {
if (!model || model.items.length === 0) {
localStorage.removeItem(KEY);
say('No filter applied, so the saved value was emptied');
} else {
localStorage.setItem(KEY, JSON.stringify(model));
say(`Saved: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`);
}
} catch {
say('Cannot save in this browser');
}
},
restore: (api: GridApi<Row>) => {
const raw = read();
if (raw === null) return say('No saved filter. Apply a filter first, then save');
try {
api.setFilterModel(JSON.parse(raw) as FilterModel);
say('Loaded the saved filter');
} catch {
say('Could not read the saved value, so nothing was loaded');
}
},
clear: (api: GridApi<Row>) => api.setFilterModel(null),
forget: () => {
try {
localStorage.removeItem(KEY);
say('Deleted the saved value');
} catch {
say('Storage is not available in this browser');
}
},
};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.save(api)">Save filter</button>
<button type="button" :disabled="!api" @click="api && actions.restore(api)">Restore saved filter</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear filter</button>
<button type="button" :disabled="!api" @click="api && actions.forget(api)">Delete saved value</button>
</div>
<Grid style="height: 500px" :options="options" @ready="onReady" />
</template>import type { FilterModel, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
team: string;
salary: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
export const options: GridOptions<Row> = {
filterRow: true,
columns: [
{
id: 'name',
title: 'Name',
width: 140,
filter: { placeholder: 'part of the name' },
},
{ id: 'team', title: 'Team', kind: 'select', width: 140 },
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 140,
align: 'end',
filter: { placeholder: 'e.g. >=50000' },
},
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i % 8] as string,
team: teams[(i * 3) % 4] as string,
salary: 38000 + ((i * 5300) % 42000),
})),
rowKey: 'id',
};
// A filter model is plain JSON, so it can be stored as is. Here it goes into browser storage (localStorage).
// It is wrapped in try/catch so environments without storage (private windows and so on) only get a message, not an error.
const KEY = 'gallery-filter-save-restore';
let say: (message: LogText) => void = () => {};
const read = (): string | null => {
try {
return localStorage.getItem(KEY);
} catch {
return null;
}
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('filterChanged', ({ filterModel }) =>
log(
filterModel && filterModel.items.length
? `${filterModel.items.length} conditions now`
: 'No conditions now',
),
);
return () => off();
}
export const actions = {
save: (api: GridApi<Row>) => {
const model = api.getFilterModel();
try {
if (!model || model.items.length === 0) {
localStorage.removeItem(KEY);
say('No filter applied, so the saved value was emptied');
} else {
localStorage.setItem(KEY, JSON.stringify(model));
say(`Saved: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`);
}
} catch {
say('Cannot save in this browser');
}
},
restore: (api: GridApi<Row>) => {
const raw = read();
if (raw === null) return say('No saved filter. Apply a filter first, then save');
try {
api.setFilterModel(JSON.parse(raw) as FilterModel);
say('Loaded the saved filter');
} catch {
say('Could not read the saved value, so nothing was loaded');
}
},
clear: (api: GridApi<Row>) => api.setFilterModel(null),
forget: () => {
try {
localStorage.removeItem(KEY);
say('Deleted the saved value');
} catch {
say('Storage is not available in this browser');
}
},
};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.save(api)"
>Save filter</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.restore(api)"
>Restore saved filter</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear filter</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.forget(api)"
>Delete saved value</button>
</div>
<mx-grid style="height: 500px" [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 { FilterModel, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
team: string;
salary: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
export const options: GridOptions<Row> = {
filterRow: true,
columns: [
{
id: 'name',
title: 'Name',
width: 140,
filter: { placeholder: 'part of the name' },
},
{ id: 'team', title: 'Team', kind: 'select', width: 140 },
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 140,
align: 'end',
filter: { placeholder: 'e.g. >=50000' },
},
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i % 8] as string,
team: teams[(i * 3) % 4] as string,
salary: 38000 + ((i * 5300) % 42000),
})),
rowKey: 'id',
};
// A filter model is plain JSON, so it can be stored as is. Here it goes into browser storage (localStorage).
// It is wrapped in try/catch so environments without storage (private windows and so on) only get a message, not an error.
const KEY = 'gallery-filter-save-restore';
let say: (message: LogText) => void = () => {};
const read = (): string | null => {
try {
return localStorage.getItem(KEY);
} catch {
return null;
}
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const off = api.on('filterChanged', ({ filterModel }) =>
log(
filterModel && filterModel.items.length
? `${filterModel.items.length} conditions now`
: 'No conditions now',
),
);
return () => off();
}
export const actions = {
save: (api: GridApi<Row>) => {
const model = api.getFilterModel();
try {
if (!model || model.items.length === 0) {
localStorage.removeItem(KEY);
say('No filter applied, so the saved value was emptied');
} else {
localStorage.setItem(KEY, JSON.stringify(model));
say(`Saved: ${model.items.map((i) => `${i.columnId} ${i.operator}`).join(', ')}`);
}
} catch {
say('Cannot save in this browser');
}
},
restore: (api: GridApi<Row>) => {
const raw = read();
if (raw === null) return say('No saved filter. Apply a filter first, then save');
try {
api.setFilterModel(JSON.parse(raw) as FilterModel);
say('Loaded the saved filter');
} catch {
say('Could not read the saved value, so nothing was loaded');
}
},
clear: (api: GridApi<Row>) => api.setFilterModel(null),
forget: () => {
try {
localStorage.removeItem(KEY);
say('Deleted the saved value');
} catch {
say('Storage is not available in this browser');
}
},
};