금액 범위와 기간으로 거르기Filter by amount range and date period
금액은 최소·최대, 날짜는 시작일·종료일로 범위를 걸러요. 한쪽만 쓰면 '이상'이나 '이하', 둘 다 쓰면 '사이'(양 끝 포함)가 되고, 두 범위를 함께 걸면 둘 다 만족하는 행만 남아요.Filter amounts by min and max and dates by start and end. One side means at least or at most, both mean between (inclusive), and both ranges combine.
코드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">
<input type="text" aria-label="최소 금액" placeholder="최소 금액" id="min" />
<input type="text" aria-label="최대 금액" placeholder="최대 금액" id="max" />
<input
type="text"
aria-label="시작일"
placeholder="시작일 YYYY-MM-DD"
id="from"
/>
<input type="text" aria-label="종료일" placeholder="종료일 YYYY-MM-DD" id="to" />
</div>
<div id="grid" style="height: 560px"></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('min').addEventListener('input', (event) => actions.min(api, event.target.value));
document.getElementById('max').addEventListener('input', (event) => actions.max(api, event.target.value));
document.getElementById('from').addEventListener('input', (event) => actions.from(api, event.target.value));
document.getElementById('to').addEventListener('input', (event) => actions.to(api, event.target.value));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const titles = [
'사무용품 정기 구매',
'서버 호스팅 갱신',
'프린터 토너',
'워크숍 대관',
'출장 항공권',
'모니터 교체',
'교육 수강료',
'광고 집행비',
];
const text = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
export const options = {
columns: [
{ id: 'title', title: '내역', width: 180 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'ordered',
title: '주문일',
kind: 'date',
width: 130,
formatValue: (value) => (value instanceof Date ? text(value) : ''),
},
],
rows: Array.from({ length: 16 }, (_, i) => ({
id: i + 1,
title: titles[i % 8],
amount: 30000 + ((i * 187000) % 900000),
ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
})),
rowKey: 'id',
};
// 범위는 한쪽만 써도 돼요: 최소만 쓰면 '이상', 최대만 쓰면 '이하', 둘 다 쓰면 '사이'(양 끝 포함)예요.
// 날짜는 YYYY-MM-DD로 쓰고, 달력 날짜(시각 없음) 기준이에요.
const range = { min: '', max: '', from: '', to: '' };
let say = () => { };
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value) => {
if (!DATE.test(value))
return null;
const [y, m, d] = value.split('-').map(Number);
const date = new Date(y, m - 1, d);
return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId, low, high) {
if (low !== null && high !== null)
return [{ columnId, operator: 'between', value: [low, high] }];
if (low !== null)
return [{ columnId, operator: 'gte', value: low }];
if (high !== null)
return [{ columnId, operator: 'lte', value: high }];
return [];
}
const parseNum = (text) => {
const t = text.replace(/,/g, '').trim();
if (t === '')
return null;
return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text) => text === '' ? null : (asDate(text) ?? 'bad');
/** 입력칸에 잘못됐다는 표시(aria-invalid)를 켜고 끈다. */
const mark = (id, bad) => {
const input = document.getElementById(id);
if (!input)
return;
if (bad)
input.setAttribute('aria-invalid', 'true');
else
input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** 한 쌍(최소·최대 또는 시작·종료)을 검사해 걸 항목과 안내 문구를 돌려준다. 잘못되면 그 쌍은 걸지 않는다. */
function pair(column, ids, values, words) {
const [low, high] = values;
const bad = [low === 'bad', high === 'bad'];
let note = bad[0] || bad[1] ? words.format : '';
if (!note && low !== null && high !== null && Number(low) > Number(high)) {
bad[0] = bad[1] = true;
note = words.order;
}
mark(ids[0], bad[0]);
mark(ids[1], bad[1]);
if (note)
return { items: [], note };
return { items: between(column, low, high), note: '' };
}
function apply(api) {
const amount = pair('amount', ['min', 'max'], [parseNum(range.min), parseNum(range.max)], {
format: L('금액은 숫자로 써 주세요. 예: 200000', 'Write the amount as a number. Example: 200000'),
order: L('최소 금액이 최대 금액보다 커요. 이 조건은 걸지 않았어요.', 'The minimum amount is greater than the maximum. This condition was not applied.'),
});
const period = pair('ordered', ['from', 'to'], [parseDate(range.from), parseDate(range.to)], {
format: L('날짜는 YYYY-MM-DD로 써 주세요. 예: 2026-03-01', 'Write the date as YYYY-MM-DD. Example: 2026-03-01'),
order: L('시작일이 종료일보다 늦어요. 이 조건은 걸지 않았어요.', 'The start date is later than the end date. This condition was not applied.'),
});
const note = [amount.note, period.note].filter(Boolean).join(' / ');
if (note && note !== lastNote)
say(note);
lastNote = note;
const items = [...amount.items, ...period.items];
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** 조작 막대에 그리드 컨트롤 모양(mxg-controls)을 입혀서, aria-invalid인 입력칸이 테마의 오류 모양(빨간 테두리·아이콘)으로 보이게 한다. */
function styleControls() {
document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
export function setup(api, log) {
styleControls();
say = log;
lastNote = '';
Object.assign(range, { min: '', max: '', from: '', to: '' });
const off = api.on('filterChanged', () => log({
ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
}));
return () => off();
}
const setter = (key) => (api, value) => {
range[key] = (value ?? '').trim();
apply(api);
};
export const actions = {
min: setter('min'),
max: setter('max'),
from: setter('from'),
to: setter('to'),
};<!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">
<input type="text" aria-label="최소 금액" placeholder="최소 금액" id="min" />
<input type="text" aria-label="최대 금액" placeholder="최대 금액" id="max" />
<input
type="text"
aria-label="시작일"
placeholder="시작일 YYYY-MM-DD"
id="from"
/>
<input type="text" aria-label="종료일" placeholder="종료일 YYYY-MM-DD" id="to" />
</div>
<div id="grid" style="height: 560px"></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 titles = [
'사무용품 정기 구매',
'서버 호스팅 갱신',
'프린터 토너',
'워크숍 대관',
'출장 항공권',
'모니터 교체',
'교육 수강료',
'광고 집행비',
];
const text = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
const options = {
columns: [
{ id: 'title', title: '내역', width: 180 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'ordered',
title: '주문일',
kind: 'date',
width: 130,
formatValue: (value) => (value instanceof Date ? text(value) : ''),
},
],
rows: Array.from({ length: 16 }, (_, i) => ({
id: i + 1,
title: titles[i % 8],
amount: 30000 + ((i * 187000) % 900000),
ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
})),
rowKey: 'id',
};
// 범위는 한쪽만 써도 돼요: 최소만 쓰면 '이상', 최대만 쓰면 '이하', 둘 다 쓰면 '사이'(양 끝 포함)예요.
// 날짜는 YYYY-MM-DD로 쓰고, 달력 날짜(시각 없음) 기준이에요.
const range = { min: '', max: '', from: '', to: '' };
let say = () => { };
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value) => {
if (!DATE.test(value))
return null;
const [y, m, d] = value.split('-').map(Number);
const date = new Date(y, m - 1, d);
return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId, low, high) {
if (low !== null && high !== null)
return [{ columnId, operator: 'between', value: [low, high] }];
if (low !== null)
return [{ columnId, operator: 'gte', value: low }];
if (high !== null)
return [{ columnId, operator: 'lte', value: high }];
return [];
}
const parseNum = (text) => {
const t = text.replace(/,/g, '').trim();
if (t === '')
return null;
return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text) => text === '' ? null : (asDate(text) ?? 'bad');
/** 입력칸에 잘못됐다는 표시(aria-invalid)를 켜고 끈다. */
const mark = (id, bad) => {
const input = document.getElementById(id);
if (!input)
return;
if (bad)
input.setAttribute('aria-invalid', 'true');
else
input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** 한 쌍(최소·최대 또는 시작·종료)을 검사해 걸 항목과 안내 문구를 돌려준다. 잘못되면 그 쌍은 걸지 않는다. */
function pair(column, ids, values, words) {
const [low, high] = values;
const bad = [low === 'bad', high === 'bad'];
let note = bad[0] || bad[1] ? words.format : '';
if (!note && low !== null && high !== null && Number(low) > Number(high)) {
bad[0] = bad[1] = true;
note = words.order;
}
mark(ids[0], bad[0]);
mark(ids[1], bad[1]);
if (note)
return { items: [], note };
return { items: between(column, low, high), note: '' };
}
function apply(api) {
const amount = pair('amount', ['min', 'max'], [parseNum(range.min), parseNum(range.max)], {
format: L('금액은 숫자로 써 주세요. 예: 200000', 'Write the amount as a number. Example: 200000'),
order: L('최소 금액이 최대 금액보다 커요. 이 조건은 걸지 않았어요.', 'The minimum amount is greater than the maximum. This condition was not applied.'),
});
const period = pair('ordered', ['from', 'to'], [parseDate(range.from), parseDate(range.to)], {
format: L('날짜는 YYYY-MM-DD로 써 주세요. 예: 2026-03-01', 'Write the date as YYYY-MM-DD. Example: 2026-03-01'),
order: L('시작일이 종료일보다 늦어요. 이 조건은 걸지 않았어요.', 'The start date is later than the end date. This condition was not applied.'),
});
const note = [amount.note, period.note].filter(Boolean).join(' / ');
if (note && note !== lastNote)
say(note);
lastNote = note;
const items = [...amount.items, ...period.items];
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** 조작 막대에 그리드 컨트롤 모양(mxg-controls)을 입혀서, aria-invalid인 입력칸이 테마의 오류 모양(빨간 테두리·아이콘)으로 보이게 한다. */
function styleControls() {
document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
function setup(api, log) {
styleControls();
say = log;
lastNote = '';
Object.assign(range, { min: '', max: '', from: '', to: '' });
const off = api.on('filterChanged', () => log({
ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
}));
return () => off();
}
const setter = (key) => (api, value) => {
range[key] = (value ?? '').trim();
apply(api);
};
const actions = {
min: setter('min'),
max: setter('max'),
from: setter('from'),
to: setter('to'),
};
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('min').addEventListener('input', (event) => actions.min(api, event.target.value));
document.getElementById('max').addEventListener('input', (event) => actions.max(api, event.target.value));
document.getElementById('from').addEventListener('input', (event) => actions.from(api, event.target.value));
document.getElementById('to').addEventListener('input', (event) => actions.to(api, event.target.value));
</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">
<input
type="text"
aria-label="최소 금액"
placeholder="최소 금액"
disabled={!api}
onChange={(event) => api && actions.min(api, event.target.value)}
/>
<input
type="text"
aria-label="최대 금액"
placeholder="최대 금액"
disabled={!api}
onChange={(event) => api && actions.max(api, event.target.value)}
/>
<input
type="text"
aria-label="시작일"
placeholder="시작일 YYYY-MM-DD"
disabled={!api}
onChange={(event) => api && actions.from(api, event.target.value)}
/>
<input
type="text"
aria-label="종료일"
placeholder="종료일 YYYY-MM-DD"
disabled={!api}
onChange={(event) => api && actions.to(api, event.target.value)}
/>
</div>
<Grid style={{ height: 560 }} ref={gridRef} options={options} />
</>
);
}import type { FilterItem, 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;
title: string;
amount: number;
ordered: Date;
}
const titles = [
'사무용품 정기 구매',
'서버 호스팅 갱신',
'프린터 토너',
'워크숍 대관',
'출장 항공권',
'모니터 교체',
'교육 수강료',
'광고 집행비',
];
const text = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: '내역', width: 180 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'ordered',
title: '주문일',
kind: 'date',
width: 130,
formatValue: (value) => (value instanceof Date ? text(value) : ''),
},
],
rows: Array.from({ length: 16 }, (_, i) => ({
id: i + 1,
title: titles[i % 8] as string,
amount: 30000 + ((i * 187000) % 900000),
ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
})),
rowKey: 'id',
};
// 범위는 한쪽만 써도 돼요: 최소만 쓰면 '이상', 최대만 쓰면 '이하', 둘 다 쓰면 '사이'(양 끝 포함)예요.
// 날짜는 YYYY-MM-DD로 쓰고, 달력 날짜(시각 없음) 기준이에요.
const range = { min: '', max: '', from: '', to: '' };
let say: (message: LogText) => void = () => {};
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value: string): Date | null => {
if (!DATE.test(value)) return null;
const [y, m, d] = value.split('-').map(Number) as [number, number, number];
const date = new Date(y, m - 1, d);
return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId: string, low: unknown, high: unknown): FilterItem[] {
if (low !== null && high !== null) return [{ columnId, operator: 'between', value: [low, high] }];
if (low !== null) return [{ columnId, operator: 'gte', value: low }];
if (high !== null) return [{ columnId, operator: 'lte', value: high }];
return [];
}
const parseNum = (text: string): number | null | 'bad' => {
const t = text.replace(/,/g, '').trim();
if (t === '') return null;
return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text: string): Date | null | 'bad' =>
text === '' ? null : (asDate(text) ?? 'bad');
/** 입력칸에 잘못됐다는 표시(aria-invalid)를 켜고 끈다. */
const mark = (id: string, bad: boolean): void => {
const input = document.getElementById(id);
if (!input) return;
if (bad) input.setAttribute('aria-invalid', 'true');
else input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** 한 쌍(최소·최대 또는 시작·종료)을 검사해 걸 항목과 안내 문구를 돌려준다. 잘못되면 그 쌍은 걸지 않는다. */
function pair<T extends number | Date>(
column: string,
ids: [string, string],
values: [T | null | 'bad', T | null | 'bad'],
words: { format: string; order: string },
): { items: FilterItem[]; note: string } {
const [low, high] = values;
const bad: [boolean, boolean] = [low === 'bad', high === 'bad'];
let note = bad[0] || bad[1] ? words.format : '';
if (!note && low !== null && high !== null && Number(low) > Number(high)) {
bad[0] = bad[1] = true;
note = words.order;
}
mark(ids[0], bad[0]);
mark(ids[1], bad[1]);
if (note) return { items: [], note };
return { items: between(column, low, high), note: '' };
}
function apply(api: GridApi<Row>): void {
const amount = pair<number>(
'amount',
['min', 'max'],
[parseNum(range.min), parseNum(range.max)],
{
format: L(
'금액은 숫자로 써 주세요. 예: 200000',
'Write the amount as a number. Example: 200000',
),
order: L(
'최소 금액이 최대 금액보다 커요. 이 조건은 걸지 않았어요.',
'The minimum amount is greater than the maximum. This condition was not applied.',
),
},
);
const period = pair<Date>(
'ordered',
['from', 'to'],
[parseDate(range.from), parseDate(range.to)],
{
format: L(
'날짜는 YYYY-MM-DD로 써 주세요. 예: 2026-03-01',
'Write the date as YYYY-MM-DD. Example: 2026-03-01',
),
order: L(
'시작일이 종료일보다 늦어요. 이 조건은 걸지 않았어요.',
'The start date is later than the end date. This condition was not applied.',
),
},
);
const note = [amount.note, period.note].filter(Boolean).join(' / ');
if (note && note !== lastNote) say(note);
lastNote = note;
const items = [...amount.items, ...period.items];
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** 조작 막대에 그리드 컨트롤 모양(mxg-controls)을 입혀서, aria-invalid인 입력칸이 테마의 오류 모양(빨간 테두리·아이콘)으로 보이게 한다. */
function styleControls(): void {
document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
styleControls();
say = log;
lastNote = '';
Object.assign(range, { min: '', max: '', from: '', to: '' });
const off = api.on('filterChanged', () =>
log({
ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
}),
);
return () => off();
}
const setter = (key: keyof typeof range) => (api: GridApi<Row>, value?: string) => {
range[key] = (value ?? '').trim();
apply(api);
};
export const actions = {
min: setter('min'),
max: setter('max'),
from: setter('from'),
to: setter('to'),
};버튼을 누르면 이 예제의 코드가 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">
<input
type="text"
aria-label="최소 금액"
placeholder="최소 금액"
:disabled="!api"
@input="api && actions.min(api, ($event.target as HTMLInputElement).value)"
/>
<input
type="text"
aria-label="최대 금액"
placeholder="최대 금액"
:disabled="!api"
@input="api && actions.max(api, ($event.target as HTMLInputElement).value)"
/>
<input
type="text"
aria-label="시작일"
placeholder="시작일 YYYY-MM-DD"
:disabled="!api"
@input="api && actions.from(api, ($event.target as HTMLInputElement).value)"
/>
<input
type="text"
aria-label="종료일"
placeholder="종료일 YYYY-MM-DD"
:disabled="!api"
@input="api && actions.to(api, ($event.target as HTMLInputElement).value)"
/>
</div>
<Grid style="height: 560px" :options="options" @ready="onReady" />
</template>import type { FilterItem, 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;
title: string;
amount: number;
ordered: Date;
}
const titles = [
'사무용품 정기 구매',
'서버 호스팅 갱신',
'프린터 토너',
'워크숍 대관',
'출장 항공권',
'모니터 교체',
'교육 수강료',
'광고 집행비',
];
const text = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: '내역', width: 180 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'ordered',
title: '주문일',
kind: 'date',
width: 130,
formatValue: (value) => (value instanceof Date ? text(value) : ''),
},
],
rows: Array.from({ length: 16 }, (_, i) => ({
id: i + 1,
title: titles[i % 8] as string,
amount: 30000 + ((i * 187000) % 900000),
ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
})),
rowKey: 'id',
};
// 범위는 한쪽만 써도 돼요: 최소만 쓰면 '이상', 최대만 쓰면 '이하', 둘 다 쓰면 '사이'(양 끝 포함)예요.
// 날짜는 YYYY-MM-DD로 쓰고, 달력 날짜(시각 없음) 기준이에요.
const range = { min: '', max: '', from: '', to: '' };
let say: (message: LogText) => void = () => {};
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value: string): Date | null => {
if (!DATE.test(value)) return null;
const [y, m, d] = value.split('-').map(Number) as [number, number, number];
const date = new Date(y, m - 1, d);
return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId: string, low: unknown, high: unknown): FilterItem[] {
if (low !== null && high !== null) return [{ columnId, operator: 'between', value: [low, high] }];
if (low !== null) return [{ columnId, operator: 'gte', value: low }];
if (high !== null) return [{ columnId, operator: 'lte', value: high }];
return [];
}
const parseNum = (text: string): number | null | 'bad' => {
const t = text.replace(/,/g, '').trim();
if (t === '') return null;
return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text: string): Date | null | 'bad' =>
text === '' ? null : (asDate(text) ?? 'bad');
/** 입력칸에 잘못됐다는 표시(aria-invalid)를 켜고 끈다. */
const mark = (id: string, bad: boolean): void => {
const input = document.getElementById(id);
if (!input) return;
if (bad) input.setAttribute('aria-invalid', 'true');
else input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** 한 쌍(최소·최대 또는 시작·종료)을 검사해 걸 항목과 안내 문구를 돌려준다. 잘못되면 그 쌍은 걸지 않는다. */
function pair<T extends number | Date>(
column: string,
ids: [string, string],
values: [T | null | 'bad', T | null | 'bad'],
words: { format: string; order: string },
): { items: FilterItem[]; note: string } {
const [low, high] = values;
const bad: [boolean, boolean] = [low === 'bad', high === 'bad'];
let note = bad[0] || bad[1] ? words.format : '';
if (!note && low !== null && high !== null && Number(low) > Number(high)) {
bad[0] = bad[1] = true;
note = words.order;
}
mark(ids[0], bad[0]);
mark(ids[1], bad[1]);
if (note) return { items: [], note };
return { items: between(column, low, high), note: '' };
}
function apply(api: GridApi<Row>): void {
const amount = pair<number>(
'amount',
['min', 'max'],
[parseNum(range.min), parseNum(range.max)],
{
format: L(
'금액은 숫자로 써 주세요. 예: 200000',
'Write the amount as a number. Example: 200000',
),
order: L(
'최소 금액이 최대 금액보다 커요. 이 조건은 걸지 않았어요.',
'The minimum amount is greater than the maximum. This condition was not applied.',
),
},
);
const period = pair<Date>(
'ordered',
['from', 'to'],
[parseDate(range.from), parseDate(range.to)],
{
format: L(
'날짜는 YYYY-MM-DD로 써 주세요. 예: 2026-03-01',
'Write the date as YYYY-MM-DD. Example: 2026-03-01',
),
order: L(
'시작일이 종료일보다 늦어요. 이 조건은 걸지 않았어요.',
'The start date is later than the end date. This condition was not applied.',
),
},
);
const note = [amount.note, period.note].filter(Boolean).join(' / ');
if (note && note !== lastNote) say(note);
lastNote = note;
const items = [...amount.items, ...period.items];
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** 조작 막대에 그리드 컨트롤 모양(mxg-controls)을 입혀서, aria-invalid인 입력칸이 테마의 오류 모양(빨간 테두리·아이콘)으로 보이게 한다. */
function styleControls(): void {
document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
styleControls();
say = log;
lastNote = '';
Object.assign(range, { min: '', max: '', from: '', to: '' });
const off = api.on('filterChanged', () =>
log({
ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
}),
);
return () => off();
}
const setter = (key: keyof typeof range) => (api: GridApi<Row>, value?: string) => {
range[key] = (value ?? '').trim();
apply(api);
};
export const actions = {
min: setter('min'),
max: setter('max'),
from: setter('from'),
to: setter('to'),
};버튼을 누르면 이 예제의 코드가 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">
<input
type="text"
aria-label="최소 금액"
placeholder="최소 금액"
[disabled]="!api"
(input)="api && actions.min(api, $any($event.target).value)"
/>
<input
type="text"
aria-label="최대 금액"
placeholder="최대 금액"
[disabled]="!api"
(input)="api && actions.max(api, $any($event.target).value)"
/>
<input
type="text"
aria-label="시작일"
placeholder="시작일 YYYY-MM-DD"
[disabled]="!api"
(input)="api && actions.from(api, $any($event.target).value)"
/>
<input
type="text"
aria-label="종료일"
placeholder="종료일 YYYY-MM-DD"
[disabled]="!api"
(input)="api && actions.to(api, $any($event.target).value)"
/>
</div>
<mx-grid style="height: 560px" [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, 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;
title: string;
amount: number;
ordered: Date;
}
const titles = [
'사무용품 정기 구매',
'서버 호스팅 갱신',
'프린터 토너',
'워크숍 대관',
'출장 항공권',
'모니터 교체',
'교육 수강료',
'광고 집행비',
];
const text = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: '내역', width: 180 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'ordered',
title: '주문일',
kind: 'date',
width: 130,
formatValue: (value) => (value instanceof Date ? text(value) : ''),
},
],
rows: Array.from({ length: 16 }, (_, i) => ({
id: i + 1,
title: titles[i % 8] as string,
amount: 30000 + ((i * 187000) % 900000),
ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
})),
rowKey: 'id',
};
// 범위는 한쪽만 써도 돼요: 최소만 쓰면 '이상', 최대만 쓰면 '이하', 둘 다 쓰면 '사이'(양 끝 포함)예요.
// 날짜는 YYYY-MM-DD로 쓰고, 달력 날짜(시각 없음) 기준이에요.
const range = { min: '', max: '', from: '', to: '' };
let say: (message: LogText) => void = () => {};
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value: string): Date | null => {
if (!DATE.test(value)) return null;
const [y, m, d] = value.split('-').map(Number) as [number, number, number];
const date = new Date(y, m - 1, d);
return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId: string, low: unknown, high: unknown): FilterItem[] {
if (low !== null && high !== null) return [{ columnId, operator: 'between', value: [low, high] }];
if (low !== null) return [{ columnId, operator: 'gte', value: low }];
if (high !== null) return [{ columnId, operator: 'lte', value: high }];
return [];
}
const parseNum = (text: string): number | null | 'bad' => {
const t = text.replace(/,/g, '').trim();
if (t === '') return null;
return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text: string): Date | null | 'bad' =>
text === '' ? null : (asDate(text) ?? 'bad');
/** 입력칸에 잘못됐다는 표시(aria-invalid)를 켜고 끈다. */
const mark = (id: string, bad: boolean): void => {
const input = document.getElementById(id);
if (!input) return;
if (bad) input.setAttribute('aria-invalid', 'true');
else input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** 한 쌍(최소·최대 또는 시작·종료)을 검사해 걸 항목과 안내 문구를 돌려준다. 잘못되면 그 쌍은 걸지 않는다. */
function pair<T extends number | Date>(
column: string,
ids: [string, string],
values: [T | null | 'bad', T | null | 'bad'],
words: { format: string; order: string },
): { items: FilterItem[]; note: string } {
const [low, high] = values;
const bad: [boolean, boolean] = [low === 'bad', high === 'bad'];
let note = bad[0] || bad[1] ? words.format : '';
if (!note && low !== null && high !== null && Number(low) > Number(high)) {
bad[0] = bad[1] = true;
note = words.order;
}
mark(ids[0], bad[0]);
mark(ids[1], bad[1]);
if (note) return { items: [], note };
return { items: between(column, low, high), note: '' };
}
function apply(api: GridApi<Row>): void {
const amount = pair<number>(
'amount',
['min', 'max'],
[parseNum(range.min), parseNum(range.max)],
{
format: L(
'금액은 숫자로 써 주세요. 예: 200000',
'Write the amount as a number. Example: 200000',
),
order: L(
'최소 금액이 최대 금액보다 커요. 이 조건은 걸지 않았어요.',
'The minimum amount is greater than the maximum. This condition was not applied.',
),
},
);
const period = pair<Date>(
'ordered',
['from', 'to'],
[parseDate(range.from), parseDate(range.to)],
{
format: L(
'날짜는 YYYY-MM-DD로 써 주세요. 예: 2026-03-01',
'Write the date as YYYY-MM-DD. Example: 2026-03-01',
),
order: L(
'시작일이 종료일보다 늦어요. 이 조건은 걸지 않았어요.',
'The start date is later than the end date. This condition was not applied.',
),
},
);
const note = [amount.note, period.note].filter(Boolean).join(' / ');
if (note && note !== lastNote) say(note);
lastNote = note;
const items = [...amount.items, ...period.items];
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** 조작 막대에 그리드 컨트롤 모양(mxg-controls)을 입혀서, aria-invalid인 입력칸이 테마의 오류 모양(빨간 테두리·아이콘)으로 보이게 한다. */
function styleControls(): void {
document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
styleControls();
say = log;
lastNote = '';
Object.assign(range, { min: '', max: '', from: '', to: '' });
const off = api.on('filterChanged', () =>
log({
ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
}),
);
return () => off();
}
const setter = (key: keyof typeof range) => (api: GridApi<Row>, value?: string) => {
range[key] = (value ?? '').trim();
apply(api);
};
export const actions = {
min: setter('min'),
max: setter('max'),
from: setter('from'),
to: setter('to'),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<input
type="text"
aria-label="Min amount"
placeholder="Min amount"
id="min"
/>
<input
type="text"
aria-label="Max amount"
placeholder="Max amount"
id="max"
/>
<input
type="text"
aria-label="From"
placeholder="From YYYY-MM-DD"
id="from"
/>
<input type="text" aria-label="To" placeholder="To YYYY-MM-DD" id="to" />
</div>
<div id="grid" style="height: 560px"></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('min').addEventListener('input', (event) => actions.min(api, event.target.value));
document.getElementById('max').addEventListener('input', (event) => actions.max(api, event.target.value));
document.getElementById('from').addEventListener('input', (event) => actions.from(api, event.target.value));
document.getElementById('to').addEventListener('input', (event) => actions.to(api, event.target.value));const titles = [
'Office supplies restock',
'Server hosting renewal',
'Printer toner',
'Workshop venue',
'Business trip flight',
'Monitor replacement',
'Training course fee',
'Ad spend',
];
const text = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
export const options = {
columns: [
{ id: 'title', title: 'Description', width: 200 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
{
id: 'ordered',
title: 'Ordered',
kind: 'date',
width: 130,
formatValue: (value) => (value instanceof Date ? text(value) : ''),
},
],
rows: Array.from({ length: 16 }, (_, i) => ({
id: i + 1,
title: titles[i % 8],
amount: 30 + ((i * 187) % 900),
ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
})),
rowKey: 'id',
};
// A range can have just one side: min only means "at least", max only means "at most", both mean "between" (ends included).
// Dates are written as YYYY-MM-DD and compared as calendar dates (no time of day).
const range = { min: '', max: '', from: '', to: '' };
let say = () => { };
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value) => {
if (!DATE.test(value))
return null;
const [y, m, d] = value.split('-').map(Number);
const date = new Date(y, m - 1, d);
return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId, low, high) {
if (low !== null && high !== null)
return [{ columnId, operator: 'between', value: [low, high] }];
if (low !== null)
return [{ columnId, operator: 'gte', value: low }];
if (high !== null)
return [{ columnId, operator: 'lte', value: high }];
return [];
}
const parseNum = (text) => {
const t = text.replace(/,/g, '').trim();
if (t === '')
return null;
return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text) => text === '' ? null : (asDate(text) ?? 'bad');
/** Turns the invalid mark (aria-invalid) on or off for an input. */
const mark = (id, bad) => {
const input = document.getElementById(id);
if (!input)
return;
if (bad)
input.setAttribute('aria-invalid', 'true');
else
input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** Checks one pair (min/max or from/to) and returns the items to apply and a message. An invalid pair is not applied. */
function pair(column, ids, values, words) {
const [low, high] = values;
const bad = [low === 'bad', high === 'bad'];
let note = bad[0] || bad[1] ? words.format : '';
if (!note && low !== null && high !== null && Number(low) > Number(high)) {
bad[0] = bad[1] = true;
note = words.order;
}
mark(ids[0], bad[0]);
mark(ids[1], bad[1]);
if (note)
return { items: [], note };
return { items: between(column, low, high), note: '' };
}
function apply(api) {
const amount = pair('amount', ['min', 'max'], [parseNum(range.min), parseNum(range.max)], {
format: 'Write the amount as a number. Example: 200',
order: 'The minimum amount is greater than the maximum. This condition was not applied.',
});
const period = pair('ordered', ['from', 'to'], [parseDate(range.from), parseDate(range.to)], {
format: 'Write the date as YYYY-MM-DD. Example: 2026-03-01',
order: 'The start date is later than the end date. This condition was not applied.',
});
const note = [amount.note, period.note].filter(Boolean).join(' / ');
if (note && note !== lastNote)
say(note);
lastNote = note;
const items = [...amount.items, ...period.items];
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** Gives the toolbar the grid control look (mxg-controls) so inputs with aria-invalid show the theme's error style (red border, icon). */
function styleControls() {
document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
export function setup(api, log) {
styleControls();
say = log;
lastNote = '';
Object.assign(range, { min: '', max: '', from: '', to: '' });
const off = api.on('filterChanged', () => log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`));
return () => off();
}
const setter = (key) => (api, value) => {
range[key] = (value ?? '').trim();
apply(api);
};
export const actions = {
min: setter('min'),
max: setter('max'),
from: setter('from'),
to: setter('to'),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Filter by amount range and date period</title>
</head>
<body>
<div class="toolbar">
<input
type="text"
aria-label="Min amount"
placeholder="Min amount"
id="min"
/>
<input
type="text"
aria-label="Max amount"
placeholder="Max amount"
id="max"
/>
<input
type="text"
aria-label="From"
placeholder="From YYYY-MM-DD"
id="from"
/>
<input type="text" aria-label="To" placeholder="To YYYY-MM-DD" id="to" />
</div>
<div id="grid" style="height: 560px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const titles = [
'Office supplies restock',
'Server hosting renewal',
'Printer toner',
'Workshop venue',
'Business trip flight',
'Monitor replacement',
'Training course fee',
'Ad spend',
];
const text = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
const options = {
columns: [
{ id: 'title', title: 'Description', width: 200 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
{
id: 'ordered',
title: 'Ordered',
kind: 'date',
width: 130,
formatValue: (value) => (value instanceof Date ? text(value) : ''),
},
],
rows: Array.from({ length: 16 }, (_, i) => ({
id: i + 1,
title: titles[i % 8],
amount: 30 + ((i * 187) % 900),
ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
})),
rowKey: 'id',
};
// A range can have just one side: min only means "at least", max only means "at most", both mean "between" (ends included).
// Dates are written as YYYY-MM-DD and compared as calendar dates (no time of day).
const range = { min: '', max: '', from: '', to: '' };
let say = () => { };
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value) => {
if (!DATE.test(value))
return null;
const [y, m, d] = value.split('-').map(Number);
const date = new Date(y, m - 1, d);
return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId, low, high) {
if (low !== null && high !== null)
return [{ columnId, operator: 'between', value: [low, high] }];
if (low !== null)
return [{ columnId, operator: 'gte', value: low }];
if (high !== null)
return [{ columnId, operator: 'lte', value: high }];
return [];
}
const parseNum = (text) => {
const t = text.replace(/,/g, '').trim();
if (t === '')
return null;
return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text) => text === '' ? null : (asDate(text) ?? 'bad');
/** Turns the invalid mark (aria-invalid) on or off for an input. */
const mark = (id, bad) => {
const input = document.getElementById(id);
if (!input)
return;
if (bad)
input.setAttribute('aria-invalid', 'true');
else
input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** Checks one pair (min/max or from/to) and returns the items to apply and a message. An invalid pair is not applied. */
function pair(column, ids, values, words) {
const [low, high] = values;
const bad = [low === 'bad', high === 'bad'];
let note = bad[0] || bad[1] ? words.format : '';
if (!note && low !== null && high !== null && Number(low) > Number(high)) {
bad[0] = bad[1] = true;
note = words.order;
}
mark(ids[0], bad[0]);
mark(ids[1], bad[1]);
if (note)
return { items: [], note };
return { items: between(column, low, high), note: '' };
}
function apply(api) {
const amount = pair('amount', ['min', 'max'], [parseNum(range.min), parseNum(range.max)], {
format: 'Write the amount as a number. Example: 200',
order: 'The minimum amount is greater than the maximum. This condition was not applied.',
});
const period = pair('ordered', ['from', 'to'], [parseDate(range.from), parseDate(range.to)], {
format: 'Write the date as YYYY-MM-DD. Example: 2026-03-01',
order: 'The start date is later than the end date. This condition was not applied.',
});
const note = [amount.note, period.note].filter(Boolean).join(' / ');
if (note && note !== lastNote)
say(note);
lastNote = note;
const items = [...amount.items, ...period.items];
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** Gives the toolbar the grid control look (mxg-controls) so inputs with aria-invalid show the theme's error style (red border, icon). */
function styleControls() {
document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
function setup(api, log) {
styleControls();
say = log;
lastNote = '';
Object.assign(range, { min: '', max: '', from: '', to: '' });
const off = api.on('filterChanged', () => log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`));
return () => off();
}
const setter = (key) => (api, value) => {
range[key] = (value ?? '').trim();
apply(api);
};
const actions = {
min: setter('min'),
max: setter('max'),
from: setter('from'),
to: setter('to'),
};
options.ariaLabel = "Filter by amount range and date period";
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('min').addEventListener('input', (event) => actions.min(api, event.target.value));
document.getElementById('max').addEventListener('input', (event) => actions.max(api, event.target.value));
document.getElementById('from').addEventListener('input', (event) => actions.from(api, event.target.value));
document.getElementById('to').addEventListener('input', (event) => actions.to(api, event.target.value));
</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">
<input
type="text"
aria-label="Min amount"
placeholder="Min amount"
disabled={!api}
onChange={(event) => api && actions.min(api, event.target.value)}
/>
<input
type="text"
aria-label="Max amount"
placeholder="Max amount"
disabled={!api}
onChange={(event) => api && actions.max(api, event.target.value)}
/>
<input
type="text"
aria-label="From"
placeholder="From YYYY-MM-DD"
disabled={!api}
onChange={(event) => api && actions.from(api, event.target.value)}
/>
<input
type="text"
aria-label="To"
placeholder="To YYYY-MM-DD"
disabled={!api}
onChange={(event) => api && actions.to(api, event.target.value)}
/>
</div>
<Grid style={{ height: 560 }} ref={gridRef} options={options} />
</>
);
}import type { FilterItem, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
title: string;
amount: number;
ordered: Date;
}
const titles = [
'Office supplies restock',
'Server hosting renewal',
'Printer toner',
'Workshop venue',
'Business trip flight',
'Monitor replacement',
'Training course fee',
'Ad spend',
];
const text = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: 'Description', width: 200 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
{
id: 'ordered',
title: 'Ordered',
kind: 'date',
width: 130,
formatValue: (value) => (value instanceof Date ? text(value) : ''),
},
],
rows: Array.from({ length: 16 }, (_, i) => ({
id: i + 1,
title: titles[i % 8] as string,
amount: 30 + ((i * 187) % 900),
ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
})),
rowKey: 'id',
};
// A range can have just one side: min only means "at least", max only means "at most", both mean "between" (ends included).
// Dates are written as YYYY-MM-DD and compared as calendar dates (no time of day).
const range = { min: '', max: '', from: '', to: '' };
let say: (message: LogText) => void = () => {};
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value: string): Date | null => {
if (!DATE.test(value)) return null;
const [y, m, d] = value.split('-').map(Number) as [number, number, number];
const date = new Date(y, m - 1, d);
return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId: string, low: unknown, high: unknown): FilterItem[] {
if (low !== null && high !== null) return [{ columnId, operator: 'between', value: [low, high] }];
if (low !== null) return [{ columnId, operator: 'gte', value: low }];
if (high !== null) return [{ columnId, operator: 'lte', value: high }];
return [];
}
const parseNum = (text: string): number | null | 'bad' => {
const t = text.replace(/,/g, '').trim();
if (t === '') return null;
return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text: string): Date | null | 'bad' =>
text === '' ? null : (asDate(text) ?? 'bad');
/** Turns the invalid mark (aria-invalid) on or off for an input. */
const mark = (id: string, bad: boolean): void => {
const input = document.getElementById(id);
if (!input) return;
if (bad) input.setAttribute('aria-invalid', 'true');
else input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** Checks one pair (min/max or from/to) and returns the items to apply and a message. An invalid pair is not applied. */
function pair<T extends number | Date>(
column: string,
ids: [string, string],
values: [T | null | 'bad', T | null | 'bad'],
words: { format: string; order: string },
): { items: FilterItem[]; note: string } {
const [low, high] = values;
const bad: [boolean, boolean] = [low === 'bad', high === 'bad'];
let note = bad[0] || bad[1] ? words.format : '';
if (!note && low !== null && high !== null && Number(low) > Number(high)) {
bad[0] = bad[1] = true;
note = words.order;
}
mark(ids[0], bad[0]);
mark(ids[1], bad[1]);
if (note) return { items: [], note };
return { items: between(column, low, high), note: '' };
}
function apply(api: GridApi<Row>): void {
const amount = pair<number>(
'amount',
['min', 'max'],
[parseNum(range.min), parseNum(range.max)],
{
format: 'Write the amount as a number. Example: 200',
order: 'The minimum amount is greater than the maximum. This condition was not applied.',
},
);
const period = pair<Date>(
'ordered',
['from', 'to'],
[parseDate(range.from), parseDate(range.to)],
{
format: 'Write the date as YYYY-MM-DD. Example: 2026-03-01',
order: 'The start date is later than the end date. This condition was not applied.',
},
);
const note = [amount.note, period.note].filter(Boolean).join(' / ');
if (note && note !== lastNote) say(note);
lastNote = note;
const items = [...amount.items, ...period.items];
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** Gives the toolbar the grid control look (mxg-controls) so inputs with aria-invalid show the theme's error style (red border, icon). */
function styleControls(): void {
document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
styleControls();
say = log;
lastNote = '';
Object.assign(range, { min: '', max: '', from: '', to: '' });
const off = api.on('filterChanged', () =>
log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`),
);
return () => off();
}
const setter = (key: keyof typeof range) => (api: GridApi<Row>, value?: string) => {
range[key] = (value ?? '').trim();
apply(api);
};
export const actions = {
min: setter('min'),
max: setter('max'),
from: setter('from'),
to: setter('to'),
};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">
<input
type="text"
aria-label="Min amount"
placeholder="Min amount"
:disabled="!api"
@input="api && actions.min(api, ($event.target as HTMLInputElement).value)"
/>
<input
type="text"
aria-label="Max amount"
placeholder="Max amount"
:disabled="!api"
@input="api && actions.max(api, ($event.target as HTMLInputElement).value)"
/>
<input
type="text"
aria-label="From"
placeholder="From YYYY-MM-DD"
:disabled="!api"
@input="api && actions.from(api, ($event.target as HTMLInputElement).value)"
/>
<input
type="text"
aria-label="To"
placeholder="To YYYY-MM-DD"
:disabled="!api"
@input="api && actions.to(api, ($event.target as HTMLInputElement).value)"
/>
</div>
<Grid style="height: 560px" :options="options" @ready="onReady" />
</template>import type { FilterItem, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
title: string;
amount: number;
ordered: Date;
}
const titles = [
'Office supplies restock',
'Server hosting renewal',
'Printer toner',
'Workshop venue',
'Business trip flight',
'Monitor replacement',
'Training course fee',
'Ad spend',
];
const text = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: 'Description', width: 200 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
{
id: 'ordered',
title: 'Ordered',
kind: 'date',
width: 130,
formatValue: (value) => (value instanceof Date ? text(value) : ''),
},
],
rows: Array.from({ length: 16 }, (_, i) => ({
id: i + 1,
title: titles[i % 8] as string,
amount: 30 + ((i * 187) % 900),
ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
})),
rowKey: 'id',
};
// A range can have just one side: min only means "at least", max only means "at most", both mean "between" (ends included).
// Dates are written as YYYY-MM-DD and compared as calendar dates (no time of day).
const range = { min: '', max: '', from: '', to: '' };
let say: (message: LogText) => void = () => {};
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value: string): Date | null => {
if (!DATE.test(value)) return null;
const [y, m, d] = value.split('-').map(Number) as [number, number, number];
const date = new Date(y, m - 1, d);
return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId: string, low: unknown, high: unknown): FilterItem[] {
if (low !== null && high !== null) return [{ columnId, operator: 'between', value: [low, high] }];
if (low !== null) return [{ columnId, operator: 'gte', value: low }];
if (high !== null) return [{ columnId, operator: 'lte', value: high }];
return [];
}
const parseNum = (text: string): number | null | 'bad' => {
const t = text.replace(/,/g, '').trim();
if (t === '') return null;
return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text: string): Date | null | 'bad' =>
text === '' ? null : (asDate(text) ?? 'bad');
/** Turns the invalid mark (aria-invalid) on or off for an input. */
const mark = (id: string, bad: boolean): void => {
const input = document.getElementById(id);
if (!input) return;
if (bad) input.setAttribute('aria-invalid', 'true');
else input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** Checks one pair (min/max or from/to) and returns the items to apply and a message. An invalid pair is not applied. */
function pair<T extends number | Date>(
column: string,
ids: [string, string],
values: [T | null | 'bad', T | null | 'bad'],
words: { format: string; order: string },
): { items: FilterItem[]; note: string } {
const [low, high] = values;
const bad: [boolean, boolean] = [low === 'bad', high === 'bad'];
let note = bad[0] || bad[1] ? words.format : '';
if (!note && low !== null && high !== null && Number(low) > Number(high)) {
bad[0] = bad[1] = true;
note = words.order;
}
mark(ids[0], bad[0]);
mark(ids[1], bad[1]);
if (note) return { items: [], note };
return { items: between(column, low, high), note: '' };
}
function apply(api: GridApi<Row>): void {
const amount = pair<number>(
'amount',
['min', 'max'],
[parseNum(range.min), parseNum(range.max)],
{
format: 'Write the amount as a number. Example: 200',
order: 'The minimum amount is greater than the maximum. This condition was not applied.',
},
);
const period = pair<Date>(
'ordered',
['from', 'to'],
[parseDate(range.from), parseDate(range.to)],
{
format: 'Write the date as YYYY-MM-DD. Example: 2026-03-01',
order: 'The start date is later than the end date. This condition was not applied.',
},
);
const note = [amount.note, period.note].filter(Boolean).join(' / ');
if (note && note !== lastNote) say(note);
lastNote = note;
const items = [...amount.items, ...period.items];
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** Gives the toolbar the grid control look (mxg-controls) so inputs with aria-invalid show the theme's error style (red border, icon). */
function styleControls(): void {
document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
styleControls();
say = log;
lastNote = '';
Object.assign(range, { min: '', max: '', from: '', to: '' });
const off = api.on('filterChanged', () =>
log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`),
);
return () => off();
}
const setter = (key: keyof typeof range) => (api: GridApi<Row>, value?: string) => {
range[key] = (value ?? '').trim();
apply(api);
};
export const actions = {
min: setter('min'),
max: setter('max'),
from: setter('from'),
to: setter('to'),
};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">
<input
type="text"
aria-label="Min amount"
placeholder="Min amount"
[disabled]="!api"
(input)="api && actions.min(api, $any($event.target).value)"
/>
<input
type="text"
aria-label="Max amount"
placeholder="Max amount"
[disabled]="!api"
(input)="api && actions.max(api, $any($event.target).value)"
/>
<input
type="text"
aria-label="From"
placeholder="From YYYY-MM-DD"
[disabled]="!api"
(input)="api && actions.from(api, $any($event.target).value)"
/>
<input
type="text"
aria-label="To"
placeholder="To YYYY-MM-DD"
[disabled]="!api"
(input)="api && actions.to(api, $any($event.target).value)"
/>
</div>
<mx-grid style="height: 560px" [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, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
title: string;
amount: number;
ordered: Date;
}
const titles = [
'Office supplies restock',
'Server hosting renewal',
'Printer toner',
'Workshop venue',
'Business trip flight',
'Monitor replacement',
'Training course fee',
'Ad spend',
];
const text = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'title', title: 'Description', width: 200 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
{
id: 'ordered',
title: 'Ordered',
kind: 'date',
width: 130,
formatValue: (value) => (value instanceof Date ? text(value) : ''),
},
],
rows: Array.from({ length: 16 }, (_, i) => ({
id: i + 1,
title: titles[i % 8] as string,
amount: 30 + ((i * 187) % 900),
ordered: new Date(2026, i % 6, 3 + ((i * 7) % 24)),
})),
rowKey: 'id',
};
// A range can have just one side: min only means "at least", max only means "at most", both mean "between" (ends included).
// Dates are written as YYYY-MM-DD and compared as calendar dates (no time of day).
const range = { min: '', max: '', from: '', to: '' };
let say: (message: LogText) => void = () => {};
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const asDate = (value: string): Date | null => {
if (!DATE.test(value)) return null;
const [y, m, d] = value.split('-').map(Number) as [number, number, number];
const date = new Date(y, m - 1, d);
return date.getMonth() === m - 1 && date.getDate() === d ? date : null;
};
function between(columnId: string, low: unknown, high: unknown): FilterItem[] {
if (low !== null && high !== null) return [{ columnId, operator: 'between', value: [low, high] }];
if (low !== null) return [{ columnId, operator: 'gte', value: low }];
if (high !== null) return [{ columnId, operator: 'lte', value: high }];
return [];
}
const parseNum = (text: string): number | null | 'bad' => {
const t = text.replace(/,/g, '').trim();
if (t === '') return null;
return Number.isFinite(Number(t)) ? Number(t) : 'bad';
};
const parseDate = (text: string): Date | null | 'bad' =>
text === '' ? null : (asDate(text) ?? 'bad');
/** Turns the invalid mark (aria-invalid) on or off for an input. */
const mark = (id: string, bad: boolean): void => {
const input = document.getElementById(id);
if (!input) return;
if (bad) input.setAttribute('aria-invalid', 'true');
else input.removeAttribute('aria-invalid');
};
let lastNote = '';
/** Checks one pair (min/max or from/to) and returns the items to apply and a message. An invalid pair is not applied. */
function pair<T extends number | Date>(
column: string,
ids: [string, string],
values: [T | null | 'bad', T | null | 'bad'],
words: { format: string; order: string },
): { items: FilterItem[]; note: string } {
const [low, high] = values;
const bad: [boolean, boolean] = [low === 'bad', high === 'bad'];
let note = bad[0] || bad[1] ? words.format : '';
if (!note && low !== null && high !== null && Number(low) > Number(high)) {
bad[0] = bad[1] = true;
note = words.order;
}
mark(ids[0], bad[0]);
mark(ids[1], bad[1]);
if (note) return { items: [], note };
return { items: between(column, low, high), note: '' };
}
function apply(api: GridApi<Row>): void {
const amount = pair<number>(
'amount',
['min', 'max'],
[parseNum(range.min), parseNum(range.max)],
{
format: 'Write the amount as a number. Example: 200',
order: 'The minimum amount is greater than the maximum. This condition was not applied.',
},
);
const period = pair<Date>(
'ordered',
['from', 'to'],
[parseDate(range.from), parseDate(range.to)],
{
format: 'Write the date as YYYY-MM-DD. Example: 2026-03-01',
order: 'The start date is later than the end date. This condition was not applied.',
},
);
const note = [amount.note, period.note].filter(Boolean).join(' / ');
if (note && note !== lastNote) say(note);
lastNote = note;
const items = [...amount.items, ...period.items];
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
/** Gives the toolbar the grid control look (mxg-controls) so inputs with aria-invalid show the theme's error style (red border, icon). */
function styleControls(): void {
document.querySelector('.toolbar')?.classList.add('mxg-controls');
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
styleControls();
say = log;
lastNote = '';
Object.assign(range, { min: '', max: '', from: '', to: '' });
const off = api.on('filterChanged', () =>
log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`),
);
return () => off();
}
const setter = (key: keyof typeof range) => (api: GridApi<Row>, value?: string) => {
range[key] = (value ?? '').trim();
apply(api);
};
export const actions = {
min: setter('min'),
max: setter('max'),
from: setter('from'),
to: setter('to'),
};