칸 모양이 달라도 정렬·검색은 원래 값으로Different cell looks, but sort and filter use the real value
아바타, 배지, 진행 막대, 별점, 태그를 한 표에 모두 쓰고, 그래도 정렬과 검색이 그려진 모양이 아니라 원래 값으로 되는 것을 확인해요.Use avatar, badge, progress, rating and tags in one grid and see that sort and filter still work on the real values, not the drawn look.
코드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="sort">
<option value="none" selected>정렬 없음</option>
<option value="progress">진행률 높은 순</option>
<option value="priority">중요도 높은 순</option>
</select>
<select aria-label="상태 보기" id="status">
<option value="all" selected>전체</option>
<option value="active">진행</option>
<option value="done">완료</option>
<option value="blocked">막힘</option>
</select>
</div>
<div id="grid" style="height: 320px"></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('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('status').addEventListener('change', (event) => actions.status(api, event.target.value));// 내장 진행 막대에는 화면 읽기 프로그램용 이름이 없어서, 줄의 첫 칸 글자를 붙여 이름을 달아 줘요.
function nameBars(label, cell = 0) {
const root = document.getElementById('grid');
if (!root)
return () => undefined;
const apply = () => {
for (const bar of root.querySelectorAll('[role="progressbar"]')) {
if (bar.getAttribute('aria-label'))
continue;
const row = bar.closest('[role="row"]');
const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
const mine = bar.closest('[role="gridcell"]');
const headers = root.querySelectorAll('[role="columnheader"]');
const header = headers[cells.indexOf(mine)]?.textContent?.trim();
bar.setAttribute('aria-label', `${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim());
}
};
const observer = new MutationObserver(apply);
observer.observe(root, { childList: true, subtree: true });
apply();
return () => observer.disconnect();
}
// 내장 칸 모양을 한 표에 모두 썼어요. 칸의 모양이 달라도 값은 그냥 글자·숫자·배열이라서,
// 정렬과 검색(필터)은 그려진 모양이 아니라 원래 값으로 해요. 예: 진행률은 "72%" 글자가 아니라 숫자 72로 정렬돼요.
export const options = {
columns: [
{ id: 'owner', title: '담당', width: 140, cellRenderer: 'avatar' },
{ id: 'project', title: '프로젝트', width: 120 },
{
id: 'status',
title: '상태',
width: 100,
cellRenderer: 'badge',
cellRendererParams: {
map: {
active: { label: '진행', tone: 'info' },
done: { label: '완료', tone: 'success' },
blocked: { label: '막힘', tone: 'danger' },
},
},
},
{
id: 'progress',
title: '진행률',
width: 160,
kind: 'number',
formatValue: (value) => `${String(value)}%`,
cellRenderer: 'progress',
cellRendererParams: {
ranges: [
{ upTo: 40, tone: 'danger' },
{ upTo: 80, tone: 'warning' },
{ upTo: 100, tone: 'success' },
],
},
},
{
id: 'priority',
title: '중요도',
width: 100,
kind: 'number',
cellRenderer: 'rating',
cellRendererParams: { max: 3 },
},
{
id: 'labels',
title: '라벨',
width: 170,
cellRenderer: 'tags',
cellRendererParams: { max: 2 },
sortable: false,
filterable: false,
},
],
rows: [
{
id: 1,
owner: '김서연',
project: '결제',
status: 'active',
progress: 72,
priority: 3,
labels: ['결제', '4분기', '감사'],
},
{
id: 2,
owner: '이준호',
project: '검색',
status: 'done',
progress: 100,
priority: 2,
labels: ['검색'],
},
{
id: 3,
owner: '박민지',
project: '모바일 앱',
status: 'blocked',
progress: 25,
priority: 3,
labels: ['모바일', '출시'],
},
{
id: 4,
owner: '최도윤',
project: '문서 사이트',
status: 'active',
progress: 9,
priority: 1,
labels: ['문서'],
},
{
id: 5,
owner: '정하은',
project: '데이터 내보내기',
status: 'active',
progress: 90,
priority: 2,
labels: [],
},
],
rowKey: 'id',
filterRow: true,
saveMode: 'none',
};
let say = () => { };
export function setup(api, log) {
say = log;
log({
ko: '머리글을 눌러 정렬하거나, 머리글 아래 입력 칸으로 거를 수 있어요.',
en: 'Click a header to sort, or filter with the inputs under the headers.',
});
const stop = nameBars('진행률', 1);
// 머리글을 눌러 정렬하거나 입력 칸으로 걸러도 위의 선택 상자가 지금 상태를 따라가게 맞춰요.
const sortBox = document.getElementById('sort');
const statusBox = document.getElementById('status');
const offs = [
api.on('sortChanged', ({ sortModel }) => {
const only = sortModel.length === 1 ? sortModel[0] : undefined;
const value = only &&
only.direction === 'desc' &&
(only.columnId === 'progress' || only.columnId === 'priority')
? only.columnId
: 'none';
if (sortBox instanceof HTMLSelectElement)
sortBox.value = value;
}),
api.on('filterChanged', ({ filterModel }) => {
const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
const value = only && only.columnId === 'status' && only.operator === 'equals'
? String(only.value)
: 'all';
if (statusBox instanceof HTMLSelectElement)
statusBox.value = value;
}),
];
return () => {
stop();
offs.forEach((off) => off());
};
}
export const actions = {
sort: (api, value) => {
const by = value === 'progress' || value === 'priority' ? value : '';
api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
say({
ko: by
? `${by === 'progress' ? '진행률' : '중요도'} 높은 순으로 정렬했어요. (숫자 기준)`
: '정렬을 풀었어요.',
en: by
? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
: 'Sort cleared.',
});
},
status: (api, value) => {
api.setFilterModel(value && value !== 'all'
? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
: null);
say({
ko: value && value !== 'all'
? `상태가 "${value}"인 줄만 남겼어요. (배지 뒤의 원래 값으로 걸러요)`
: '필터를 풀었어요.',
en: value && value !== 'all'
? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
: 'Filter cleared.',
});
},
};<!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="sort">
<option value="none" selected>정렬 없음</option>
<option value="progress">진행률 높은 순</option>
<option value="priority">중요도 높은 순</option>
</select>
<select aria-label="상태 보기" id="status">
<option value="all" selected>전체</option>
<option value="active">진행</option>
<option value="done">완료</option>
<option value="blocked">막힘</option>
</select>
</div>
<div id="grid" style="height: 320px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 내장 진행 막대에는 화면 읽기 프로그램용 이름이 없어서, 줄의 첫 칸 글자를 붙여 이름을 달아 줘요.
function nameBars(label, cell = 0) {
const root = document.getElementById('grid');
if (!root)
return () => undefined;
const apply = () => {
for (const bar of root.querySelectorAll('[role="progressbar"]')) {
if (bar.getAttribute('aria-label'))
continue;
const row = bar.closest('[role="row"]');
const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
const mine = bar.closest('[role="gridcell"]');
const headers = root.querySelectorAll('[role="columnheader"]');
const header = headers[cells.indexOf(mine)]?.textContent?.trim();
bar.setAttribute('aria-label', `${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim());
}
};
const observer = new MutationObserver(apply);
observer.observe(root, { childList: true, subtree: true });
apply();
return () => observer.disconnect();
}
// 내장 칸 모양을 한 표에 모두 썼어요. 칸의 모양이 달라도 값은 그냥 글자·숫자·배열이라서,
// 정렬과 검색(필터)은 그려진 모양이 아니라 원래 값으로 해요. 예: 진행률은 "72%" 글자가 아니라 숫자 72로 정렬돼요.
const options = {
columns: [
{ id: 'owner', title: '담당', width: 140, cellRenderer: 'avatar' },
{ id: 'project', title: '프로젝트', width: 120 },
{
id: 'status',
title: '상태',
width: 100,
cellRenderer: 'badge',
cellRendererParams: {
map: {
active: { label: '진행', tone: 'info' },
done: { label: '완료', tone: 'success' },
blocked: { label: '막힘', tone: 'danger' },
},
},
},
{
id: 'progress',
title: '진행률',
width: 160,
kind: 'number',
formatValue: (value) => `${String(value)}%`,
cellRenderer: 'progress',
cellRendererParams: {
ranges: [
{ upTo: 40, tone: 'danger' },
{ upTo: 80, tone: 'warning' },
{ upTo: 100, tone: 'success' },
],
},
},
{
id: 'priority',
title: '중요도',
width: 100,
kind: 'number',
cellRenderer: 'rating',
cellRendererParams: { max: 3 },
},
{
id: 'labels',
title: '라벨',
width: 170,
cellRenderer: 'tags',
cellRendererParams: { max: 2 },
sortable: false,
filterable: false,
},
],
rows: [
{
id: 1,
owner: '김서연',
project: '결제',
status: 'active',
progress: 72,
priority: 3,
labels: ['결제', '4분기', '감사'],
},
{
id: 2,
owner: '이준호',
project: '검색',
status: 'done',
progress: 100,
priority: 2,
labels: ['검색'],
},
{
id: 3,
owner: '박민지',
project: '모바일 앱',
status: 'blocked',
progress: 25,
priority: 3,
labels: ['모바일', '출시'],
},
{
id: 4,
owner: '최도윤',
project: '문서 사이트',
status: 'active',
progress: 9,
priority: 1,
labels: ['문서'],
},
{
id: 5,
owner: '정하은',
project: '데이터 내보내기',
status: 'active',
progress: 90,
priority: 2,
labels: [],
},
],
rowKey: 'id',
filterRow: true,
saveMode: 'none',
};
let say = () => { };
function setup(api, log) {
say = log;
log({
ko: '머리글을 눌러 정렬하거나, 머리글 아래 입력 칸으로 거를 수 있어요.',
en: 'Click a header to sort, or filter with the inputs under the headers.',
});
const stop = nameBars('진행률', 1);
// 머리글을 눌러 정렬하거나 입력 칸으로 걸러도 위의 선택 상자가 지금 상태를 따라가게 맞춰요.
const sortBox = document.getElementById('sort');
const statusBox = document.getElementById('status');
const offs = [
api.on('sortChanged', ({ sortModel }) => {
const only = sortModel.length === 1 ? sortModel[0] : undefined;
const value = only &&
only.direction === 'desc' &&
(only.columnId === 'progress' || only.columnId === 'priority')
? only.columnId
: 'none';
if (sortBox instanceof HTMLSelectElement)
sortBox.value = value;
}),
api.on('filterChanged', ({ filterModel }) => {
const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
const value = only && only.columnId === 'status' && only.operator === 'equals'
? String(only.value)
: 'all';
if (statusBox instanceof HTMLSelectElement)
statusBox.value = value;
}),
];
return () => {
stop();
offs.forEach((off) => off());
};
}
const actions = {
sort: (api, value) => {
const by = value === 'progress' || value === 'priority' ? value : '';
api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
say({
ko: by
? `${by === 'progress' ? '진행률' : '중요도'} 높은 순으로 정렬했어요. (숫자 기준)`
: '정렬을 풀었어요.',
en: by
? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
: 'Sort cleared.',
});
},
status: (api, value) => {
api.setFilterModel(value && value !== 'all'
? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
: null);
say({
ko: value && value !== 'all'
? `상태가 "${value}"인 줄만 남겼어요. (배지 뒤의 원래 값으로 걸러요)`
: '필터를 풀었어요.',
en: value && value !== 'all'
? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
: 'Filter cleared.',
});
},
};
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('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('status').addEventListener('change', (event) => actions.status(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">
<select
aria-label="정렬"
disabled={!api}
onChange={(event) => api && actions.sort(api, event.target.value)}
>
<option value="none">정렬 없음</option>
<option value="progress">진행률 높은 순</option>
<option value="priority">중요도 높은 순</option>
</select>
<select defaultValue="none"
aria-label="상태 보기"
disabled={!api}
onChange={(event) => api && actions.status(api, event.target.value)}
>
<option value="all">전체</option>
<option value="active">진행</option>
<option value="done">완료</option>
<option value="blocked">막힘</option>
</select>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
// 내장 진행 막대에는 화면 읽기 프로그램용 이름이 없어서, 줄의 첫 칸 글자를 붙여 이름을 달아 줘요.
function nameBars(label: string, cell = 0): () => void {
const root = document.getElementById('grid');
if (!root) return () => undefined;
const apply = (): void => {
for (const bar of root.querySelectorAll('[role="progressbar"]')) {
if (bar.getAttribute('aria-label')) continue;
const row = bar.closest('[role="row"]');
const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
const mine = bar.closest('[role="gridcell"]');
const headers = root.querySelectorAll('[role="columnheader"]');
const header = headers[cells.indexOf(mine as Element)]?.textContent?.trim();
bar.setAttribute(
'aria-label',
`${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim(),
);
}
};
const observer = new MutationObserver(apply);
observer.observe(root, { childList: true, subtree: true });
apply();
return () => observer.disconnect();
}
export interface Row {
id: number;
owner: string;
project: string;
status: string;
progress: number;
priority: number;
labels: string[];
}
// 내장 칸 모양을 한 표에 모두 썼어요. 칸의 모양이 달라도 값은 그냥 글자·숫자·배열이라서,
// 정렬과 검색(필터)은 그려진 모양이 아니라 원래 값으로 해요. 예: 진행률은 "72%" 글자가 아니라 숫자 72로 정렬돼요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'owner', title: '담당', width: 140, cellRenderer: 'avatar' },
{ id: 'project', title: '프로젝트', width: 120 },
{
id: 'status',
title: '상태',
width: 100,
cellRenderer: 'badge',
cellRendererParams: {
map: {
active: { label: '진행', tone: 'info' },
done: { label: '완료', tone: 'success' },
blocked: { label: '막힘', tone: 'danger' },
},
},
},
{
id: 'progress',
title: '진행률',
width: 160,
kind: 'number',
formatValue: (value) => `${String(value)}%`,
cellRenderer: 'progress',
cellRendererParams: {
ranges: [
{ upTo: 40, tone: 'danger' },
{ upTo: 80, tone: 'warning' },
{ upTo: 100, tone: 'success' },
],
},
},
{
id: 'priority',
title: '중요도',
width: 100,
kind: 'number',
cellRenderer: 'rating',
cellRendererParams: { max: 3 },
},
{
id: 'labels',
title: '라벨',
width: 170,
cellRenderer: 'tags',
cellRendererParams: { max: 2 },
sortable: false,
filterable: false,
},
],
rows: [
{
id: 1,
owner: '김서연',
project: '결제',
status: 'active',
progress: 72,
priority: 3,
labels: ['결제', '4분기', '감사'],
},
{
id: 2,
owner: '이준호',
project: '검색',
status: 'done',
progress: 100,
priority: 2,
labels: ['검색'],
},
{
id: 3,
owner: '박민지',
project: '모바일 앱',
status: 'blocked',
progress: 25,
priority: 3,
labels: ['모바일', '출시'],
},
{
id: 4,
owner: '최도윤',
project: '문서 사이트',
status: 'active',
progress: 9,
priority: 1,
labels: ['문서'],
},
{
id: 5,
owner: '정하은',
project: '데이터 내보내기',
status: 'active',
progress: 90,
priority: 2,
labels: [],
},
],
rowKey: 'id',
filterRow: true,
saveMode: 'none',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '머리글을 눌러 정렬하거나, 머리글 아래 입력 칸으로 거를 수 있어요.',
en: 'Click a header to sort, or filter with the inputs under the headers.',
});
const stop = nameBars('진행률', 1);
// 머리글을 눌러 정렬하거나 입력 칸으로 걸러도 위의 선택 상자가 지금 상태를 따라가게 맞춰요.
const sortBox = document.getElementById('sort');
const statusBox = document.getElementById('status');
const offs = [
api.on('sortChanged', ({ sortModel }) => {
const only = sortModel.length === 1 ? sortModel[0] : undefined;
const value =
only &&
only.direction === 'desc' &&
(only.columnId === 'progress' || only.columnId === 'priority')
? only.columnId
: 'none';
if (sortBox instanceof HTMLSelectElement) sortBox.value = value;
}),
api.on('filterChanged', ({ filterModel }) => {
const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
const value =
only && only.columnId === 'status' && only.operator === 'equals'
? String(only.value)
: 'all';
if (statusBox instanceof HTMLSelectElement) statusBox.value = value;
}),
];
return () => {
stop();
offs.forEach((off) => off());
};
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => {
const by = value === 'progress' || value === 'priority' ? value : '';
api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
say({
ko: by
? `${by === 'progress' ? '진행률' : '중요도'} 높은 순으로 정렬했어요. (숫자 기준)`
: '정렬을 풀었어요.',
en: by
? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
: 'Sort cleared.',
});
},
status: (api: GridApi<Row>, value?: string) => {
api.setFilterModel(
value && value !== 'all'
? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
: null,
);
say({
ko:
value && value !== 'all'
? `상태가 "${value}"인 줄만 남겼어요. (배지 뒤의 원래 값으로 걸러요)`
: '필터를 풀었어요.',
en:
value && value !== 'all'
? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
: 'Filter cleared.',
});
},
};버튼을 누르면 이 예제의 코드가 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.sort(api, ($event.target as HTMLSelectElement).value)"
>
<option value="none" selected>정렬 없음</option>
<option value="progress">진행률 높은 순</option>
<option value="priority">중요도 높은 순</option>
</select>
<select
aria-label="상태 보기"
:disabled="!api"
@change="api && actions.status(api, ($event.target as HTMLSelectElement).value)"
>
<option value="all" selected>전체</option>
<option value="active">진행</option>
<option value="done">완료</option>
<option value="blocked">막힘</option>
</select>
</div>
<Grid style="height: 320px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
// 내장 진행 막대에는 화면 읽기 프로그램용 이름이 없어서, 줄의 첫 칸 글자를 붙여 이름을 달아 줘요.
function nameBars(label: string, cell = 0): () => void {
const root = document.getElementById('grid');
if (!root) return () => undefined;
const apply = (): void => {
for (const bar of root.querySelectorAll('[role="progressbar"]')) {
if (bar.getAttribute('aria-label')) continue;
const row = bar.closest('[role="row"]');
const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
const mine = bar.closest('[role="gridcell"]');
const headers = root.querySelectorAll('[role="columnheader"]');
const header = headers[cells.indexOf(mine as Element)]?.textContent?.trim();
bar.setAttribute(
'aria-label',
`${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim(),
);
}
};
const observer = new MutationObserver(apply);
observer.observe(root, { childList: true, subtree: true });
apply();
return () => observer.disconnect();
}
export interface Row {
id: number;
owner: string;
project: string;
status: string;
progress: number;
priority: number;
labels: string[];
}
// 내장 칸 모양을 한 표에 모두 썼어요. 칸의 모양이 달라도 값은 그냥 글자·숫자·배열이라서,
// 정렬과 검색(필터)은 그려진 모양이 아니라 원래 값으로 해요. 예: 진행률은 "72%" 글자가 아니라 숫자 72로 정렬돼요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'owner', title: '담당', width: 140, cellRenderer: 'avatar' },
{ id: 'project', title: '프로젝트', width: 120 },
{
id: 'status',
title: '상태',
width: 100,
cellRenderer: 'badge',
cellRendererParams: {
map: {
active: { label: '진행', tone: 'info' },
done: { label: '완료', tone: 'success' },
blocked: { label: '막힘', tone: 'danger' },
},
},
},
{
id: 'progress',
title: '진행률',
width: 160,
kind: 'number',
formatValue: (value) => `${String(value)}%`,
cellRenderer: 'progress',
cellRendererParams: {
ranges: [
{ upTo: 40, tone: 'danger' },
{ upTo: 80, tone: 'warning' },
{ upTo: 100, tone: 'success' },
],
},
},
{
id: 'priority',
title: '중요도',
width: 100,
kind: 'number',
cellRenderer: 'rating',
cellRendererParams: { max: 3 },
},
{
id: 'labels',
title: '라벨',
width: 170,
cellRenderer: 'tags',
cellRendererParams: { max: 2 },
sortable: false,
filterable: false,
},
],
rows: [
{
id: 1,
owner: '김서연',
project: '결제',
status: 'active',
progress: 72,
priority: 3,
labels: ['결제', '4분기', '감사'],
},
{
id: 2,
owner: '이준호',
project: '검색',
status: 'done',
progress: 100,
priority: 2,
labels: ['검색'],
},
{
id: 3,
owner: '박민지',
project: '모바일 앱',
status: 'blocked',
progress: 25,
priority: 3,
labels: ['모바일', '출시'],
},
{
id: 4,
owner: '최도윤',
project: '문서 사이트',
status: 'active',
progress: 9,
priority: 1,
labels: ['문서'],
},
{
id: 5,
owner: '정하은',
project: '데이터 내보내기',
status: 'active',
progress: 90,
priority: 2,
labels: [],
},
],
rowKey: 'id',
filterRow: true,
saveMode: 'none',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '머리글을 눌러 정렬하거나, 머리글 아래 입력 칸으로 거를 수 있어요.',
en: 'Click a header to sort, or filter with the inputs under the headers.',
});
const stop = nameBars('진행률', 1);
// 머리글을 눌러 정렬하거나 입력 칸으로 걸러도 위의 선택 상자가 지금 상태를 따라가게 맞춰요.
const sortBox = document.getElementById('sort');
const statusBox = document.getElementById('status');
const offs = [
api.on('sortChanged', ({ sortModel }) => {
const only = sortModel.length === 1 ? sortModel[0] : undefined;
const value =
only &&
only.direction === 'desc' &&
(only.columnId === 'progress' || only.columnId === 'priority')
? only.columnId
: 'none';
if (sortBox instanceof HTMLSelectElement) sortBox.value = value;
}),
api.on('filterChanged', ({ filterModel }) => {
const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
const value =
only && only.columnId === 'status' && only.operator === 'equals'
? String(only.value)
: 'all';
if (statusBox instanceof HTMLSelectElement) statusBox.value = value;
}),
];
return () => {
stop();
offs.forEach((off) => off());
};
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => {
const by = value === 'progress' || value === 'priority' ? value : '';
api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
say({
ko: by
? `${by === 'progress' ? '진행률' : '중요도'} 높은 순으로 정렬했어요. (숫자 기준)`
: '정렬을 풀었어요.',
en: by
? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
: 'Sort cleared.',
});
},
status: (api: GridApi<Row>, value?: string) => {
api.setFilterModel(
value && value !== 'all'
? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
: null,
);
say({
ko:
value && value !== 'all'
? `상태가 "${value}"인 줄만 남겼어요. (배지 뒤의 원래 값으로 걸러요)`
: '필터를 풀었어요.',
en:
value && value !== 'all'
? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
: 'Filter cleared.',
});
},
};버튼을 누르면 이 예제의 코드가 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.sort(api, $any($event.target).value)"
>
<option value="none" selected>정렬 없음</option>
<option value="progress">진행률 높은 순</option>
<option value="priority">중요도 높은 순</option>
</select>
<select
aria-label="상태 보기"
[disabled]="!api"
(change)="api && actions.status(api, $any($event.target).value)"
>
<option value="all" selected>전체</option>
<option value="active">진행</option>
<option value="done">완료</option>
<option value="blocked">막힘</option>
</select>
</div>
<mx-grid style="height: 320px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
// 내장 진행 막대에는 화면 읽기 프로그램용 이름이 없어서, 줄의 첫 칸 글자를 붙여 이름을 달아 줘요.
function nameBars(label: string, cell = 0): () => void {
const root = document.getElementById('grid');
if (!root) return () => undefined;
const apply = (): void => {
for (const bar of root.querySelectorAll('[role="progressbar"]')) {
if (bar.getAttribute('aria-label')) continue;
const row = bar.closest('[role="row"]');
const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
const mine = bar.closest('[role="gridcell"]');
const headers = root.querySelectorAll('[role="columnheader"]');
const header = headers[cells.indexOf(mine as Element)]?.textContent?.trim();
bar.setAttribute(
'aria-label',
`${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim(),
);
}
};
const observer = new MutationObserver(apply);
observer.observe(root, { childList: true, subtree: true });
apply();
return () => observer.disconnect();
}
export interface Row {
id: number;
owner: string;
project: string;
status: string;
progress: number;
priority: number;
labels: string[];
}
// 내장 칸 모양을 한 표에 모두 썼어요. 칸의 모양이 달라도 값은 그냥 글자·숫자·배열이라서,
// 정렬과 검색(필터)은 그려진 모양이 아니라 원래 값으로 해요. 예: 진행률은 "72%" 글자가 아니라 숫자 72로 정렬돼요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'owner', title: '담당', width: 140, cellRenderer: 'avatar' },
{ id: 'project', title: '프로젝트', width: 120 },
{
id: 'status',
title: '상태',
width: 100,
cellRenderer: 'badge',
cellRendererParams: {
map: {
active: { label: '진행', tone: 'info' },
done: { label: '완료', tone: 'success' },
blocked: { label: '막힘', tone: 'danger' },
},
},
},
{
id: 'progress',
title: '진행률',
width: 160,
kind: 'number',
formatValue: (value) => `${String(value)}%`,
cellRenderer: 'progress',
cellRendererParams: {
ranges: [
{ upTo: 40, tone: 'danger' },
{ upTo: 80, tone: 'warning' },
{ upTo: 100, tone: 'success' },
],
},
},
{
id: 'priority',
title: '중요도',
width: 100,
kind: 'number',
cellRenderer: 'rating',
cellRendererParams: { max: 3 },
},
{
id: 'labels',
title: '라벨',
width: 170,
cellRenderer: 'tags',
cellRendererParams: { max: 2 },
sortable: false,
filterable: false,
},
],
rows: [
{
id: 1,
owner: '김서연',
project: '결제',
status: 'active',
progress: 72,
priority: 3,
labels: ['결제', '4분기', '감사'],
},
{
id: 2,
owner: '이준호',
project: '검색',
status: 'done',
progress: 100,
priority: 2,
labels: ['검색'],
},
{
id: 3,
owner: '박민지',
project: '모바일 앱',
status: 'blocked',
progress: 25,
priority: 3,
labels: ['모바일', '출시'],
},
{
id: 4,
owner: '최도윤',
project: '문서 사이트',
status: 'active',
progress: 9,
priority: 1,
labels: ['문서'],
},
{
id: 5,
owner: '정하은',
project: '데이터 내보내기',
status: 'active',
progress: 90,
priority: 2,
labels: [],
},
],
rowKey: 'id',
filterRow: true,
saveMode: 'none',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '머리글을 눌러 정렬하거나, 머리글 아래 입력 칸으로 거를 수 있어요.',
en: 'Click a header to sort, or filter with the inputs under the headers.',
});
const stop = nameBars('진행률', 1);
// 머리글을 눌러 정렬하거나 입력 칸으로 걸러도 위의 선택 상자가 지금 상태를 따라가게 맞춰요.
const sortBox = document.getElementById('sort');
const statusBox = document.getElementById('status');
const offs = [
api.on('sortChanged', ({ sortModel }) => {
const only = sortModel.length === 1 ? sortModel[0] : undefined;
const value =
only &&
only.direction === 'desc' &&
(only.columnId === 'progress' || only.columnId === 'priority')
? only.columnId
: 'none';
if (sortBox instanceof HTMLSelectElement) sortBox.value = value;
}),
api.on('filterChanged', ({ filterModel }) => {
const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
const value =
only && only.columnId === 'status' && only.operator === 'equals'
? String(only.value)
: 'all';
if (statusBox instanceof HTMLSelectElement) statusBox.value = value;
}),
];
return () => {
stop();
offs.forEach((off) => off());
};
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => {
const by = value === 'progress' || value === 'priority' ? value : '';
api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
say({
ko: by
? `${by === 'progress' ? '진행률' : '중요도'} 높은 순으로 정렬했어요. (숫자 기준)`
: '정렬을 풀었어요.',
en: by
? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
: 'Sort cleared.',
});
},
status: (api: GridApi<Row>, value?: string) => {
api.setFilterModel(
value && value !== 'all'
? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
: null,
);
say({
ko:
value && value !== 'all'
? `상태가 "${value}"인 줄만 남겼어요. (배지 뒤의 원래 값으로 걸러요)`
: '필터를 풀었어요.',
en:
value && value !== 'all'
? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
: 'Filter cleared.',
});
},
};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="Sort" id="sort">
<option value="none" selected>No sort</option>
<option value="progress">Progress high first</option>
<option value="priority">Priority high first</option>
</select>
<select aria-label="Show status" id="status">
<option value="all" selected>All</option>
<option value="active">Active</option>
<option value="done">Done</option>
<option value="blocked">Blocked</option>
</select>
</div>
<div id="grid" style="height: 320px"></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('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('status').addEventListener('change', (event) => actions.status(api, event.target.value));// The built-in progress bar has no name for screen readers, so this adds one using the text of the row's first cell.
function nameBars(label, cell = 0) {
const root = document.getElementById('grid');
if (!root)
return () => undefined;
const apply = () => {
for (const bar of root.querySelectorAll('[role="progressbar"]')) {
if (bar.getAttribute('aria-label'))
continue;
const row = bar.closest('[role="row"]');
const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
const mine = bar.closest('[role="gridcell"]');
const headers = root.querySelectorAll('[role="columnheader"]');
const header = headers[cells.indexOf(mine)]?.textContent?.trim();
bar.setAttribute('aria-label', `${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim());
}
};
const observer = new MutationObserver(apply);
observer.observe(root, { childList: true, subtree: true });
apply();
return () => observer.disconnect();
}
// All the built-in cell looks are used in one table. Whatever the cell looks like, the value is still plain text, a number or an array,
// so sorting and search (filter) use the original value, not the drawn look. Example: progress sorts as the number 72, not the text "72%".
export const options = {
columns: [
{ id: 'owner', title: 'Owner', width: 140, cellRenderer: 'avatar' },
{ id: 'project', title: 'Project', width: 140 },
{
id: 'status',
title: 'Status',
width: 100,
cellRenderer: 'badge',
cellRendererParams: {
map: {
active: { label: 'Active', tone: 'info' },
done: { label: 'Done', tone: 'success' },
blocked: { label: 'Blocked', tone: 'danger' },
},
},
},
{
id: 'progress',
title: 'Progress',
width: 160,
kind: 'number',
formatValue: (value) => `${String(value)}%`,
cellRenderer: 'progress',
cellRendererParams: {
ranges: [
{ upTo: 40, tone: 'danger' },
{ upTo: 80, tone: 'warning' },
{ upTo: 100, tone: 'success' },
],
},
},
{
id: 'priority',
title: 'Priority',
width: 100,
kind: 'number',
cellRenderer: 'rating',
cellRendererParams: { max: 3 },
},
{
id: 'labels',
title: 'Labels',
width: 170,
cellRenderer: 'tags',
cellRendererParams: { max: 2 },
sortable: false,
filterable: false,
},
],
rows: [
{
id: 1,
owner: 'Olivia Reed',
project: 'Payments',
status: 'active',
progress: 72,
priority: 3,
labels: ['payments', 'Q4', 'audit'],
},
{
id: 2,
owner: 'Liam Carter',
project: 'Search',
status: 'done',
progress: 100,
priority: 2,
labels: ['search'],
},
{
id: 3,
owner: 'Emma Stone',
project: 'Mobile app',
status: 'blocked',
progress: 25,
priority: 3,
labels: ['mobile', 'launch'],
},
{
id: 4,
owner: 'Noah Wright',
project: 'Docs site',
status: 'active',
progress: 9,
priority: 1,
labels: ['docs'],
},
{
id: 5,
owner: 'Ava Brooks',
project: 'Data export',
status: 'active',
progress: 90,
priority: 2,
labels: [],
},
],
rowKey: 'id',
filterRow: true,
saveMode: 'none',
};
let say = () => { };
export function setup(api, log) {
say = log;
log('Click a header to sort, or filter with the inputs under the headers.');
const stop = nameBars('Progress', 1);
// Keep the select boxes above in step with the current state when you sort by header click or filter with the inputs.
const sortBox = document.getElementById('sort');
const statusBox = document.getElementById('status');
const offs = [
api.on('sortChanged', ({ sortModel }) => {
const only = sortModel.length === 1 ? sortModel[0] : undefined;
const value = only &&
only.direction === 'desc' &&
(only.columnId === 'progress' || only.columnId === 'priority')
? only.columnId
: 'none';
if (sortBox instanceof HTMLSelectElement)
sortBox.value = value;
}),
api.on('filterChanged', ({ filterModel }) => {
const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
const value = only && only.columnId === 'status' && only.operator === 'equals'
? String(only.value)
: 'all';
if (statusBox instanceof HTMLSelectElement)
statusBox.value = value;
}),
];
return () => {
stop();
offs.forEach((off) => off());
};
}
export const actions = {
sort: (api, value) => {
const by = value === 'progress' || value === 'priority' ? value : '';
api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
say(by
? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
: 'Sort cleared.');
},
status: (api, value) => {
api.setFilterModel(value && value !== 'all'
? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
: null);
say(value && value !== 'all'
? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
: 'Filter cleared.');
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Different cell looks, but sort and filter use the real value</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Sort" id="sort">
<option value="none" selected>No sort</option>
<option value="progress">Progress high first</option>
<option value="priority">Priority high first</option>
</select>
<select aria-label="Show status" id="status">
<option value="all" selected>All</option>
<option value="active">Active</option>
<option value="done">Done</option>
<option value="blocked">Blocked</option>
</select>
</div>
<div id="grid" style="height: 320px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// The built-in progress bar has no name for screen readers, so this adds one using the text of the row's first cell.
function nameBars(label, cell = 0) {
const root = document.getElementById('grid');
if (!root)
return () => undefined;
const apply = () => {
for (const bar of root.querySelectorAll('[role="progressbar"]')) {
if (bar.getAttribute('aria-label'))
continue;
const row = bar.closest('[role="row"]');
const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
const mine = bar.closest('[role="gridcell"]');
const headers = root.querySelectorAll('[role="columnheader"]');
const header = headers[cells.indexOf(mine)]?.textContent?.trim();
bar.setAttribute('aria-label', `${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim());
}
};
const observer = new MutationObserver(apply);
observer.observe(root, { childList: true, subtree: true });
apply();
return () => observer.disconnect();
}
// All the built-in cell looks are used in one table. Whatever the cell looks like, the value is still plain text, a number or an array,
// so sorting and search (filter) use the original value, not the drawn look. Example: progress sorts as the number 72, not the text "72%".
const options = {
columns: [
{ id: 'owner', title: 'Owner', width: 140, cellRenderer: 'avatar' },
{ id: 'project', title: 'Project', width: 140 },
{
id: 'status',
title: 'Status',
width: 100,
cellRenderer: 'badge',
cellRendererParams: {
map: {
active: { label: 'Active', tone: 'info' },
done: { label: 'Done', tone: 'success' },
blocked: { label: 'Blocked', tone: 'danger' },
},
},
},
{
id: 'progress',
title: 'Progress',
width: 160,
kind: 'number',
formatValue: (value) => `${String(value)}%`,
cellRenderer: 'progress',
cellRendererParams: {
ranges: [
{ upTo: 40, tone: 'danger' },
{ upTo: 80, tone: 'warning' },
{ upTo: 100, tone: 'success' },
],
},
},
{
id: 'priority',
title: 'Priority',
width: 100,
kind: 'number',
cellRenderer: 'rating',
cellRendererParams: { max: 3 },
},
{
id: 'labels',
title: 'Labels',
width: 170,
cellRenderer: 'tags',
cellRendererParams: { max: 2 },
sortable: false,
filterable: false,
},
],
rows: [
{
id: 1,
owner: 'Olivia Reed',
project: 'Payments',
status: 'active',
progress: 72,
priority: 3,
labels: ['payments', 'Q4', 'audit'],
},
{
id: 2,
owner: 'Liam Carter',
project: 'Search',
status: 'done',
progress: 100,
priority: 2,
labels: ['search'],
},
{
id: 3,
owner: 'Emma Stone',
project: 'Mobile app',
status: 'blocked',
progress: 25,
priority: 3,
labels: ['mobile', 'launch'],
},
{
id: 4,
owner: 'Noah Wright',
project: 'Docs site',
status: 'active',
progress: 9,
priority: 1,
labels: ['docs'],
},
{
id: 5,
owner: 'Ava Brooks',
project: 'Data export',
status: 'active',
progress: 90,
priority: 2,
labels: [],
},
],
rowKey: 'id',
filterRow: true,
saveMode: 'none',
};
let say = () => { };
function setup(api, log) {
say = log;
log('Click a header to sort, or filter with the inputs under the headers.');
const stop = nameBars('Progress', 1);
// Keep the select boxes above in step with the current state when you sort by header click or filter with the inputs.
const sortBox = document.getElementById('sort');
const statusBox = document.getElementById('status');
const offs = [
api.on('sortChanged', ({ sortModel }) => {
const only = sortModel.length === 1 ? sortModel[0] : undefined;
const value = only &&
only.direction === 'desc' &&
(only.columnId === 'progress' || only.columnId === 'priority')
? only.columnId
: 'none';
if (sortBox instanceof HTMLSelectElement)
sortBox.value = value;
}),
api.on('filterChanged', ({ filterModel }) => {
const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
const value = only && only.columnId === 'status' && only.operator === 'equals'
? String(only.value)
: 'all';
if (statusBox instanceof HTMLSelectElement)
statusBox.value = value;
}),
];
return () => {
stop();
offs.forEach((off) => off());
};
}
const actions = {
sort: (api, value) => {
const by = value === 'progress' || value === 'priority' ? value : '';
api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
say(by
? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
: 'Sort cleared.');
},
status: (api, value) => {
api.setFilterModel(value && value !== 'all'
? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
: null);
say(value && value !== 'all'
? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
: 'Filter cleared.');
},
};
options.ariaLabel = "Different cell looks, but sort and filter use the real value";
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('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('status').addEventListener('change', (event) => actions.status(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">
<select
aria-label="Sort"
disabled={!api}
onChange={(event) => api && actions.sort(api, event.target.value)}
>
<option value="none">No sort</option>
<option value="progress">Progress high first</option>
<option value="priority">Priority high first</option>
</select>
<select defaultValue="none"
aria-label="Show status"
disabled={!api}
onChange={(event) => api && actions.status(api, event.target.value)}
>
<option value="all">All</option>
<option value="active">Active</option>
<option value="done">Done</option>
<option value="blocked">Blocked</option>
</select>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
// The built-in progress bar has no name for screen readers, so this adds one using the text of the row's first cell.
function nameBars(label: string, cell = 0): () => void {
const root = document.getElementById('grid');
if (!root) return () => undefined;
const apply = (): void => {
for (const bar of root.querySelectorAll('[role="progressbar"]')) {
if (bar.getAttribute('aria-label')) continue;
const row = bar.closest('[role="row"]');
const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
const mine = bar.closest('[role="gridcell"]');
const headers = root.querySelectorAll('[role="columnheader"]');
const header = headers[cells.indexOf(mine as Element)]?.textContent?.trim();
bar.setAttribute(
'aria-label',
`${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim(),
);
}
};
const observer = new MutationObserver(apply);
observer.observe(root, { childList: true, subtree: true });
apply();
return () => observer.disconnect();
}
export interface Row {
id: number;
owner: string;
project: string;
status: string;
progress: number;
priority: number;
labels: string[];
}
// All the built-in cell looks are used in one table. Whatever the cell looks like, the value is still plain text, a number or an array,
// so sorting and search (filter) use the original value, not the drawn look. Example: progress sorts as the number 72, not the text "72%".
export const options: GridOptions<Row> = {
columns: [
{ id: 'owner', title: 'Owner', width: 140, cellRenderer: 'avatar' },
{ id: 'project', title: 'Project', width: 140 },
{
id: 'status',
title: 'Status',
width: 100,
cellRenderer: 'badge',
cellRendererParams: {
map: {
active: { label: 'Active', tone: 'info' },
done: { label: 'Done', tone: 'success' },
blocked: { label: 'Blocked', tone: 'danger' },
},
},
},
{
id: 'progress',
title: 'Progress',
width: 160,
kind: 'number',
formatValue: (value) => `${String(value)}%`,
cellRenderer: 'progress',
cellRendererParams: {
ranges: [
{ upTo: 40, tone: 'danger' },
{ upTo: 80, tone: 'warning' },
{ upTo: 100, tone: 'success' },
],
},
},
{
id: 'priority',
title: 'Priority',
width: 100,
kind: 'number',
cellRenderer: 'rating',
cellRendererParams: { max: 3 },
},
{
id: 'labels',
title: 'Labels',
width: 170,
cellRenderer: 'tags',
cellRendererParams: { max: 2 },
sortable: false,
filterable: false,
},
],
rows: [
{
id: 1,
owner: 'Olivia Reed',
project: 'Payments',
status: 'active',
progress: 72,
priority: 3,
labels: ['payments', 'Q4', 'audit'],
},
{
id: 2,
owner: 'Liam Carter',
project: 'Search',
status: 'done',
progress: 100,
priority: 2,
labels: ['search'],
},
{
id: 3,
owner: 'Emma Stone',
project: 'Mobile app',
status: 'blocked',
progress: 25,
priority: 3,
labels: ['mobile', 'launch'],
},
{
id: 4,
owner: 'Noah Wright',
project: 'Docs site',
status: 'active',
progress: 9,
priority: 1,
labels: ['docs'],
},
{
id: 5,
owner: 'Ava Brooks',
project: 'Data export',
status: 'active',
progress: 90,
priority: 2,
labels: [],
},
],
rowKey: 'id',
filterRow: true,
saveMode: 'none',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Click a header to sort, or filter with the inputs under the headers.');
const stop = nameBars('Progress', 1);
// Keep the select boxes above in step with the current state when you sort by header click or filter with the inputs.
const sortBox = document.getElementById('sort');
const statusBox = document.getElementById('status');
const offs = [
api.on('sortChanged', ({ sortModel }) => {
const only = sortModel.length === 1 ? sortModel[0] : undefined;
const value =
only &&
only.direction === 'desc' &&
(only.columnId === 'progress' || only.columnId === 'priority')
? only.columnId
: 'none';
if (sortBox instanceof HTMLSelectElement) sortBox.value = value;
}),
api.on('filterChanged', ({ filterModel }) => {
const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
const value =
only && only.columnId === 'status' && only.operator === 'equals'
? String(only.value)
: 'all';
if (statusBox instanceof HTMLSelectElement) statusBox.value = value;
}),
];
return () => {
stop();
offs.forEach((off) => off());
};
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => {
const by = value === 'progress' || value === 'priority' ? value : '';
api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
say(
by
? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
: 'Sort cleared.',
);
},
status: (api: GridApi<Row>, value?: string) => {
api.setFilterModel(
value && value !== 'all'
? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
: null,
);
say(
value && value !== 'all'
? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
: 'Filter cleared.',
);
},
};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="Sort"
:disabled="!api"
@change="api && actions.sort(api, ($event.target as HTMLSelectElement).value)"
>
<option value="none" selected>No sort</option>
<option value="progress">Progress high first</option>
<option value="priority">Priority high first</option>
</select>
<select
aria-label="Show status"
:disabled="!api"
@change="api && actions.status(api, ($event.target as HTMLSelectElement).value)"
>
<option value="all" selected>All</option>
<option value="active">Active</option>
<option value="done">Done</option>
<option value="blocked">Blocked</option>
</select>
</div>
<Grid style="height: 320px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
// The built-in progress bar has no name for screen readers, so this adds one using the text of the row's first cell.
function nameBars(label: string, cell = 0): () => void {
const root = document.getElementById('grid');
if (!root) return () => undefined;
const apply = (): void => {
for (const bar of root.querySelectorAll('[role="progressbar"]')) {
if (bar.getAttribute('aria-label')) continue;
const row = bar.closest('[role="row"]');
const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
const mine = bar.closest('[role="gridcell"]');
const headers = root.querySelectorAll('[role="columnheader"]');
const header = headers[cells.indexOf(mine as Element)]?.textContent?.trim();
bar.setAttribute(
'aria-label',
`${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim(),
);
}
};
const observer = new MutationObserver(apply);
observer.observe(root, { childList: true, subtree: true });
apply();
return () => observer.disconnect();
}
export interface Row {
id: number;
owner: string;
project: string;
status: string;
progress: number;
priority: number;
labels: string[];
}
// All the built-in cell looks are used in one table. Whatever the cell looks like, the value is still plain text, a number or an array,
// so sorting and search (filter) use the original value, not the drawn look. Example: progress sorts as the number 72, not the text "72%".
export const options: GridOptions<Row> = {
columns: [
{ id: 'owner', title: 'Owner', width: 140, cellRenderer: 'avatar' },
{ id: 'project', title: 'Project', width: 140 },
{
id: 'status',
title: 'Status',
width: 100,
cellRenderer: 'badge',
cellRendererParams: {
map: {
active: { label: 'Active', tone: 'info' },
done: { label: 'Done', tone: 'success' },
blocked: { label: 'Blocked', tone: 'danger' },
},
},
},
{
id: 'progress',
title: 'Progress',
width: 160,
kind: 'number',
formatValue: (value) => `${String(value)}%`,
cellRenderer: 'progress',
cellRendererParams: {
ranges: [
{ upTo: 40, tone: 'danger' },
{ upTo: 80, tone: 'warning' },
{ upTo: 100, tone: 'success' },
],
},
},
{
id: 'priority',
title: 'Priority',
width: 100,
kind: 'number',
cellRenderer: 'rating',
cellRendererParams: { max: 3 },
},
{
id: 'labels',
title: 'Labels',
width: 170,
cellRenderer: 'tags',
cellRendererParams: { max: 2 },
sortable: false,
filterable: false,
},
],
rows: [
{
id: 1,
owner: 'Olivia Reed',
project: 'Payments',
status: 'active',
progress: 72,
priority: 3,
labels: ['payments', 'Q4', 'audit'],
},
{
id: 2,
owner: 'Liam Carter',
project: 'Search',
status: 'done',
progress: 100,
priority: 2,
labels: ['search'],
},
{
id: 3,
owner: 'Emma Stone',
project: 'Mobile app',
status: 'blocked',
progress: 25,
priority: 3,
labels: ['mobile', 'launch'],
},
{
id: 4,
owner: 'Noah Wright',
project: 'Docs site',
status: 'active',
progress: 9,
priority: 1,
labels: ['docs'],
},
{
id: 5,
owner: 'Ava Brooks',
project: 'Data export',
status: 'active',
progress: 90,
priority: 2,
labels: [],
},
],
rowKey: 'id',
filterRow: true,
saveMode: 'none',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Click a header to sort, or filter with the inputs under the headers.');
const stop = nameBars('Progress', 1);
// Keep the select boxes above in step with the current state when you sort by header click or filter with the inputs.
const sortBox = document.getElementById('sort');
const statusBox = document.getElementById('status');
const offs = [
api.on('sortChanged', ({ sortModel }) => {
const only = sortModel.length === 1 ? sortModel[0] : undefined;
const value =
only &&
only.direction === 'desc' &&
(only.columnId === 'progress' || only.columnId === 'priority')
? only.columnId
: 'none';
if (sortBox instanceof HTMLSelectElement) sortBox.value = value;
}),
api.on('filterChanged', ({ filterModel }) => {
const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
const value =
only && only.columnId === 'status' && only.operator === 'equals'
? String(only.value)
: 'all';
if (statusBox instanceof HTMLSelectElement) statusBox.value = value;
}),
];
return () => {
stop();
offs.forEach((off) => off());
};
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => {
const by = value === 'progress' || value === 'priority' ? value : '';
api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
say(
by
? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
: 'Sort cleared.',
);
},
status: (api: GridApi<Row>, value?: string) => {
api.setFilterModel(
value && value !== 'all'
? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
: null,
);
say(
value && value !== 'all'
? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
: 'Filter cleared.',
);
},
};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="Sort"
[disabled]="!api"
(change)="api && actions.sort(api, $any($event.target).value)"
>
<option value="none" selected>No sort</option>
<option value="progress">Progress high first</option>
<option value="priority">Priority high first</option>
</select>
<select
aria-label="Show status"
[disabled]="!api"
(change)="api && actions.status(api, $any($event.target).value)"
>
<option value="all" selected>All</option>
<option value="active">Active</option>
<option value="done">Done</option>
<option value="blocked">Blocked</option>
</select>
</div>
<mx-grid style="height: 320px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
// The built-in progress bar has no name for screen readers, so this adds one using the text of the row's first cell.
function nameBars(label: string, cell = 0): () => void {
const root = document.getElementById('grid');
if (!root) return () => undefined;
const apply = (): void => {
for (const bar of root.querySelectorAll('[role="progressbar"]')) {
if (bar.getAttribute('aria-label')) continue;
const row = bar.closest('[role="row"]');
const cells = [...(row?.querySelectorAll('[role="gridcell"]:not(.mxg-checkcell)') ?? [])];
const mine = bar.closest('[role="gridcell"]');
const headers = root.querySelectorAll('[role="columnheader"]');
const header = headers[cells.indexOf(mine as Element)]?.textContent?.trim();
bar.setAttribute(
'aria-label',
`${cells[cell]?.textContent?.trim() ?? ''} ${header || label}`.trim(),
);
}
};
const observer = new MutationObserver(apply);
observer.observe(root, { childList: true, subtree: true });
apply();
return () => observer.disconnect();
}
export interface Row {
id: number;
owner: string;
project: string;
status: string;
progress: number;
priority: number;
labels: string[];
}
// All the built-in cell looks are used in one table. Whatever the cell looks like, the value is still plain text, a number or an array,
// so sorting and search (filter) use the original value, not the drawn look. Example: progress sorts as the number 72, not the text "72%".
export const options: GridOptions<Row> = {
columns: [
{ id: 'owner', title: 'Owner', width: 140, cellRenderer: 'avatar' },
{ id: 'project', title: 'Project', width: 140 },
{
id: 'status',
title: 'Status',
width: 100,
cellRenderer: 'badge',
cellRendererParams: {
map: {
active: { label: 'Active', tone: 'info' },
done: { label: 'Done', tone: 'success' },
blocked: { label: 'Blocked', tone: 'danger' },
},
},
},
{
id: 'progress',
title: 'Progress',
width: 160,
kind: 'number',
formatValue: (value) => `${String(value)}%`,
cellRenderer: 'progress',
cellRendererParams: {
ranges: [
{ upTo: 40, tone: 'danger' },
{ upTo: 80, tone: 'warning' },
{ upTo: 100, tone: 'success' },
],
},
},
{
id: 'priority',
title: 'Priority',
width: 100,
kind: 'number',
cellRenderer: 'rating',
cellRendererParams: { max: 3 },
},
{
id: 'labels',
title: 'Labels',
width: 170,
cellRenderer: 'tags',
cellRendererParams: { max: 2 },
sortable: false,
filterable: false,
},
],
rows: [
{
id: 1,
owner: 'Olivia Reed',
project: 'Payments',
status: 'active',
progress: 72,
priority: 3,
labels: ['payments', 'Q4', 'audit'],
},
{
id: 2,
owner: 'Liam Carter',
project: 'Search',
status: 'done',
progress: 100,
priority: 2,
labels: ['search'],
},
{
id: 3,
owner: 'Emma Stone',
project: 'Mobile app',
status: 'blocked',
progress: 25,
priority: 3,
labels: ['mobile', 'launch'],
},
{
id: 4,
owner: 'Noah Wright',
project: 'Docs site',
status: 'active',
progress: 9,
priority: 1,
labels: ['docs'],
},
{
id: 5,
owner: 'Ava Brooks',
project: 'Data export',
status: 'active',
progress: 90,
priority: 2,
labels: [],
},
],
rowKey: 'id',
filterRow: true,
saveMode: 'none',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Click a header to sort, or filter with the inputs under the headers.');
const stop = nameBars('Progress', 1);
// Keep the select boxes above in step with the current state when you sort by header click or filter with the inputs.
const sortBox = document.getElementById('sort');
const statusBox = document.getElementById('status');
const offs = [
api.on('sortChanged', ({ sortModel }) => {
const only = sortModel.length === 1 ? sortModel[0] : undefined;
const value =
only &&
only.direction === 'desc' &&
(only.columnId === 'progress' || only.columnId === 'priority')
? only.columnId
: 'none';
if (sortBox instanceof HTMLSelectElement) sortBox.value = value;
}),
api.on('filterChanged', ({ filterModel }) => {
const only = filterModel?.items.length === 1 ? filterModel.items[0] : undefined;
const value =
only && only.columnId === 'status' && only.operator === 'equals'
? String(only.value)
: 'all';
if (statusBox instanceof HTMLSelectElement) statusBox.value = value;
}),
];
return () => {
stop();
offs.forEach((off) => off());
};
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => {
const by = value === 'progress' || value === 'priority' ? value : '';
api.setSortModel(by ? [{ columnId: by, direction: 'desc' }] : []);
say(
by
? `Sorted by ${by === 'progress' ? 'progress' : 'importance'}, highest first. (by number)`
: 'Sort cleared.',
);
},
status: (api: GridApi<Row>, value?: string) => {
api.setFilterModel(
value && value !== 'all'
? { match: 'all', items: [{ columnId: 'status', operator: 'equals', value }] }
: null,
);
say(
value && value !== 'all'
? `Kept only rows with status "${value}". (filtering uses the original value behind the badge)`
: 'Filter cleared.',
);
},
};