필터를 주소 글자로 바꾸고 되살리기 (주소창 흉내)Turn a filter into address text and back (address bar simulated)
필터를 걸 때마다 조건을 '?dept=개발팀&min=500' 같은 주소 글자로 바꿔 보여 줘요. 그 글자를 읽어 같은 필터를 다시 걸 수도 있어요. 이 미리보기 안에서는 실제 주소창을 바꿀 수 없어서 아래 줄이 주소창을 대신해요.Each filter change is turned into address text such as ?dept=...&min=500, and the same filter can be rebuilt from that text. The preview cannot change the real address bar, so the line below stands in for it.
코드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="dept">
<option value="all" selected>전체 부서 (기본)</option>
<option value="dev">개발팀</option>
<option value="design">디자인팀</option>
<option value="sales">영업팀</option>
</select>
<select aria-label="최소 월급" id="minSalary">
<option value="0" selected>제한 없음 (기본)</option>
<option value="400">400만원 이상</option>
<option value="500">500만원 이상</option>
</select>
<button type="button" id="clear">모두 지우기</button>
<button type="button" id="openLink">링크 열기 흉내</button>
</div>
<div id="grid" style="height: 440px"></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('dept').addEventListener('change', (event) => actions.dept(api, event.target.value));
document.getElementById('minSalary').addEventListener('change', (event) => actions.minSalary(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('openLink').addEventListener('click', () => actions.openLink(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
];
const depts = ['개발팀', '디자인팀', '영업팀'];
// 선택 목록의 값(영문 id)과 데이터의 부서 이름을 맞바꿔요.
const DEPT_BY_ID = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[i % 3],
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
// 이 화면이 만들 수 있는 조건만 쿼리 글자로 적고, 읽을 때도 그 조건만 받아요.
// 그래서 주소에 이상한 글자가 들어와도 그리드에는 예상한 조건만 전달돼요.
function toQuery(model) {
const params = new URLSearchParams();
for (const item of model?.items ?? []) {
if (item.columnId === 'dept')
params.set('dept', String(item.value));
if (item.columnId === 'salary')
params.set('min', String(item.value));
}
return params.toString();
}
function fromQuery(query) {
const params = new URLSearchParams(query);
const items = [];
const dept = params.get('dept');
const min = Number(params.get('min'));
if (dept && depts.includes(dept))
items.push({ columnId: 'dept', operator: 'equals', value: dept });
if (params.get('min') && Number.isFinite(min)) {
items.push({ columnId: 'salary', operator: 'gte', value: min });
}
return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // 실제 앱에서는 history.replaceState(null, '', `?${query}`)로 쓰고, 열 때 location.search를 읽어요
let bar = null;
const put = (id, value) => {
const el = document.getElementById(id);
if (el instanceof HTMLSelectElement)
el.value = value;
};
const show = () => {
if (bar)
bar.textContent = L(`주소창 대신 보여 주는 줄: ?${decodeURIComponent(saved)}`, `Line shown instead of the address bar: ?${decodeURIComponent(saved)}`);
};
export function setup(api, log) {
state.dept = '';
state.min = '';
saved = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
show();
const off = api.on('filterChanged', ({ filterModel }) => {
saved = toQuery(filterModel);
show();
// 어떤 경로로 조건이 바뀌어도(링크 열기 포함) 위 선택 목록이 표와 어긋나지 않게 맞춰요.
const item = (id) => filterModel?.items.find((it) => it.columnId === id);
put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
put('minSalary', String(item('salary')?.value ?? '0'));
log({
ko: `주소창 대신 보여 주는 줄에 적었어요: ?${decodeURIComponent(saved)}`,
en: `Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`,
});
});
return () => {
off();
bar?.remove();
bar = null;
};
}
export const actions = {
dept: (api, value) => {
state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
minSalary: (api, value) => {
state.min = value && value !== '0' ? value : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
clear: (api) => {
state.dept = '';
state.min = '';
api.setFilterModel(null);
},
// 누군가 ?dept=영업팀&min=400 링크를 열었다고 치고, 그 쿼리를 읽어 필터를 되살려요(새로고침할 때와 같은 일이에요).
openLink: (api) => {
const query = 'dept=영업팀&min=400';
state.dept = '영업팀';
state.min = '400';
api.setFilterModel(fromQuery(query));
},
};<!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="dept">
<option value="all" selected>전체 부서 (기본)</option>
<option value="dev">개발팀</option>
<option value="design">디자인팀</option>
<option value="sales">영업팀</option>
</select>
<select aria-label="최소 월급" id="minSalary">
<option value="0" selected>제한 없음 (기본)</option>
<option value="400">400만원 이상</option>
<option value="500">500만원 이상</option>
</select>
<button type="button" id="clear">모두 지우기</button>
<button type="button" id="openLink">링크 열기 흉내</button>
</div>
<div id="grid" style="height: 440px"></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 depts = ['개발팀', '디자인팀', '영업팀'];
// 선택 목록의 값(영문 id)과 데이터의 부서 이름을 맞바꿔요.
const DEPT_BY_ID = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
const options = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[i % 3],
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
// 이 화면이 만들 수 있는 조건만 쿼리 글자로 적고, 읽을 때도 그 조건만 받아요.
// 그래서 주소에 이상한 글자가 들어와도 그리드에는 예상한 조건만 전달돼요.
function toQuery(model) {
const params = new URLSearchParams();
for (const item of model?.items ?? []) {
if (item.columnId === 'dept')
params.set('dept', String(item.value));
if (item.columnId === 'salary')
params.set('min', String(item.value));
}
return params.toString();
}
function fromQuery(query) {
const params = new URLSearchParams(query);
const items = [];
const dept = params.get('dept');
const min = Number(params.get('min'));
if (dept && depts.includes(dept))
items.push({ columnId: 'dept', operator: 'equals', value: dept });
if (params.get('min') && Number.isFinite(min)) {
items.push({ columnId: 'salary', operator: 'gte', value: min });
}
return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // 실제 앱에서는 history.replaceState(null, '', `?${query}`)로 쓰고, 열 때 location.search를 읽어요
let bar = null;
const put = (id, value) => {
const el = document.getElementById(id);
if (el instanceof HTMLSelectElement)
el.value = value;
};
const show = () => {
if (bar)
bar.textContent = L(`주소창 대신 보여 주는 줄: ?${decodeURIComponent(saved)}`, `Line shown instead of the address bar: ?${decodeURIComponent(saved)}`);
};
function setup(api, log) {
state.dept = '';
state.min = '';
saved = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
show();
const off = api.on('filterChanged', ({ filterModel }) => {
saved = toQuery(filterModel);
show();
// 어떤 경로로 조건이 바뀌어도(링크 열기 포함) 위 선택 목록이 표와 어긋나지 않게 맞춰요.
const item = (id) => filterModel?.items.find((it) => it.columnId === id);
put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
put('minSalary', String(item('salary')?.value ?? '0'));
log({
ko: `주소창 대신 보여 주는 줄에 적었어요: ?${decodeURIComponent(saved)}`,
en: `Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`,
});
});
return () => {
off();
bar?.remove();
bar = null;
};
}
const actions = {
dept: (api, value) => {
state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
minSalary: (api, value) => {
state.min = value && value !== '0' ? value : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
clear: (api) => {
state.dept = '';
state.min = '';
api.setFilterModel(null);
},
// 누군가 ?dept=영업팀&min=400 링크를 열었다고 치고, 그 쿼리를 읽어 필터를 되살려요(새로고침할 때와 같은 일이에요).
openLink: (api) => {
const query = 'dept=영업팀&min=400';
state.dept = '영업팀';
state.min = '400';
api.setFilterModel(fromQuery(query));
},
};
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('dept').addEventListener('change', (event) => actions.dept(api, event.target.value));
document.getElementById('minSalary').addEventListener('change', (event) => actions.minSalary(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('openLink').addEventListener('click', () => actions.openLink(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.dept(api, event.target.value)}
>
<option value="all">전체 부서 (기본)</option>
<option value="dev">개발팀</option>
<option value="design">디자인팀</option>
<option value="sales">영업팀</option>
</select>
<select defaultValue="all"
aria-label="최소 월급"
disabled={!api}
onChange={(event) => api && actions.minSalary(api, event.target.value)}
>
<option value="0">제한 없음 (기본)</option>
<option value="400">400만원 이상</option>
<option value="500">500만원 이상</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>모두 지우기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.openLink(api)}
>링크 열기 흉내</button>
</div>
<Grid style={{ height: 440 }} ref={gridRef} options={options} />
</>
);
}import type { FilterItem, 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;
dept: string;
salary: number;
}
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
];
const depts = ['개발팀', '디자인팀', '영업팀'];
// 선택 목록의 값(영문 id)과 데이터의 부서 이름을 맞바꿔요.
const DEPT_BY_ID: Record<string, string> = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
// 이 화면이 만들 수 있는 조건만 쿼리 글자로 적고, 읽을 때도 그 조건만 받아요.
// 그래서 주소에 이상한 글자가 들어와도 그리드에는 예상한 조건만 전달돼요.
function toQuery(model: FilterModel | null): string {
const params = new URLSearchParams();
for (const item of model?.items ?? []) {
if (item.columnId === 'dept') params.set('dept', String(item.value));
if (item.columnId === 'salary') params.set('min', String(item.value));
}
return params.toString();
}
function fromQuery(query: string): FilterModel | null {
const params = new URLSearchParams(query);
const items: FilterItem[] = [];
const dept = params.get('dept');
const min = Number(params.get('min'));
if (dept && depts.includes(dept))
items.push({ columnId: 'dept', operator: 'equals', value: dept });
if (params.get('min') && Number.isFinite(min)) {
items.push({ columnId: 'salary', operator: 'gte', value: min });
}
return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // 실제 앱에서는 history.replaceState(null, '', `?${query}`)로 쓰고, 열 때 location.search를 읽어요
let bar: HTMLElement | null = null;
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
if (el instanceof HTMLSelectElement) el.value = value;
};
const show = (): void => {
if (bar)
bar.textContent = L(
`주소창 대신 보여 주는 줄: ?${decodeURIComponent(saved)}`,
`Line shown instead of the address bar: ?${decodeURIComponent(saved)}`,
);
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
state.dept = '';
state.min = '';
saved = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
show();
const off = api.on('filterChanged', ({ filterModel }) => {
saved = toQuery(filterModel);
show();
// 어떤 경로로 조건이 바뀌어도(링크 열기 포함) 위 선택 목록이 표와 어긋나지 않게 맞춰요.
const item = (id: string): FilterItem | undefined =>
filterModel?.items.find((it) => it.columnId === id);
put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
put('minSalary', String(item('salary')?.value ?? '0'));
log({
ko: `주소창 대신 보여 주는 줄에 적었어요: ?${decodeURIComponent(saved)}`,
en: `Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`,
});
});
return () => {
off();
bar?.remove();
bar = null;
};
}
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
minSalary: (api: GridApi<Row>, value?: string) => {
state.min = value && value !== '0' ? value : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
clear: (api: GridApi<Row>) => {
state.dept = '';
state.min = '';
api.setFilterModel(null);
},
// 누군가 ?dept=영업팀&min=400 링크를 열었다고 치고, 그 쿼리를 읽어 필터를 되살려요(새로고침할 때와 같은 일이에요).
openLink: (api: GridApi<Row>) => {
const query = 'dept=영업팀&min=400';
state.dept = '영업팀';
state.min = '400';
api.setFilterModel(fromQuery(query));
},
};버튼을 누르면 이 예제의 코드가 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.dept(api, ($event.target as HTMLSelectElement).value)"
>
<option value="all" selected>전체 부서 (기본)</option>
<option value="dev">개발팀</option>
<option value="design">디자인팀</option>
<option value="sales">영업팀</option>
</select>
<select
aria-label="최소 월급"
:disabled="!api"
@change="api && actions.minSalary(api, ($event.target as HTMLSelectElement).value)"
>
<option value="0" selected>제한 없음 (기본)</option>
<option value="400">400만원 이상</option>
<option value="500">500만원 이상</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">모두 지우기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.openLink(api)"
>링크 열기 흉내</button>
</div>
<Grid style="height: 440px" :options="options" @ready="onReady" />
</template>import type { FilterItem, 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;
dept: string;
salary: number;
}
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
];
const depts = ['개발팀', '디자인팀', '영업팀'];
// 선택 목록의 값(영문 id)과 데이터의 부서 이름을 맞바꿔요.
const DEPT_BY_ID: Record<string, string> = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
// 이 화면이 만들 수 있는 조건만 쿼리 글자로 적고, 읽을 때도 그 조건만 받아요.
// 그래서 주소에 이상한 글자가 들어와도 그리드에는 예상한 조건만 전달돼요.
function toQuery(model: FilterModel | null): string {
const params = new URLSearchParams();
for (const item of model?.items ?? []) {
if (item.columnId === 'dept') params.set('dept', String(item.value));
if (item.columnId === 'salary') params.set('min', String(item.value));
}
return params.toString();
}
function fromQuery(query: string): FilterModel | null {
const params = new URLSearchParams(query);
const items: FilterItem[] = [];
const dept = params.get('dept');
const min = Number(params.get('min'));
if (dept && depts.includes(dept))
items.push({ columnId: 'dept', operator: 'equals', value: dept });
if (params.get('min') && Number.isFinite(min)) {
items.push({ columnId: 'salary', operator: 'gte', value: min });
}
return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // 실제 앱에서는 history.replaceState(null, '', `?${query}`)로 쓰고, 열 때 location.search를 읽어요
let bar: HTMLElement | null = null;
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
if (el instanceof HTMLSelectElement) el.value = value;
};
const show = (): void => {
if (bar)
bar.textContent = L(
`주소창 대신 보여 주는 줄: ?${decodeURIComponent(saved)}`,
`Line shown instead of the address bar: ?${decodeURIComponent(saved)}`,
);
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
state.dept = '';
state.min = '';
saved = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
show();
const off = api.on('filterChanged', ({ filterModel }) => {
saved = toQuery(filterModel);
show();
// 어떤 경로로 조건이 바뀌어도(링크 열기 포함) 위 선택 목록이 표와 어긋나지 않게 맞춰요.
const item = (id: string): FilterItem | undefined =>
filterModel?.items.find((it) => it.columnId === id);
put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
put('minSalary', String(item('salary')?.value ?? '0'));
log({
ko: `주소창 대신 보여 주는 줄에 적었어요: ?${decodeURIComponent(saved)}`,
en: `Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`,
});
});
return () => {
off();
bar?.remove();
bar = null;
};
}
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
minSalary: (api: GridApi<Row>, value?: string) => {
state.min = value && value !== '0' ? value : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
clear: (api: GridApi<Row>) => {
state.dept = '';
state.min = '';
api.setFilterModel(null);
},
// 누군가 ?dept=영업팀&min=400 링크를 열었다고 치고, 그 쿼리를 읽어 필터를 되살려요(새로고침할 때와 같은 일이에요).
openLink: (api: GridApi<Row>) => {
const query = 'dept=영업팀&min=400';
state.dept = '영업팀';
state.min = '400';
api.setFilterModel(fromQuery(query));
},
};버튼을 누르면 이 예제의 코드가 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.dept(api, $any($event.target).value)"
>
<option value="all" selected>전체 부서 (기본)</option>
<option value="dev">개발팀</option>
<option value="design">디자인팀</option>
<option value="sales">영업팀</option>
</select>
<select
aria-label="최소 월급"
[disabled]="!api"
(change)="api && actions.minSalary(api, $any($event.target).value)"
>
<option value="0" selected>제한 없음 (기본)</option>
<option value="400">400만원 이상</option>
<option value="500">500만원 이상</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>모두 지우기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.openLink(api)"
>링크 열기 흉내</button>
</div>
<mx-grid style="height: 440px" [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 { FilterItem, 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;
dept: string;
salary: number;
}
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
];
const depts = ['개발팀', '디자인팀', '영업팀'];
// 선택 목록의 값(영문 id)과 데이터의 부서 이름을 맞바꿔요.
const DEPT_BY_ID: Record<string, string> = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
// 이 화면이 만들 수 있는 조건만 쿼리 글자로 적고, 읽을 때도 그 조건만 받아요.
// 그래서 주소에 이상한 글자가 들어와도 그리드에는 예상한 조건만 전달돼요.
function toQuery(model: FilterModel | null): string {
const params = new URLSearchParams();
for (const item of model?.items ?? []) {
if (item.columnId === 'dept') params.set('dept', String(item.value));
if (item.columnId === 'salary') params.set('min', String(item.value));
}
return params.toString();
}
function fromQuery(query: string): FilterModel | null {
const params = new URLSearchParams(query);
const items: FilterItem[] = [];
const dept = params.get('dept');
const min = Number(params.get('min'));
if (dept && depts.includes(dept))
items.push({ columnId: 'dept', operator: 'equals', value: dept });
if (params.get('min') && Number.isFinite(min)) {
items.push({ columnId: 'salary', operator: 'gte', value: min });
}
return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // 실제 앱에서는 history.replaceState(null, '', `?${query}`)로 쓰고, 열 때 location.search를 읽어요
let bar: HTMLElement | null = null;
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
if (el instanceof HTMLSelectElement) el.value = value;
};
const show = (): void => {
if (bar)
bar.textContent = L(
`주소창 대신 보여 주는 줄: ?${decodeURIComponent(saved)}`,
`Line shown instead of the address bar: ?${decodeURIComponent(saved)}`,
);
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
state.dept = '';
state.min = '';
saved = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
show();
const off = api.on('filterChanged', ({ filterModel }) => {
saved = toQuery(filterModel);
show();
// 어떤 경로로 조건이 바뀌어도(링크 열기 포함) 위 선택 목록이 표와 어긋나지 않게 맞춰요.
const item = (id: string): FilterItem | undefined =>
filterModel?.items.find((it) => it.columnId === id);
put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
put('minSalary', String(item('salary')?.value ?? '0'));
log({
ko: `주소창 대신 보여 주는 줄에 적었어요: ?${decodeURIComponent(saved)}`,
en: `Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`,
});
});
return () => {
off();
bar?.remove();
bar = null;
};
}
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
minSalary: (api: GridApi<Row>, value?: string) => {
state.min = value && value !== '0' ? value : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
clear: (api: GridApi<Row>) => {
state.dept = '';
state.min = '';
api.setFilterModel(null);
},
// 누군가 ?dept=영업팀&min=400 링크를 열었다고 치고, 그 쿼리를 읽어 필터를 되살려요(새로고침할 때와 같은 일이에요).
openLink: (api: GridApi<Row>) => {
const query = 'dept=영업팀&min=400';
state.dept = '영업팀';
state.min = '400';
api.setFilterModel(fromQuery(query));
},
};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="Department" id="dept">
<option value="all" selected>All (default)</option>
<option value="dev">Development</option>
<option value="design">Design</option>
<option value="sales">Sales</option>
</select>
<select aria-label="Min salary" id="minSalary">
<option value="0" selected>No limit (default)</option>
<option value="400">400+</option>
<option value="500">500+</option>
</select>
<button type="button" id="clear">Clear all</button>
<button type="button" id="openLink">Simulate opening a link</button>
</div>
<div id="grid" style="height: 440px"></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('dept').addEventListener('change', (event) => actions.dept(api, event.target.value));
document.getElementById('minSalary').addEventListener('change', (event) => actions.minSalary(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('openLink').addEventListener('click', () => actions.openLink(api));const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
'Mason Gray',
'Ava Morgan',
'Lucas Hart',
'Mia Foster',
];
const depts = ['Dev', 'Design', 'Sales'];
// Map the select values (ASCII ids from meta.json) to the English dept names in the data.
const DEPT_BY_ID = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'salary',
title: 'Monthly pay ($100)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[i % 3],
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
// Only conditions this screen can create are written to the query string, and only those are accepted when reading.
// So even if odd text appears in the address, the grid receives only the expected conditions.
function toQuery(model) {
const params = new URLSearchParams();
for (const item of model?.items ?? []) {
if (item.columnId === 'dept')
params.set('dept', String(item.value));
if (item.columnId === 'salary')
params.set('min', String(item.value));
}
return params.toString();
}
function fromQuery(query) {
const params = new URLSearchParams(query);
const items = [];
const dept = params.get('dept');
const min = Number(params.get('min'));
if (dept && depts.includes(dept))
items.push({ columnId: 'dept', operator: 'equals', value: dept });
if (params.get('min') && Number.isFinite(min)) {
items.push({ columnId: 'salary', operator: 'gte', value: min });
}
return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // a real app would use history.replaceState(null, '', `?${query}`) to write and read location.search on open
let bar = null;
const put = (id, value) => {
const el = document.getElementById(id);
if (el instanceof HTMLSelectElement)
el.value = value;
};
const show = () => {
if (bar)
bar.textContent = `Line shown instead of the address bar: ?${decodeURIComponent(saved)}`;
};
export function setup(api, log) {
state.dept = '';
state.min = '';
saved = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
show();
const off = api.on('filterChanged', ({ filterModel }) => {
saved = toQuery(filterModel);
show();
// However the condition changes (including opening a link), keep the select lists above in step with the table.
const item = (id) => filterModel?.items.find((it) => it.columnId === id);
put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
put('minSalary', String(item('salary')?.value ?? '0'));
log(`Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`);
});
return () => {
off();
bar?.remove();
bar = null;
};
}
export const actions = {
dept: (api, value) => {
state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
minSalary: (api, value) => {
state.min = value && value !== '0' ? value : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
clear: (api) => {
state.dept = '';
state.min = '';
api.setFilterModel(null);
},
// Pretend someone opened a ?dept=Sales&min=400 link, then read that query to restore the filter (same as on reload).
openLink: (api) => {
const query = 'dept=Sales&min=400';
state.dept = 'Sales';
state.min = '400';
api.setFilterModel(fromQuery(query));
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Turn a filter into address text and back (address bar simulated)</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Department" id="dept">
<option value="all" selected>All (default)</option>
<option value="dev">Development</option>
<option value="design">Design</option>
<option value="sales">Sales</option>
</select>
<select aria-label="Min salary" id="minSalary">
<option value="0" selected>No limit (default)</option>
<option value="400">400+</option>
<option value="500">500+</option>
</select>
<button type="button" id="clear">Clear all</button>
<button type="button" id="openLink">Simulate opening a link</button>
</div>
<div id="grid" style="height: 440px"></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 Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
'Mason Gray',
'Ava Morgan',
'Lucas Hart',
'Mia Foster',
];
const depts = ['Dev', 'Design', 'Sales'];
// Map the select values (ASCII ids from meta.json) to the English dept names in the data.
const DEPT_BY_ID = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
const options = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'salary',
title: 'Monthly pay ($100)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[i % 3],
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
// Only conditions this screen can create are written to the query string, and only those are accepted when reading.
// So even if odd text appears in the address, the grid receives only the expected conditions.
function toQuery(model) {
const params = new URLSearchParams();
for (const item of model?.items ?? []) {
if (item.columnId === 'dept')
params.set('dept', String(item.value));
if (item.columnId === 'salary')
params.set('min', String(item.value));
}
return params.toString();
}
function fromQuery(query) {
const params = new URLSearchParams(query);
const items = [];
const dept = params.get('dept');
const min = Number(params.get('min'));
if (dept && depts.includes(dept))
items.push({ columnId: 'dept', operator: 'equals', value: dept });
if (params.get('min') && Number.isFinite(min)) {
items.push({ columnId: 'salary', operator: 'gte', value: min });
}
return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // a real app would use history.replaceState(null, '', `?${query}`) to write and read location.search on open
let bar = null;
const put = (id, value) => {
const el = document.getElementById(id);
if (el instanceof HTMLSelectElement)
el.value = value;
};
const show = () => {
if (bar)
bar.textContent = `Line shown instead of the address bar: ?${decodeURIComponent(saved)}`;
};
function setup(api, log) {
state.dept = '';
state.min = '';
saved = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
show();
const off = api.on('filterChanged', ({ filterModel }) => {
saved = toQuery(filterModel);
show();
// However the condition changes (including opening a link), keep the select lists above in step with the table.
const item = (id) => filterModel?.items.find((it) => it.columnId === id);
put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
put('minSalary', String(item('salary')?.value ?? '0'));
log(`Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`);
});
return () => {
off();
bar?.remove();
bar = null;
};
}
const actions = {
dept: (api, value) => {
state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
minSalary: (api, value) => {
state.min = value && value !== '0' ? value : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
clear: (api) => {
state.dept = '';
state.min = '';
api.setFilterModel(null);
},
// Pretend someone opened a ?dept=Sales&min=400 link, then read that query to restore the filter (same as on reload).
openLink: (api) => {
const query = 'dept=Sales&min=400';
state.dept = 'Sales';
state.min = '400';
api.setFilterModel(fromQuery(query));
},
};
options.ariaLabel = "Turn a filter into address text and back (address bar simulated)";
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('dept').addEventListener('change', (event) => actions.dept(api, event.target.value));
document.getElementById('minSalary').addEventListener('change', (event) => actions.minSalary(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
document.getElementById('openLink').addEventListener('click', () => actions.openLink(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="Department"
disabled={!api}
onChange={(event) => api && actions.dept(api, event.target.value)}
>
<option value="all">All (default)</option>
<option value="dev">Development</option>
<option value="design">Design</option>
<option value="sales">Sales</option>
</select>
<select defaultValue="all"
aria-label="Min salary"
disabled={!api}
onChange={(event) => api && actions.minSalary(api, event.target.value)}
>
<option value="0">No limit (default)</option>
<option value="400">400+</option>
<option value="500">500+</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear all</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.openLink(api)}
>Simulate opening a link</button>
</div>
<Grid style={{ height: 440 }} ref={gridRef} options={options} />
</>
);
}import type { FilterItem, FilterModel, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
'Mason Gray',
'Ava Morgan',
'Lucas Hart',
'Mia Foster',
];
const depts = ['Dev', 'Design', 'Sales'];
// Map the select values (ASCII ids from meta.json) to the English dept names in the data.
const DEPT_BY_ID: Record<string, string> = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'salary',
title: 'Monthly pay ($100)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
// Only conditions this screen can create are written to the query string, and only those are accepted when reading.
// So even if odd text appears in the address, the grid receives only the expected conditions.
function toQuery(model: FilterModel | null): string {
const params = new URLSearchParams();
for (const item of model?.items ?? []) {
if (item.columnId === 'dept') params.set('dept', String(item.value));
if (item.columnId === 'salary') params.set('min', String(item.value));
}
return params.toString();
}
function fromQuery(query: string): FilterModel | null {
const params = new URLSearchParams(query);
const items: FilterItem[] = [];
const dept = params.get('dept');
const min = Number(params.get('min'));
if (dept && depts.includes(dept))
items.push({ columnId: 'dept', operator: 'equals', value: dept });
if (params.get('min') && Number.isFinite(min)) {
items.push({ columnId: 'salary', operator: 'gte', value: min });
}
return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // a real app would use history.replaceState(null, '', `?${query}`) to write and read location.search on open
let bar: HTMLElement | null = null;
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
if (el instanceof HTMLSelectElement) el.value = value;
};
const show = (): void => {
if (bar) bar.textContent = `Line shown instead of the address bar: ?${decodeURIComponent(saved)}`;
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
state.dept = '';
state.min = '';
saved = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
show();
const off = api.on('filterChanged', ({ filterModel }) => {
saved = toQuery(filterModel);
show();
// However the condition changes (including opening a link), keep the select lists above in step with the table.
const item = (id: string): FilterItem | undefined =>
filterModel?.items.find((it) => it.columnId === id);
put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
put('minSalary', String(item('salary')?.value ?? '0'));
log(`Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`);
});
return () => {
off();
bar?.remove();
bar = null;
};
}
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
minSalary: (api: GridApi<Row>, value?: string) => {
state.min = value && value !== '0' ? value : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
clear: (api: GridApi<Row>) => {
state.dept = '';
state.min = '';
api.setFilterModel(null);
},
// Pretend someone opened a ?dept=Sales&min=400 link, then read that query to restore the filter (same as on reload).
openLink: (api: GridApi<Row>) => {
const query = 'dept=Sales&min=400';
state.dept = 'Sales';
state.min = '400';
api.setFilterModel(fromQuery(query));
},
};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="Department"
:disabled="!api"
@change="api && actions.dept(api, ($event.target as HTMLSelectElement).value)"
>
<option value="all" selected>All (default)</option>
<option value="dev">Development</option>
<option value="design">Design</option>
<option value="sales">Sales</option>
</select>
<select
aria-label="Min salary"
:disabled="!api"
@change="api && actions.minSalary(api, ($event.target as HTMLSelectElement).value)"
>
<option value="0" selected>No limit (default)</option>
<option value="400">400+</option>
<option value="500">500+</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear all</button>
<button
type="button"
:disabled="!api"
@click="api && actions.openLink(api)"
>Simulate opening a link</button>
</div>
<Grid style="height: 440px" :options="options" @ready="onReady" />
</template>import type { FilterItem, FilterModel, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
'Mason Gray',
'Ava Morgan',
'Lucas Hart',
'Mia Foster',
];
const depts = ['Dev', 'Design', 'Sales'];
// Map the select values (ASCII ids from meta.json) to the English dept names in the data.
const DEPT_BY_ID: Record<string, string> = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'salary',
title: 'Monthly pay ($100)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
// Only conditions this screen can create are written to the query string, and only those are accepted when reading.
// So even if odd text appears in the address, the grid receives only the expected conditions.
function toQuery(model: FilterModel | null): string {
const params = new URLSearchParams();
for (const item of model?.items ?? []) {
if (item.columnId === 'dept') params.set('dept', String(item.value));
if (item.columnId === 'salary') params.set('min', String(item.value));
}
return params.toString();
}
function fromQuery(query: string): FilterModel | null {
const params = new URLSearchParams(query);
const items: FilterItem[] = [];
const dept = params.get('dept');
const min = Number(params.get('min'));
if (dept && depts.includes(dept))
items.push({ columnId: 'dept', operator: 'equals', value: dept });
if (params.get('min') && Number.isFinite(min)) {
items.push({ columnId: 'salary', operator: 'gte', value: min });
}
return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // a real app would use history.replaceState(null, '', `?${query}`) to write and read location.search on open
let bar: HTMLElement | null = null;
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
if (el instanceof HTMLSelectElement) el.value = value;
};
const show = (): void => {
if (bar) bar.textContent = `Line shown instead of the address bar: ?${decodeURIComponent(saved)}`;
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
state.dept = '';
state.min = '';
saved = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
show();
const off = api.on('filterChanged', ({ filterModel }) => {
saved = toQuery(filterModel);
show();
// However the condition changes (including opening a link), keep the select lists above in step with the table.
const item = (id: string): FilterItem | undefined =>
filterModel?.items.find((it) => it.columnId === id);
put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
put('minSalary', String(item('salary')?.value ?? '0'));
log(`Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`);
});
return () => {
off();
bar?.remove();
bar = null;
};
}
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
minSalary: (api: GridApi<Row>, value?: string) => {
state.min = value && value !== '0' ? value : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
clear: (api: GridApi<Row>) => {
state.dept = '';
state.min = '';
api.setFilterModel(null);
},
// Pretend someone opened a ?dept=Sales&min=400 link, then read that query to restore the filter (same as on reload).
openLink: (api: GridApi<Row>) => {
const query = 'dept=Sales&min=400';
state.dept = 'Sales';
state.min = '400';
api.setFilterModel(fromQuery(query));
},
};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="Department"
[disabled]="!api"
(change)="api && actions.dept(api, $any($event.target).value)"
>
<option value="all" selected>All (default)</option>
<option value="dev">Development</option>
<option value="design">Design</option>
<option value="sales">Sales</option>
</select>
<select
aria-label="Min salary"
[disabled]="!api"
(change)="api && actions.minSalary(api, $any($event.target).value)"
>
<option value="0" selected>No limit (default)</option>
<option value="400">400+</option>
<option value="500">500+</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear all</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.openLink(api)"
>Simulate opening a link</button>
</div>
<mx-grid style="height: 440px" [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 { FilterItem, FilterModel, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
'Mason Gray',
'Ava Morgan',
'Lucas Hart',
'Mia Foster',
];
const depts = ['Dev', 'Design', 'Sales'];
// Map the select values (ASCII ids from meta.json) to the English dept names in the data.
const DEPT_BY_ID: Record<string, string> = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const ID_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_ID).map(([id, name]) => [name, id]));
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'salary',
title: 'Monthly pay ($100)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[i % 3] as string,
salary: 320 + ((i * 83) % 400),
})),
rowKey: 'id',
};
// Only conditions this screen can create are written to the query string, and only those are accepted when reading.
// So even if odd text appears in the address, the grid receives only the expected conditions.
function toQuery(model: FilterModel | null): string {
const params = new URLSearchParams();
for (const item of model?.items ?? []) {
if (item.columnId === 'dept') params.set('dept', String(item.value));
if (item.columnId === 'salary') params.set('min', String(item.value));
}
return params.toString();
}
function fromQuery(query: string): FilterModel | null {
const params = new URLSearchParams(query);
const items: FilterItem[] = [];
const dept = params.get('dept');
const min = Number(params.get('min'));
if (dept && depts.includes(dept))
items.push({ columnId: 'dept', operator: 'equals', value: dept });
if (params.get('min') && Number.isFinite(min)) {
items.push({ columnId: 'salary', operator: 'gte', value: min });
}
return items.length ? { match: 'all', items } : null;
}
const state = { dept: '', min: '' };
let saved = ''; // a real app would use history.replaceState(null, '', `?${query}`) to write and read location.search on open
let bar: HTMLElement | null = null;
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
if (el instanceof HTMLSelectElement) el.value = value;
};
const show = (): void => {
if (bar) bar.textContent = `Line shown instead of the address bar: ?${decodeURIComponent(saved)}`;
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
state.dept = '';
state.min = '';
saved = '';
bar = document.createElement('div');
bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
show();
const off = api.on('filterChanged', ({ filterModel }) => {
saved = toQuery(filterModel);
show();
// However the condition changes (including opening a link), keep the select lists above in step with the table.
const item = (id: string): FilterItem | undefined =>
filterModel?.items.find((it) => it.columnId === id);
put('dept', ID_BY_DEPT[String(item('dept')?.value)] ?? 'all');
put('minSalary', String(item('salary')?.value ?? '0'));
log(`Wrote it in the line shown instead of the address bar: ?${decodeURIComponent(saved)}`);
});
return () => {
off();
bar?.remove();
bar = null;
};
}
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
state.dept = value && value !== 'all' ? (DEPT_BY_ID[value] ?? value) : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
minSalary: (api: GridApi<Row>, value?: string) => {
state.min = value && value !== '0' ? value : '';
api.setFilterModel(fromQuery(new URLSearchParams(state).toString()));
},
clear: (api: GridApi<Row>) => {
state.dept = '';
state.min = '';
api.setFilterModel(null);
},
// Pretend someone opened a ?dept=Sales&min=400 link, then read that query to restore the filter (same as on reload).
openLink: (api: GridApi<Row>) => {
const query = 'dept=Sales&min=400';
state.dept = 'Sales';
state.min = '400';
api.setFilterModel(fromQuery(query));
},
};