걸려 있는 조건 목록과 건수·합계List active filters with row count and total
필터 조건은 그냥 목록이라서, 걸린 조건을 '칩' 목록으로 보여 주거나 하나만 빼는 일은 그 목록을 다루면 돼요. 보이는 행 수와 합계는 지금 보이는 행만 더해서 필터를 따라가요.Filter conditions are a plain list, so showing the active ones as chips or removing just one is list work. The visible row count and total add only the rows now shown, so they follow the filter.
코드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>
<option value="600">600만원 이상</option>
</select>
<input type="text" aria-label="이름" placeholder="이름 (예: 김)" id="name" />
<button type="button" id="removeDept">부서 조건만 빼기</button>
<button type="button" id="removeSalary">월급 조건만 빼기</button>
<button type="button" id="clear">모두 지우기</button>
</div>
<div id="grid" style="height: 520px"></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('name').addEventListener('input', (event) => actions.name(api, event.target.value));
document.getElementById('removeDept').addEventListener('click', () => actions.removeDept(api));
document.getElementById('removeSalary').addEventListener('click', () => actions.removeSalary(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
'강다온',
'임수빈',
];
const depts = ['개발팀', '디자인팀', '영업팀'];
export const options = {
columns: [
{ id: 'name', title: '이름', width: 120 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[(i * 5) % 3],
salary: 320 + ((i * 97) % 380),
})),
rowKey: 'id',
};
// 필터 모델의 items는 그냥 조건 배열이라서, 걸려 있는 조건 목록('칩')은 getFilterModel().items를 그대로 보여 주면 돼요.
// 이 예제는 칩을 기록 창에 한 줄로 찍고, 조건 하나만 빼는 일도 같은 배열에서 그 항목만 걸러서 해요.
const TITLE = { name: '이름', dept: '부서', salary: '월급' };
const OP = { contains: '포함', equals: '=', gte: '≥' };
const chip = (item) => `[${TITLE[item.columnId] ?? item.columnId} ${OP[item.operator] ?? item.operator} ${Number.isFinite(item.value) ? Number(item.value).toLocaleString('ko-KR') : item.value}]`;
function summary(api) {
const items = api.getFilterModel()?.items ?? [];
const total = api.getVisibleRows().reduce((sum, row) => sum + row.salary, 0);
const rows = L(`${api.getRowCount()}행 중 ${api.getVisibleRowCount()}행, 월급 합계 ${total.toLocaleString('ko-KR')}만원`, `${api.getVisibleRowCount()} of ${api.getRowCount()} rows, pay total ${total.toLocaleString('en-US')} (10k KRW)`);
return items.length
? `${items.map(chip).join(' ')} → ${rows}`
: `${L('조건 없음', 'No conditions')} → ${rows}`;
}
export function setup(api, log) {
say = log;
log(summary(api));
// 조작 칸은 항상 필터 모델에서 다시 읽어요. 조건이 어떻게 바뀌든(칩 빼기, 모두 지우기, 코드) 칸이 표와 어긋나지 않아요.
const off = api.on('filterChanged', () => {
syncControls(api);
log(summary(api));
});
return () => off();
}
function syncControls(api) {
const items = api.getFilterModel()?.items ?? [];
const of = (id) => items.find((it) => it.columnId === id);
const put = (id, value) => {
const el = document.getElementById(id);
// 입력 중인 칸은 건드리지 않아요.
if ((el instanceof HTMLInputElement || el instanceof HTMLSelectElement) &&
el !== document.activeElement) {
el.value = value;
}
};
put('dept', KEY_BY_DEPT[String(of('dept')?.value)] ?? 'all');
put('minSalary', String(of('salary')?.value ?? '0'));
put('name', String(of('name')?.value ?? ''));
}
/** 한 컬럼의 조건을 바꾸거나(item) 빼고(null), 다른 컬럼의 조건은 그대로 둔다. */
function set(api, columnId, item) {
const rest = (api.getFilterModel()?.items ?? []).filter((it) => it.columnId !== columnId);
const items = item ? [...rest, item] : rest;
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
let say = () => { };
/** 조작 칸(select·입력칸)의 값을 되돌린다. */
function reset(id, value) {
const el = document.getElementById(id);
if (el instanceof HTMLInputElement || el instanceof HTMLSelectElement)
el.value = value;
}
function remove(api, columnId) {
const has = (api.getFilterModel()?.items ?? []).some((it) => it.columnId === columnId);
if (!has)
return say({
ko: `${TITLE[columnId]} 조건은 걸려 있지 않아요`,
en: `No condition on ${TITLE[columnId]}`,
});
set(api, columnId, null);
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 표의 값으로 바꿔 써요.
const DEPT_BY_KEY = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const KEY_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_KEY).map(([k, v]) => [v, k]));
export const actions = {
dept: (api, value) => {
const dept = value ? DEPT_BY_KEY[value] : undefined;
set(api, 'dept', dept ? { columnId: 'dept', operator: 'equals', value: dept } : null);
},
minSalary: (api, value) => set(api, 'salary', Number(value) > 0 ? { columnId: 'salary', operator: 'gte', value: Number(value) } : null),
name: (api, value) => {
const text = (value ?? '').trim();
set(api, 'name', text ? { columnId: 'name', operator: 'contains', value: text } : null);
},
// 조건을 코드로 뺄 때는 위 조작 칸도 같이 되돌려서, 칸에 남은 값이 표와 어긋나지 않게 해요.
removeDept: (api) => {
reset('dept', 'all');
remove(api, 'dept');
},
removeSalary: (api) => {
reset('minSalary', '0');
remove(api, 'salary');
},
clear: (api) => {
reset('dept', 'all');
reset('minSalary', '0');
reset('name', '');
if (!api.getFilterModel())
return say({ ko: '걸려 있는 조건이 없어요', en: 'No conditions applied' });
api.setFilterModel(null);
},
};<!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>
<option value="600">600만원 이상</option>
</select>
<input type="text" aria-label="이름" placeholder="이름 (예: 김)" id="name" />
<button type="button" id="removeDept">부서 조건만 빼기</button>
<button type="button" id="removeSalary">월급 조건만 빼기</button>
<button type="button" id="clear">모두 지우기</button>
</div>
<div id="grid" style="height: 520px"></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 = ['개발팀', '디자인팀', '영업팀'];
const options = {
columns: [
{ id: 'name', title: '이름', width: 120 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[(i * 5) % 3],
salary: 320 + ((i * 97) % 380),
})),
rowKey: 'id',
};
// 필터 모델의 items는 그냥 조건 배열이라서, 걸려 있는 조건 목록('칩')은 getFilterModel().items를 그대로 보여 주면 돼요.
// 이 예제는 칩을 기록 창에 한 줄로 찍고, 조건 하나만 빼는 일도 같은 배열에서 그 항목만 걸러서 해요.
const TITLE = { name: '이름', dept: '부서', salary: '월급' };
const OP = { contains: '포함', equals: '=', gte: '≥' };
const chip = (item) => `[${TITLE[item.columnId] ?? item.columnId} ${OP[item.operator] ?? item.operator} ${Number.isFinite(item.value) ? Number(item.value).toLocaleString('ko-KR') : item.value}]`;
function summary(api) {
const items = api.getFilterModel()?.items ?? [];
const total = api.getVisibleRows().reduce((sum, row) => sum + row.salary, 0);
const rows = L(`${api.getRowCount()}행 중 ${api.getVisibleRowCount()}행, 월급 합계 ${total.toLocaleString('ko-KR')}만원`, `${api.getVisibleRowCount()} of ${api.getRowCount()} rows, pay total ${total.toLocaleString('en-US')} (10k KRW)`);
return items.length
? `${items.map(chip).join(' ')} → ${rows}`
: `${L('조건 없음', 'No conditions')} → ${rows}`;
}
function setup(api, log) {
say = log;
log(summary(api));
// 조작 칸은 항상 필터 모델에서 다시 읽어요. 조건이 어떻게 바뀌든(칩 빼기, 모두 지우기, 코드) 칸이 표와 어긋나지 않아요.
const off = api.on('filterChanged', () => {
syncControls(api);
log(summary(api));
});
return () => off();
}
function syncControls(api) {
const items = api.getFilterModel()?.items ?? [];
const of = (id) => items.find((it) => it.columnId === id);
const put = (id, value) => {
const el = document.getElementById(id);
// 입력 중인 칸은 건드리지 않아요.
if ((el instanceof HTMLInputElement || el instanceof HTMLSelectElement) &&
el !== document.activeElement) {
el.value = value;
}
};
put('dept', KEY_BY_DEPT[String(of('dept')?.value)] ?? 'all');
put('minSalary', String(of('salary')?.value ?? '0'));
put('name', String(of('name')?.value ?? ''));
}
/** 한 컬럼의 조건을 바꾸거나(item) 빼고(null), 다른 컬럼의 조건은 그대로 둔다. */
function set(api, columnId, item) {
const rest = (api.getFilterModel()?.items ?? []).filter((it) => it.columnId !== columnId);
const items = item ? [...rest, item] : rest;
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
let say = () => { };
/** 조작 칸(select·입력칸)의 값을 되돌린다. */
function reset(id, value) {
const el = document.getElementById(id);
if (el instanceof HTMLInputElement || el instanceof HTMLSelectElement)
el.value = value;
}
function remove(api, columnId) {
const has = (api.getFilterModel()?.items ?? []).some((it) => it.columnId === columnId);
if (!has)
return say({
ko: `${TITLE[columnId]} 조건은 걸려 있지 않아요`,
en: `No condition on ${TITLE[columnId]}`,
});
set(api, columnId, null);
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 표의 값으로 바꿔 써요.
const DEPT_BY_KEY = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const KEY_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_KEY).map(([k, v]) => [v, k]));
const actions = {
dept: (api, value) => {
const dept = value ? DEPT_BY_KEY[value] : undefined;
set(api, 'dept', dept ? { columnId: 'dept', operator: 'equals', value: dept } : null);
},
minSalary: (api, value) => set(api, 'salary', Number(value) > 0 ? { columnId: 'salary', operator: 'gte', value: Number(value) } : null),
name: (api, value) => {
const text = (value ?? '').trim();
set(api, 'name', text ? { columnId: 'name', operator: 'contains', value: text } : null);
},
// 조건을 코드로 뺄 때는 위 조작 칸도 같이 되돌려서, 칸에 남은 값이 표와 어긋나지 않게 해요.
removeDept: (api) => {
reset('dept', 'all');
remove(api, 'dept');
},
removeSalary: (api) => {
reset('minSalary', '0');
remove(api, 'salary');
},
clear: (api) => {
reset('dept', 'all');
reset('minSalary', '0');
reset('name', '');
if (!api.getFilterModel())
return say({ ko: '걸려 있는 조건이 없어요', en: 'No conditions applied' });
api.setFilterModel(null);
},
};
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('name').addEventListener('input', (event) => actions.name(api, event.target.value));
document.getElementById('removeDept').addEventListener('click', () => actions.removeDept(api));
document.getElementById('removeSalary').addEventListener('click', () => actions.removeSalary(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<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>
<option value="600">600만원 이상</option>
</select>
<input
type="text"
aria-label="이름"
placeholder="이름 (예: 김)"
disabled={!api}
onChange={(event) => api && actions.name(api, event.target.value)}
/>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeDept(api)}
>부서 조건만 빼기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeSalary(api)}
>월급 조건만 빼기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>모두 지우기</button>
</div>
<Grid style={{ height: 520 }} 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;
name: string;
dept: string;
salary: number;
}
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
'강다온',
'임수빈',
];
const depts = ['개발팀', '디자인팀', '영업팀'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 120 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[(i * 5) % 3] as string,
salary: 320 + ((i * 97) % 380),
})),
rowKey: 'id',
};
// 필터 모델의 items는 그냥 조건 배열이라서, 걸려 있는 조건 목록('칩')은 getFilterModel().items를 그대로 보여 주면 돼요.
// 이 예제는 칩을 기록 창에 한 줄로 찍고, 조건 하나만 빼는 일도 같은 배열에서 그 항목만 걸러서 해요.
const TITLE: Record<string, string> = { name: '이름', dept: '부서', salary: '월급' };
const OP: Record<string, string> = { contains: '포함', equals: '=', gte: '≥' };
const chip = (item: FilterItem): string =>
`[${TITLE[item.columnId] ?? item.columnId} ${OP[item.operator] ?? item.operator} ${Number.isFinite(item.value) ? Number(item.value).toLocaleString('ko-KR') : item.value}]`;
function summary(api: GridApi<Row>): string {
const items = api.getFilterModel()?.items ?? [];
const total = api.getVisibleRows().reduce((sum, row) => sum + row.salary, 0);
const rows = L(
`${api.getRowCount()}행 중 ${api.getVisibleRowCount()}행, 월급 합계 ${total.toLocaleString('ko-KR')}만원`,
`${api.getVisibleRowCount()} of ${api.getRowCount()} rows, pay total ${total.toLocaleString('en-US')} (10k KRW)`,
);
return items.length
? `${items.map(chip).join(' ')} → ${rows}`
: `${L('조건 없음', 'No conditions')} → ${rows}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(summary(api));
// 조작 칸은 항상 필터 모델에서 다시 읽어요. 조건이 어떻게 바뀌든(칩 빼기, 모두 지우기, 코드) 칸이 표와 어긋나지 않아요.
const off = api.on('filterChanged', () => {
syncControls(api);
log(summary(api));
});
return () => off();
}
function syncControls(api: GridApi<Row>): void {
const items = api.getFilterModel()?.items ?? [];
const of = (id: string): FilterItem | undefined => items.find((it) => it.columnId === id);
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
// 입력 중인 칸은 건드리지 않아요.
if (
(el instanceof HTMLInputElement || el instanceof HTMLSelectElement) &&
el !== document.activeElement
) {
el.value = value;
}
};
put('dept', KEY_BY_DEPT[String(of('dept')?.value)] ?? 'all');
put('minSalary', String(of('salary')?.value ?? '0'));
put('name', String(of('name')?.value ?? ''));
}
/** 한 컬럼의 조건을 바꾸거나(item) 빼고(null), 다른 컬럼의 조건은 그대로 둔다. */
function set(api: GridApi<Row>, columnId: string, item: FilterItem | null): void {
const rest = (api.getFilterModel()?.items ?? []).filter((it) => it.columnId !== columnId);
const items = item ? [...rest, item] : rest;
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
let say: (message: LogText) => void = () => {};
/** 조작 칸(select·입력칸)의 값을 되돌린다. */
function reset(id: string, value: string): void {
const el = document.getElementById(id);
if (el instanceof HTMLInputElement || el instanceof HTMLSelectElement) el.value = value;
}
function remove(api: GridApi<Row>, columnId: string): void {
const has = (api.getFilterModel()?.items ?? []).some((it) => it.columnId === columnId);
if (!has)
return say({
ko: `${TITLE[columnId]} 조건은 걸려 있지 않아요`,
en: `No condition on ${TITLE[columnId]}`,
});
set(api, columnId, null);
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 표의 값으로 바꿔 써요.
const DEPT_BY_KEY: Record<string, string> = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const KEY_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_KEY).map(([k, v]) => [v, k]));
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
const dept = value ? DEPT_BY_KEY[value] : undefined;
set(api, 'dept', dept ? { columnId: 'dept', operator: 'equals', value: dept } : null);
},
minSalary: (api: GridApi<Row>, value?: string) =>
set(
api,
'salary',
Number(value) > 0 ? { columnId: 'salary', operator: 'gte', value: Number(value) } : null,
),
name: (api: GridApi<Row>, value?: string) => {
const text = (value ?? '').trim();
set(api, 'name', text ? { columnId: 'name', operator: 'contains', value: text } : null);
},
// 조건을 코드로 뺄 때는 위 조작 칸도 같이 되돌려서, 칸에 남은 값이 표와 어긋나지 않게 해요.
removeDept: (api: GridApi<Row>) => {
reset('dept', 'all');
remove(api, 'dept');
},
removeSalary: (api: GridApi<Row>) => {
reset('minSalary', '0');
remove(api, 'salary');
},
clear: (api: GridApi<Row>) => {
reset('dept', 'all');
reset('minSalary', '0');
reset('name', '');
if (!api.getFilterModel())
return say({ ko: '걸려 있는 조건이 없어요', en: 'No conditions applied' });
api.setFilterModel(null);
},
};버튼을 누르면 이 예제의 코드가 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>
<option value="600">600만원 이상</option>
</select>
<input
type="text"
aria-label="이름"
placeholder="이름 (예: 김)"
:disabled="!api"
@input="api && actions.name(api, ($event.target as HTMLInputElement).value)"
/>
<button
type="button"
:disabled="!api"
@click="api && actions.removeDept(api)"
>부서 조건만 빼기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeSalary(api)"
>월급 조건만 빼기</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">모두 지우기</button>
</div>
<Grid style="height: 520px" :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;
name: string;
dept: string;
salary: number;
}
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
'강다온',
'임수빈',
];
const depts = ['개발팀', '디자인팀', '영업팀'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 120 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[(i * 5) % 3] as string,
salary: 320 + ((i * 97) % 380),
})),
rowKey: 'id',
};
// 필터 모델의 items는 그냥 조건 배열이라서, 걸려 있는 조건 목록('칩')은 getFilterModel().items를 그대로 보여 주면 돼요.
// 이 예제는 칩을 기록 창에 한 줄로 찍고, 조건 하나만 빼는 일도 같은 배열에서 그 항목만 걸러서 해요.
const TITLE: Record<string, string> = { name: '이름', dept: '부서', salary: '월급' };
const OP: Record<string, string> = { contains: '포함', equals: '=', gte: '≥' };
const chip = (item: FilterItem): string =>
`[${TITLE[item.columnId] ?? item.columnId} ${OP[item.operator] ?? item.operator} ${Number.isFinite(item.value) ? Number(item.value).toLocaleString('ko-KR') : item.value}]`;
function summary(api: GridApi<Row>): string {
const items = api.getFilterModel()?.items ?? [];
const total = api.getVisibleRows().reduce((sum, row) => sum + row.salary, 0);
const rows = L(
`${api.getRowCount()}행 중 ${api.getVisibleRowCount()}행, 월급 합계 ${total.toLocaleString('ko-KR')}만원`,
`${api.getVisibleRowCount()} of ${api.getRowCount()} rows, pay total ${total.toLocaleString('en-US')} (10k KRW)`,
);
return items.length
? `${items.map(chip).join(' ')} → ${rows}`
: `${L('조건 없음', 'No conditions')} → ${rows}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(summary(api));
// 조작 칸은 항상 필터 모델에서 다시 읽어요. 조건이 어떻게 바뀌든(칩 빼기, 모두 지우기, 코드) 칸이 표와 어긋나지 않아요.
const off = api.on('filterChanged', () => {
syncControls(api);
log(summary(api));
});
return () => off();
}
function syncControls(api: GridApi<Row>): void {
const items = api.getFilterModel()?.items ?? [];
const of = (id: string): FilterItem | undefined => items.find((it) => it.columnId === id);
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
// 입력 중인 칸은 건드리지 않아요.
if (
(el instanceof HTMLInputElement || el instanceof HTMLSelectElement) &&
el !== document.activeElement
) {
el.value = value;
}
};
put('dept', KEY_BY_DEPT[String(of('dept')?.value)] ?? 'all');
put('minSalary', String(of('salary')?.value ?? '0'));
put('name', String(of('name')?.value ?? ''));
}
/** 한 컬럼의 조건을 바꾸거나(item) 빼고(null), 다른 컬럼의 조건은 그대로 둔다. */
function set(api: GridApi<Row>, columnId: string, item: FilterItem | null): void {
const rest = (api.getFilterModel()?.items ?? []).filter((it) => it.columnId !== columnId);
const items = item ? [...rest, item] : rest;
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
let say: (message: LogText) => void = () => {};
/** 조작 칸(select·입력칸)의 값을 되돌린다. */
function reset(id: string, value: string): void {
const el = document.getElementById(id);
if (el instanceof HTMLInputElement || el instanceof HTMLSelectElement) el.value = value;
}
function remove(api: GridApi<Row>, columnId: string): void {
const has = (api.getFilterModel()?.items ?? []).some((it) => it.columnId === columnId);
if (!has)
return say({
ko: `${TITLE[columnId]} 조건은 걸려 있지 않아요`,
en: `No condition on ${TITLE[columnId]}`,
});
set(api, columnId, null);
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 표의 값으로 바꿔 써요.
const DEPT_BY_KEY: Record<string, string> = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const KEY_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_KEY).map(([k, v]) => [v, k]));
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
const dept = value ? DEPT_BY_KEY[value] : undefined;
set(api, 'dept', dept ? { columnId: 'dept', operator: 'equals', value: dept } : null);
},
minSalary: (api: GridApi<Row>, value?: string) =>
set(
api,
'salary',
Number(value) > 0 ? { columnId: 'salary', operator: 'gte', value: Number(value) } : null,
),
name: (api: GridApi<Row>, value?: string) => {
const text = (value ?? '').trim();
set(api, 'name', text ? { columnId: 'name', operator: 'contains', value: text } : null);
},
// 조건을 코드로 뺄 때는 위 조작 칸도 같이 되돌려서, 칸에 남은 값이 표와 어긋나지 않게 해요.
removeDept: (api: GridApi<Row>) => {
reset('dept', 'all');
remove(api, 'dept');
},
removeSalary: (api: GridApi<Row>) => {
reset('minSalary', '0');
remove(api, 'salary');
},
clear: (api: GridApi<Row>) => {
reset('dept', 'all');
reset('minSalary', '0');
reset('name', '');
if (!api.getFilterModel())
return say({ ko: '걸려 있는 조건이 없어요', en: 'No conditions applied' });
api.setFilterModel(null);
},
};버튼을 누르면 이 예제의 코드가 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>
<option value="600">600만원 이상</option>
</select>
<input
type="text"
aria-label="이름"
placeholder="이름 (예: 김)"
[disabled]="!api"
(input)="api && actions.name(api, $any($event.target).value)"
/>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeDept(api)"
>부서 조건만 빼기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeSalary(api)"
>월급 조건만 빼기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>모두 지우기</button>
</div>
<mx-grid style="height: 520px" [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;
name: string;
dept: string;
salary: number;
}
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'김서윤',
'장하은',
'윤재민',
'강다온',
'임수빈',
];
const depts = ['개발팀', '디자인팀', '영업팀'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 120 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[(i * 5) % 3] as string,
salary: 320 + ((i * 97) % 380),
})),
rowKey: 'id',
};
// 필터 모델의 items는 그냥 조건 배열이라서, 걸려 있는 조건 목록('칩')은 getFilterModel().items를 그대로 보여 주면 돼요.
// 이 예제는 칩을 기록 창에 한 줄로 찍고, 조건 하나만 빼는 일도 같은 배열에서 그 항목만 걸러서 해요.
const TITLE: Record<string, string> = { name: '이름', dept: '부서', salary: '월급' };
const OP: Record<string, string> = { contains: '포함', equals: '=', gte: '≥' };
const chip = (item: FilterItem): string =>
`[${TITLE[item.columnId] ?? item.columnId} ${OP[item.operator] ?? item.operator} ${Number.isFinite(item.value) ? Number(item.value).toLocaleString('ko-KR') : item.value}]`;
function summary(api: GridApi<Row>): string {
const items = api.getFilterModel()?.items ?? [];
const total = api.getVisibleRows().reduce((sum, row) => sum + row.salary, 0);
const rows = L(
`${api.getRowCount()}행 중 ${api.getVisibleRowCount()}행, 월급 합계 ${total.toLocaleString('ko-KR')}만원`,
`${api.getVisibleRowCount()} of ${api.getRowCount()} rows, pay total ${total.toLocaleString('en-US')} (10k KRW)`,
);
return items.length
? `${items.map(chip).join(' ')} → ${rows}`
: `${L('조건 없음', 'No conditions')} → ${rows}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(summary(api));
// 조작 칸은 항상 필터 모델에서 다시 읽어요. 조건이 어떻게 바뀌든(칩 빼기, 모두 지우기, 코드) 칸이 표와 어긋나지 않아요.
const off = api.on('filterChanged', () => {
syncControls(api);
log(summary(api));
});
return () => off();
}
function syncControls(api: GridApi<Row>): void {
const items = api.getFilterModel()?.items ?? [];
const of = (id: string): FilterItem | undefined => items.find((it) => it.columnId === id);
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
// 입력 중인 칸은 건드리지 않아요.
if (
(el instanceof HTMLInputElement || el instanceof HTMLSelectElement) &&
el !== document.activeElement
) {
el.value = value;
}
};
put('dept', KEY_BY_DEPT[String(of('dept')?.value)] ?? 'all');
put('minSalary', String(of('salary')?.value ?? '0'));
put('name', String(of('name')?.value ?? ''));
}
/** 한 컬럼의 조건을 바꾸거나(item) 빼고(null), 다른 컬럼의 조건은 그대로 둔다. */
function set(api: GridApi<Row>, columnId: string, item: FilterItem | null): void {
const rest = (api.getFilterModel()?.items ?? []).filter((it) => it.columnId !== columnId);
const items = item ? [...rest, item] : rest;
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
let say: (message: LogText) => void = () => {};
/** 조작 칸(select·입력칸)의 값을 되돌린다. */
function reset(id: string, value: string): void {
const el = document.getElementById(id);
if (el instanceof HTMLInputElement || el instanceof HTMLSelectElement) el.value = value;
}
function remove(api: GridApi<Row>, columnId: string): void {
const has = (api.getFilterModel()?.items ?? []).some((it) => it.columnId === columnId);
if (!has)
return say({
ko: `${TITLE[columnId]} 조건은 걸려 있지 않아요`,
en: `No condition on ${TITLE[columnId]}`,
});
set(api, columnId, null);
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 표의 값으로 바꿔 써요.
const DEPT_BY_KEY: Record<string, string> = { dev: '개발팀', design: '디자인팀', sales: '영업팀' };
const KEY_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_KEY).map(([k, v]) => [v, k]));
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
const dept = value ? DEPT_BY_KEY[value] : undefined;
set(api, 'dept', dept ? { columnId: 'dept', operator: 'equals', value: dept } : null);
},
minSalary: (api: GridApi<Row>, value?: string) =>
set(
api,
'salary',
Number(value) > 0 ? { columnId: 'salary', operator: 'gte', value: Number(value) } : null,
),
name: (api: GridApi<Row>, value?: string) => {
const text = (value ?? '').trim();
set(api, 'name', text ? { columnId: 'name', operator: 'contains', value: text } : null);
},
// 조건을 코드로 뺄 때는 위 조작 칸도 같이 되돌려서, 칸에 남은 값이 표와 어긋나지 않게 해요.
removeDept: (api: GridApi<Row>) => {
reset('dept', 'all');
remove(api, 'dept');
},
removeSalary: (api: GridApi<Row>) => {
reset('minSalary', '0');
remove(api, 'salary');
},
clear: (api: GridApi<Row>) => {
reset('dept', 'all');
reset('minSalary', '0');
reset('name', '');
if (!api.getFilterModel())
return say({ ko: '걸려 있는 조건이 없어요', en: 'No conditions applied' });
api.setFilterModel(null);
},
};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 departments</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</option>
<option value="400">$4,000+</option>
<option value="500">$5,000+</option>
<option value="600">$6,000+</option>
</select>
<input
type="text"
aria-label="Name"
placeholder="Name (e.g. Liam)"
id="name"
/>
<button type="button" id="removeDept">Remove department only</button>
<button type="button" id="removeSalary">Remove salary only</button>
<button type="button" id="clear">Clear all</button>
</div>
<div id="grid" style="height: 520px"></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('name').addEventListener('input', (event) => actions.name(api, event.target.value));
document.getElementById('removeDept').addEventListener('click', () => actions.removeDept(api));
document.getElementById('removeSalary').addEventListener('click', () => actions.removeSalary(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
'Lucas Hayes',
'Mia Foster',
'Jacob Rivera',
'Chloe Bennett',
];
const depts = ['Dev', 'Design', 'Sales'];
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 140 },
{ id: 'dept', title: 'Department', width: 130 },
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[(i * 5) % 3],
salary: 3200 + ((i * 970) % 3800),
})),
rowKey: 'id',
};
// The filter model's items are just an array of conditions, so the active-condition list ("chips") is getFilterModel().items shown as is.
// This example prints the chips on one line in the log, and removing one condition is just filtering that item out of the same array.
const TITLE = { name: 'Name', dept: 'Department', salary: 'Salary' };
const OP = { contains: 'contains', equals: '=', gte: '≥' };
const chip = (item) => `[${TITLE[item.columnId] ?? item.columnId} ${OP[item.operator] ?? item.operator} ${Number.isFinite(item.value) ? `$${Number(item.value).toLocaleString('en-US')}` : item.value}]`;
function summary(api) {
const items = api.getFilterModel()?.items ?? [];
const total = api.getVisibleRows().reduce((sum, row) => sum + row.salary, 0);
const rows = `${api.getVisibleRowCount()} of ${api.getRowCount()} rows, pay total $${total.toLocaleString('en-US')}`;
return items.length ? `${items.map(chip).join(' ')} → ${rows}` : `No conditions → ${rows}`;
}
export function setup(api, log) {
say = log;
log(summary(api));
// The control values (0, 400, 500, 600) are in units of 10 dollars, so the action multiplies them by 10.
// The controls are always re-read from the filter model. However the conditions change (removing a chip, clearing all, code), the controls never drift from the grid.
const off = api.on('filterChanged', () => {
syncControls(api);
log(summary(api));
});
return () => off();
}
function syncControls(api) {
const items = api.getFilterModel()?.items ?? [];
const of = (id) => items.find((it) => it.columnId === id);
const put = (id, value) => {
const el = document.getElementById(id);
// Leave the field being typed in alone.
if ((el instanceof HTMLInputElement || el instanceof HTMLSelectElement) &&
el !== document.activeElement) {
el.value = value;
}
};
put('dept', KEY_BY_DEPT[String(of('dept')?.value)] ?? 'all');
put('minSalary', String(of('salary')?.value ?? '0'));
put('name', String(of('name')?.value ?? ''));
}
/** Replaces (item) or removes (null) the condition of one column and leaves the other columns' conditions as they are. */
function set(api, columnId, item) {
const rest = (api.getFilterModel()?.items ?? []).filter((it) => it.columnId !== columnId);
const items = item ? [...rest, item] : rest;
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
let say = () => { };
/** Puts a control (select or input) back to the given value. */
function reset(id, value) {
const el = document.getElementById(id);
if (el instanceof HTMLInputElement || el instanceof HTMLSelectElement)
el.value = value;
}
function remove(api, columnId) {
const has = (api.getFilterModel()?.items ?? []).some((it) => it.columnId === columnId);
if (!has)
return say(`No condition on ${TITLE[columnId]}`);
set(api, columnId, null);
}
// The control values are language-neutral keys; map them to the values in the table.
const DEPT_BY_KEY = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const KEY_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_KEY).map(([k, v]) => [v, k]));
export const actions = {
dept: (api, value) => {
const dept = value ? DEPT_BY_KEY[value] : undefined;
set(api, 'dept', dept ? { columnId: 'dept', operator: 'equals', value: dept } : null);
},
minSalary: (api, value) => set(api, 'salary', Number(value) > 0 ? { columnId: 'salary', operator: 'gte', value: Number(value) * 10 } : null),
name: (api, value) => {
const text = (value ?? '').trim();
set(api, 'name', text ? { columnId: 'name', operator: 'contains', value: text } : null);
},
// When a condition is removed from code, the controls above are reset too so no stale value is left in them.
removeDept: (api) => {
reset('dept', 'all');
remove(api, 'dept');
},
removeSalary: (api) => {
reset('minSalary', '0');
remove(api, 'salary');
},
clear: (api) => {
reset('dept', 'all');
reset('minSalary', '0');
reset('name', '');
if (!api.getFilterModel())
return say('No conditions applied');
api.setFilterModel(null);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>List active filters with row count and total</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Department" id="dept">
<option value="all" selected>All departments</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</option>
<option value="400">$4,000+</option>
<option value="500">$5,000+</option>
<option value="600">$6,000+</option>
</select>
<input
type="text"
aria-label="Name"
placeholder="Name (e.g. Liam)"
id="name"
/>
<button type="button" id="removeDept">Remove department only</button>
<button type="button" id="removeSalary">Remove salary only</button>
<button type="button" id="clear">Clear all</button>
</div>
<div id="grid" style="height: 520px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
'Lucas Hayes',
'Mia Foster',
'Jacob Rivera',
'Chloe Bennett',
];
const depts = ['Dev', 'Design', 'Sales'];
const options = {
columns: [
{ id: 'name', title: 'Name', width: 140 },
{ id: 'dept', title: 'Department', width: 130 },
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[(i * 5) % 3],
salary: 3200 + ((i * 970) % 3800),
})),
rowKey: 'id',
};
// The filter model's items are just an array of conditions, so the active-condition list ("chips") is getFilterModel().items shown as is.
// This example prints the chips on one line in the log, and removing one condition is just filtering that item out of the same array.
const TITLE = { name: 'Name', dept: 'Department', salary: 'Salary' };
const OP = { contains: 'contains', equals: '=', gte: '≥' };
const chip = (item) => `[${TITLE[item.columnId] ?? item.columnId} ${OP[item.operator] ?? item.operator} ${Number.isFinite(item.value) ? `$${Number(item.value).toLocaleString('en-US')}` : item.value}]`;
function summary(api) {
const items = api.getFilterModel()?.items ?? [];
const total = api.getVisibleRows().reduce((sum, row) => sum + row.salary, 0);
const rows = `${api.getVisibleRowCount()} of ${api.getRowCount()} rows, pay total $${total.toLocaleString('en-US')}`;
return items.length ? `${items.map(chip).join(' ')} → ${rows}` : `No conditions → ${rows}`;
}
function setup(api, log) {
say = log;
log(summary(api));
// The control values (0, 400, 500, 600) are in units of 10 dollars, so the action multiplies them by 10.
// The controls are always re-read from the filter model. However the conditions change (removing a chip, clearing all, code), the controls never drift from the grid.
const off = api.on('filterChanged', () => {
syncControls(api);
log(summary(api));
});
return () => off();
}
function syncControls(api) {
const items = api.getFilterModel()?.items ?? [];
const of = (id) => items.find((it) => it.columnId === id);
const put = (id, value) => {
const el = document.getElementById(id);
// Leave the field being typed in alone.
if ((el instanceof HTMLInputElement || el instanceof HTMLSelectElement) &&
el !== document.activeElement) {
el.value = value;
}
};
put('dept', KEY_BY_DEPT[String(of('dept')?.value)] ?? 'all');
put('minSalary', String(of('salary')?.value ?? '0'));
put('name', String(of('name')?.value ?? ''));
}
/** Replaces (item) or removes (null) the condition of one column and leaves the other columns' conditions as they are. */
function set(api, columnId, item) {
const rest = (api.getFilterModel()?.items ?? []).filter((it) => it.columnId !== columnId);
const items = item ? [...rest, item] : rest;
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
let say = () => { };
/** Puts a control (select or input) back to the given value. */
function reset(id, value) {
const el = document.getElementById(id);
if (el instanceof HTMLInputElement || el instanceof HTMLSelectElement)
el.value = value;
}
function remove(api, columnId) {
const has = (api.getFilterModel()?.items ?? []).some((it) => it.columnId === columnId);
if (!has)
return say(`No condition on ${TITLE[columnId]}`);
set(api, columnId, null);
}
// The control values are language-neutral keys; map them to the values in the table.
const DEPT_BY_KEY = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const KEY_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_KEY).map(([k, v]) => [v, k]));
const actions = {
dept: (api, value) => {
const dept = value ? DEPT_BY_KEY[value] : undefined;
set(api, 'dept', dept ? { columnId: 'dept', operator: 'equals', value: dept } : null);
},
minSalary: (api, value) => set(api, 'salary', Number(value) > 0 ? { columnId: 'salary', operator: 'gte', value: Number(value) * 10 } : null),
name: (api, value) => {
const text = (value ?? '').trim();
set(api, 'name', text ? { columnId: 'name', operator: 'contains', value: text } : null);
},
// When a condition is removed from code, the controls above are reset too so no stale value is left in them.
removeDept: (api) => {
reset('dept', 'all');
remove(api, 'dept');
},
removeSalary: (api) => {
reset('minSalary', '0');
remove(api, 'salary');
},
clear: (api) => {
reset('dept', 'all');
reset('minSalary', '0');
reset('name', '');
if (!api.getFilterModel())
return say('No conditions applied');
api.setFilterModel(null);
},
};
options.ariaLabel = "List active filters with row count and total";
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('name').addEventListener('input', (event) => actions.name(api, event.target.value));
document.getElementById('removeDept').addEventListener('click', () => actions.removeDept(api));
document.getElementById('removeSalary').addEventListener('click', () => actions.removeSalary(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="Department"
disabled={!api}
onChange={(event) => api && actions.dept(api, event.target.value)}
>
<option value="all">All departments</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</option>
<option value="400">$4,000+</option>
<option value="500">$5,000+</option>
<option value="600">$6,000+</option>
</select>
<input
type="text"
aria-label="Name"
placeholder="Name (e.g. Liam)"
disabled={!api}
onChange={(event) => api && actions.name(api, event.target.value)}
/>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeDept(api)}
>Remove department only</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeSalary(api)}
>Remove salary only</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear all</button>
</div>
<Grid style={{ height: 520 }} ref={gridRef} options={options} />
</>
);
}import type { FilterItem, 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 Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
'Lucas Hayes',
'Mia Foster',
'Jacob Rivera',
'Chloe Bennett',
];
const depts = ['Dev', 'Design', 'Sales'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 140 },
{ id: 'dept', title: 'Department', width: 130 },
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[(i * 5) % 3] as string,
salary: 3200 + ((i * 970) % 3800),
})),
rowKey: 'id',
};
// The filter model's items are just an array of conditions, so the active-condition list ("chips") is getFilterModel().items shown as is.
// This example prints the chips on one line in the log, and removing one condition is just filtering that item out of the same array.
const TITLE: Record<string, string> = { name: 'Name', dept: 'Department', salary: 'Salary' };
const OP: Record<string, string> = { contains: 'contains', equals: '=', gte: '≥' };
const chip = (item: FilterItem): string =>
`[${TITLE[item.columnId] ?? item.columnId} ${OP[item.operator] ?? item.operator} ${Number.isFinite(item.value) ? `$${Number(item.value).toLocaleString('en-US')}` : item.value}]`;
function summary(api: GridApi<Row>): string {
const items = api.getFilterModel()?.items ?? [];
const total = api.getVisibleRows().reduce((sum, row) => sum + row.salary, 0);
const rows = `${api.getVisibleRowCount()} of ${api.getRowCount()} rows, pay total $${total.toLocaleString('en-US')}`;
return items.length ? `${items.map(chip).join(' ')} → ${rows}` : `No conditions → ${rows}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(summary(api));
// The control values (0, 400, 500, 600) are in units of 10 dollars, so the action multiplies them by 10.
// The controls are always re-read from the filter model. However the conditions change (removing a chip, clearing all, code), the controls never drift from the grid.
const off = api.on('filterChanged', () => {
syncControls(api);
log(summary(api));
});
return () => off();
}
function syncControls(api: GridApi<Row>): void {
const items = api.getFilterModel()?.items ?? [];
const of = (id: string): FilterItem | undefined => items.find((it) => it.columnId === id);
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
// Leave the field being typed in alone.
if (
(el instanceof HTMLInputElement || el instanceof HTMLSelectElement) &&
el !== document.activeElement
) {
el.value = value;
}
};
put('dept', KEY_BY_DEPT[String(of('dept')?.value)] ?? 'all');
put('minSalary', String(of('salary')?.value ?? '0'));
put('name', String(of('name')?.value ?? ''));
}
/** Replaces (item) or removes (null) the condition of one column and leaves the other columns' conditions as they are. */
function set(api: GridApi<Row>, columnId: string, item: FilterItem | null): void {
const rest = (api.getFilterModel()?.items ?? []).filter((it) => it.columnId !== columnId);
const items = item ? [...rest, item] : rest;
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
let say: (message: LogText) => void = () => {};
/** Puts a control (select or input) back to the given value. */
function reset(id: string, value: string): void {
const el = document.getElementById(id);
if (el instanceof HTMLInputElement || el instanceof HTMLSelectElement) el.value = value;
}
function remove(api: GridApi<Row>, columnId: string): void {
const has = (api.getFilterModel()?.items ?? []).some((it) => it.columnId === columnId);
if (!has) return say(`No condition on ${TITLE[columnId]}`);
set(api, columnId, null);
}
// The control values are language-neutral keys; map them to the values in the table.
const DEPT_BY_KEY: Record<string, string> = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const KEY_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_KEY).map(([k, v]) => [v, k]));
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
const dept = value ? DEPT_BY_KEY[value] : undefined;
set(api, 'dept', dept ? { columnId: 'dept', operator: 'equals', value: dept } : null);
},
minSalary: (api: GridApi<Row>, value?: string) =>
set(
api,
'salary',
Number(value) > 0 ? { columnId: 'salary', operator: 'gte', value: Number(value) * 10 } : null,
),
name: (api: GridApi<Row>, value?: string) => {
const text = (value ?? '').trim();
set(api, 'name', text ? { columnId: 'name', operator: 'contains', value: text } : null);
},
// When a condition is removed from code, the controls above are reset too so no stale value is left in them.
removeDept: (api: GridApi<Row>) => {
reset('dept', 'all');
remove(api, 'dept');
},
removeSalary: (api: GridApi<Row>) => {
reset('minSalary', '0');
remove(api, 'salary');
},
clear: (api: GridApi<Row>) => {
reset('dept', 'all');
reset('minSalary', '0');
reset('name', '');
if (!api.getFilterModel()) return say('No conditions applied');
api.setFilterModel(null);
},
};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 departments</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</option>
<option value="400">$4,000+</option>
<option value="500">$5,000+</option>
<option value="600">$6,000+</option>
</select>
<input
type="text"
aria-label="Name"
placeholder="Name (e.g. Liam)"
:disabled="!api"
@input="api && actions.name(api, ($event.target as HTMLInputElement).value)"
/>
<button
type="button"
:disabled="!api"
@click="api && actions.removeDept(api)"
>Remove department only</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeSalary(api)"
>Remove salary only</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear all</button>
</div>
<Grid style="height: 520px" :options="options" @ready="onReady" />
</template>import type { FilterItem, 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 Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
'Lucas Hayes',
'Mia Foster',
'Jacob Rivera',
'Chloe Bennett',
];
const depts = ['Dev', 'Design', 'Sales'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 140 },
{ id: 'dept', title: 'Department', width: 130 },
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[(i * 5) % 3] as string,
salary: 3200 + ((i * 970) % 3800),
})),
rowKey: 'id',
};
// The filter model's items are just an array of conditions, so the active-condition list ("chips") is getFilterModel().items shown as is.
// This example prints the chips on one line in the log, and removing one condition is just filtering that item out of the same array.
const TITLE: Record<string, string> = { name: 'Name', dept: 'Department', salary: 'Salary' };
const OP: Record<string, string> = { contains: 'contains', equals: '=', gte: '≥' };
const chip = (item: FilterItem): string =>
`[${TITLE[item.columnId] ?? item.columnId} ${OP[item.operator] ?? item.operator} ${Number.isFinite(item.value) ? `$${Number(item.value).toLocaleString('en-US')}` : item.value}]`;
function summary(api: GridApi<Row>): string {
const items = api.getFilterModel()?.items ?? [];
const total = api.getVisibleRows().reduce((sum, row) => sum + row.salary, 0);
const rows = `${api.getVisibleRowCount()} of ${api.getRowCount()} rows, pay total $${total.toLocaleString('en-US')}`;
return items.length ? `${items.map(chip).join(' ')} → ${rows}` : `No conditions → ${rows}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(summary(api));
// The control values (0, 400, 500, 600) are in units of 10 dollars, so the action multiplies them by 10.
// The controls are always re-read from the filter model. However the conditions change (removing a chip, clearing all, code), the controls never drift from the grid.
const off = api.on('filterChanged', () => {
syncControls(api);
log(summary(api));
});
return () => off();
}
function syncControls(api: GridApi<Row>): void {
const items = api.getFilterModel()?.items ?? [];
const of = (id: string): FilterItem | undefined => items.find((it) => it.columnId === id);
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
// Leave the field being typed in alone.
if (
(el instanceof HTMLInputElement || el instanceof HTMLSelectElement) &&
el !== document.activeElement
) {
el.value = value;
}
};
put('dept', KEY_BY_DEPT[String(of('dept')?.value)] ?? 'all');
put('minSalary', String(of('salary')?.value ?? '0'));
put('name', String(of('name')?.value ?? ''));
}
/** Replaces (item) or removes (null) the condition of one column and leaves the other columns' conditions as they are. */
function set(api: GridApi<Row>, columnId: string, item: FilterItem | null): void {
const rest = (api.getFilterModel()?.items ?? []).filter((it) => it.columnId !== columnId);
const items = item ? [...rest, item] : rest;
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
let say: (message: LogText) => void = () => {};
/** Puts a control (select or input) back to the given value. */
function reset(id: string, value: string): void {
const el = document.getElementById(id);
if (el instanceof HTMLInputElement || el instanceof HTMLSelectElement) el.value = value;
}
function remove(api: GridApi<Row>, columnId: string): void {
const has = (api.getFilterModel()?.items ?? []).some((it) => it.columnId === columnId);
if (!has) return say(`No condition on ${TITLE[columnId]}`);
set(api, columnId, null);
}
// The control values are language-neutral keys; map them to the values in the table.
const DEPT_BY_KEY: Record<string, string> = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const KEY_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_KEY).map(([k, v]) => [v, k]));
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
const dept = value ? DEPT_BY_KEY[value] : undefined;
set(api, 'dept', dept ? { columnId: 'dept', operator: 'equals', value: dept } : null);
},
minSalary: (api: GridApi<Row>, value?: string) =>
set(
api,
'salary',
Number(value) > 0 ? { columnId: 'salary', operator: 'gte', value: Number(value) * 10 } : null,
),
name: (api: GridApi<Row>, value?: string) => {
const text = (value ?? '').trim();
set(api, 'name', text ? { columnId: 'name', operator: 'contains', value: text } : null);
},
// When a condition is removed from code, the controls above are reset too so no stale value is left in them.
removeDept: (api: GridApi<Row>) => {
reset('dept', 'all');
remove(api, 'dept');
},
removeSalary: (api: GridApi<Row>) => {
reset('minSalary', '0');
remove(api, 'salary');
},
clear: (api: GridApi<Row>) => {
reset('dept', 'all');
reset('minSalary', '0');
reset('name', '');
if (!api.getFilterModel()) return say('No conditions applied');
api.setFilterModel(null);
},
};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 departments</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</option>
<option value="400">$4,000+</option>
<option value="500">$5,000+</option>
<option value="600">$6,000+</option>
</select>
<input
type="text"
aria-label="Name"
placeholder="Name (e.g. Liam)"
[disabled]="!api"
(input)="api && actions.name(api, $any($event.target).value)"
/>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeDept(api)"
>Remove department only</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeSalary(api)"
>Remove salary only</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear all</button>
</div>
<mx-grid style="height: 520px" [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;
name: string;
dept: string;
salary: number;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Sophia Lee',
'Mason Reed',
'Ava Morgan',
'Lucas Hayes',
'Mia Foster',
'Jacob Rivera',
'Chloe Bennett',
];
const depts = ['Dev', 'Design', 'Sales'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 140 },
{ id: 'dept', title: 'Department', width: 130 },
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
},
],
rows: names.map((name, i) => ({
id: i + 1,
name,
dept: depts[(i * 5) % 3] as string,
salary: 3200 + ((i * 970) % 3800),
})),
rowKey: 'id',
};
// The filter model's items are just an array of conditions, so the active-condition list ("chips") is getFilterModel().items shown as is.
// This example prints the chips on one line in the log, and removing one condition is just filtering that item out of the same array.
const TITLE: Record<string, string> = { name: 'Name', dept: 'Department', salary: 'Salary' };
const OP: Record<string, string> = { contains: 'contains', equals: '=', gte: '≥' };
const chip = (item: FilterItem): string =>
`[${TITLE[item.columnId] ?? item.columnId} ${OP[item.operator] ?? item.operator} ${Number.isFinite(item.value) ? `$${Number(item.value).toLocaleString('en-US')}` : item.value}]`;
function summary(api: GridApi<Row>): string {
const items = api.getFilterModel()?.items ?? [];
const total = api.getVisibleRows().reduce((sum, row) => sum + row.salary, 0);
const rows = `${api.getVisibleRowCount()} of ${api.getRowCount()} rows, pay total $${total.toLocaleString('en-US')}`;
return items.length ? `${items.map(chip).join(' ')} → ${rows}` : `No conditions → ${rows}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(summary(api));
// The control values (0, 400, 500, 600) are in units of 10 dollars, so the action multiplies them by 10.
// The controls are always re-read from the filter model. However the conditions change (removing a chip, clearing all, code), the controls never drift from the grid.
const off = api.on('filterChanged', () => {
syncControls(api);
log(summary(api));
});
return () => off();
}
function syncControls(api: GridApi<Row>): void {
const items = api.getFilterModel()?.items ?? [];
const of = (id: string): FilterItem | undefined => items.find((it) => it.columnId === id);
const put = (id: string, value: string): void => {
const el = document.getElementById(id);
// Leave the field being typed in alone.
if (
(el instanceof HTMLInputElement || el instanceof HTMLSelectElement) &&
el !== document.activeElement
) {
el.value = value;
}
};
put('dept', KEY_BY_DEPT[String(of('dept')?.value)] ?? 'all');
put('minSalary', String(of('salary')?.value ?? '0'));
put('name', String(of('name')?.value ?? ''));
}
/** Replaces (item) or removes (null) the condition of one column and leaves the other columns' conditions as they are. */
function set(api: GridApi<Row>, columnId: string, item: FilterItem | null): void {
const rest = (api.getFilterModel()?.items ?? []).filter((it) => it.columnId !== columnId);
const items = item ? [...rest, item] : rest;
api.setFilterModel(items.length ? { match: 'all', items } : null);
}
let say: (message: LogText) => void = () => {};
/** Puts a control (select or input) back to the given value. */
function reset(id: string, value: string): void {
const el = document.getElementById(id);
if (el instanceof HTMLInputElement || el instanceof HTMLSelectElement) el.value = value;
}
function remove(api: GridApi<Row>, columnId: string): void {
const has = (api.getFilterModel()?.items ?? []).some((it) => it.columnId === columnId);
if (!has) return say(`No condition on ${TITLE[columnId]}`);
set(api, columnId, null);
}
// The control values are language-neutral keys; map them to the values in the table.
const DEPT_BY_KEY: Record<string, string> = { dev: 'Dev', design: 'Design', sales: 'Sales' };
const KEY_BY_DEPT = Object.fromEntries(Object.entries(DEPT_BY_KEY).map(([k, v]) => [v, k]));
export const actions = {
dept: (api: GridApi<Row>, value?: string) => {
const dept = value ? DEPT_BY_KEY[value] : undefined;
set(api, 'dept', dept ? { columnId: 'dept', operator: 'equals', value: dept } : null);
},
minSalary: (api: GridApi<Row>, value?: string) =>
set(
api,
'salary',
Number(value) > 0 ? { columnId: 'salary', operator: 'gte', value: Number(value) * 10 } : null,
),
name: (api: GridApi<Row>, value?: string) => {
const text = (value ?? '').trim();
set(api, 'name', text ? { columnId: 'name', operator: 'contains', value: text } : null);
},
// When a condition is removed from code, the controls above are reset too so no stale value is left in them.
removeDept: (api: GridApi<Row>) => {
reset('dept', 'all');
remove(api, 'dept');
},
removeSalary: (api: GridApi<Row>) => {
reset('minSalary', '0');
remove(api, 'salary');
},
clear: (api: GridApi<Row>) => {
reset('dept', 'all');
reset('minSalary', '0');
reset('name', '');
if (!api.getFilterModel()) return say('No conditions applied');
api.setFilterModel(null);
},
};