고객을 열어 주문 내역 보기Open a customer to see their orders
고객 줄 아래에 주문 내역 패널이 펼쳐져요. 여러 개를 동시에 열 수도, 하나만 열 수도, 행을 고를 때마다 상세가 따라오게 할 수도 있어요.A panel with the customer's orders opens right under the row. Open several at once, only one, or let the panel follow the selected row.
코드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="mode">
<option value="free" selected>마음대로 여러 개</option>
<option value="one">하나만 열기</option>
<option value="follow">행을 고르면 따라가기</option>
</select>
<button type="button" id="closeAll">모두 닫기</button>
</div>
<div id="grid" style="height: 460px"></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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('closeAll').addEventListener('click', () => actions.closeAll(api));const customers = [
'한빛물류',
'푸른식품',
'북촌상회',
'단풍리테일',
'정상테크',
'바다수산',
'새봄약품',
'은하전자',
];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const products = [
'A4 복사지',
'라벨 스티커',
'박스 테이프',
'포장 완충재',
'바코드 라벨러',
'스트레치 필름',
];
// 고객마다 주문이 2~5건. 상세 패널에서 보여 줄 주문 내역을 고객 번호로 만들어요.
// 실제로는 고객 번호로 서버에 요청해서 받아 오는 자리예요.
function ordersOf(index) {
return Array.from({ length: 2 + (index % 4) }, (_, k) => {
const qty = 1 + ((index * 3 + k * 5) % 9);
const price = 4000 + ((index + k) % 6) * 2500;
return {
date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
product: products[(index + k * 2) % products.length],
qty,
amount: qty * price,
};
});
}
const rows = customers.map((customer, i) => ({
id: `cust${i + 1}`,
customer,
city: cities[i],
orders: ordersOf(i).length,
total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const won = (value) => `${value.toLocaleString('ko-KR')}원`;
// 상세 패널은 어댑터가 만들어요. 값은 항상 textContent로 넣어서 HTML로 해석되지 않아요.
const panel = () => {
let box;
const fill = (row) => {
const index = rows.findIndex((r) => r.id === row.id);
const head = document.createElement('strong');
head.textContent = `${row.customer} 주문 내역 (${row.orders}건)`;
const table = document.createElement('table');
table.style.cssText =
'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
const line = (cells, bold) => {
const tr = document.createElement('tr');
cells.forEach((text, c) => {
const td = document.createElement(bold ? 'th' : 'td');
td.textContent = text;
td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
tr.append(td);
});
return tr;
};
table.append(line(['주문일', '상품', '수량', '금액'], true));
for (const o of ordersOf(index))
table.append(line([o.date, o.product, String(o.qty), won(o.amount)], false));
// 좁은 화면에서는 표만 옆으로 스크롤돼요.
const scroller = document.createElement('div');
scroller.style.overflowX = 'auto';
scroller.append(table);
box.replaceChildren(head, scroller);
};
return {
mount(element, { row }) {
box = element;
element.style.padding = '8px 16px';
fill(row);
},
update({ row }) {
fill(row);
},
destroy() { },
};
};
export const options = {
columns: [
{ id: 'customer', title: '고객', width: 150 },
{ id: 'city', title: '지역', width: 90 },
{ id: 'orders', title: '주문 수', kind: 'number', width: 90, align: 'end' },
{
id: 'total',
title: '주문 합계',
kind: 'number',
width: 130,
align: 'end',
formatValue: (v) => won(Number(v)),
},
],
rows,
rowKey: 'id',
selection: 'single',
// 주문이 많은 고객일수록 패널을 더 높게. 처음에는 3번 고객(cust3)이 열려 있어요.
detail: {
renderer: panel,
height: (row) => 62 + row.orders * 25,
expanded: ['cust3'],
},
};
let mode = 'free';
let busy = false; // 우리가 열고 닫는 동안 오는 이벤트는 무시해서 서로 부르지 않게 해요.
function openOnly(api, key) {
busy = true;
for (const row of api.getRows())
if (row.id !== key && api.isDetailExpanded(row.id))
api.collapseDetail(row.id);
if (!api.isDetailExpanded(key))
api.expandDetail(key);
busy = false;
}
export function setup(api, log) {
const nameOf = (key) => api.getRowByKey(key)?.customer ?? key;
const offs = [
api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${nameOf(String(rowKey))} 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`,
});
if (!busy && expanded && mode === 'one')
openOnly(api, String(rowKey));
}),
api.on('selectionChanged', ({ selectedKeys }) => {
const key = selectedKeys[0];
if (mode === 'follow' && key !== undefined && !busy)
openOnly(api, String(key));
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
mode: (api, value) => {
mode = value === 'one' || value === 'follow' ? value : 'free';
const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
if (mode !== 'free' && open.length > 1)
openOnly(api, open[0].id);
},
closeAll: (api) => {
for (const row of api.getRows())
if (api.isDetailExpanded(row.id))
api.collapseDetail(row.id);
},
};<!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="mode">
<option value="free" selected>마음대로 여러 개</option>
<option value="one">하나만 열기</option>
<option value="follow">행을 고르면 따라가기</option>
</select>
<button type="button" id="closeAll">모두 닫기</button>
</div>
<div id="grid" style="height: 460px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const customers = [
'한빛물류',
'푸른식품',
'북촌상회',
'단풍리테일',
'정상테크',
'바다수산',
'새봄약품',
'은하전자',
];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const products = [
'A4 복사지',
'라벨 스티커',
'박스 테이프',
'포장 완충재',
'바코드 라벨러',
'스트레치 필름',
];
// 고객마다 주문이 2~5건. 상세 패널에서 보여 줄 주문 내역을 고객 번호로 만들어요.
// 실제로는 고객 번호로 서버에 요청해서 받아 오는 자리예요.
function ordersOf(index) {
return Array.from({ length: 2 + (index % 4) }, (_, k) => {
const qty = 1 + ((index * 3 + k * 5) % 9);
const price = 4000 + ((index + k) % 6) * 2500;
return {
date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
product: products[(index + k * 2) % products.length],
qty,
amount: qty * price,
};
});
}
const rows = customers.map((customer, i) => ({
id: `cust${i + 1}`,
customer,
city: cities[i],
orders: ordersOf(i).length,
total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const won = (value) => `${value.toLocaleString('ko-KR')}원`;
// 상세 패널은 어댑터가 만들어요. 값은 항상 textContent로 넣어서 HTML로 해석되지 않아요.
const panel = () => {
let box;
const fill = (row) => {
const index = rows.findIndex((r) => r.id === row.id);
const head = document.createElement('strong');
head.textContent = `${row.customer} 주문 내역 (${row.orders}건)`;
const table = document.createElement('table');
table.style.cssText =
'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
const line = (cells, bold) => {
const tr = document.createElement('tr');
cells.forEach((text, c) => {
const td = document.createElement(bold ? 'th' : 'td');
td.textContent = text;
td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
tr.append(td);
});
return tr;
};
table.append(line(['주문일', '상품', '수량', '금액'], true));
for (const o of ordersOf(index))
table.append(line([o.date, o.product, String(o.qty), won(o.amount)], false));
// 좁은 화면에서는 표만 옆으로 스크롤돼요.
const scroller = document.createElement('div');
scroller.style.overflowX = 'auto';
scroller.append(table);
box.replaceChildren(head, scroller);
};
return {
mount(element, { row }) {
box = element;
element.style.padding = '8px 16px';
fill(row);
},
update({ row }) {
fill(row);
},
destroy() { },
};
};
const options = {
columns: [
{ id: 'customer', title: '고객', width: 150 },
{ id: 'city', title: '지역', width: 90 },
{ id: 'orders', title: '주문 수', kind: 'number', width: 90, align: 'end' },
{
id: 'total',
title: '주문 합계',
kind: 'number',
width: 130,
align: 'end',
formatValue: (v) => won(Number(v)),
},
],
rows,
rowKey: 'id',
selection: 'single',
// 주문이 많은 고객일수록 패널을 더 높게. 처음에는 3번 고객(cust3)이 열려 있어요.
detail: {
renderer: panel,
height: (row) => 62 + row.orders * 25,
expanded: ['cust3'],
},
};
let mode = 'free';
let busy = false; // 우리가 열고 닫는 동안 오는 이벤트는 무시해서 서로 부르지 않게 해요.
function openOnly(api, key) {
busy = true;
for (const row of api.getRows())
if (row.id !== key && api.isDetailExpanded(row.id))
api.collapseDetail(row.id);
if (!api.isDetailExpanded(key))
api.expandDetail(key);
busy = false;
}
function setup(api, log) {
const nameOf = (key) => api.getRowByKey(key)?.customer ?? key;
const offs = [
api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${nameOf(String(rowKey))} 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`,
});
if (!busy && expanded && mode === 'one')
openOnly(api, String(rowKey));
}),
api.on('selectionChanged', ({ selectedKeys }) => {
const key = selectedKeys[0];
if (mode === 'follow' && key !== undefined && !busy)
openOnly(api, String(key));
}),
];
return () => offs.forEach((off) => off());
}
const actions = {
mode: (api, value) => {
mode = value === 'one' || value === 'follow' ? value : 'free';
const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
if (mode !== 'free' && open.length > 1)
openOnly(api, open[0].id);
},
closeAll: (api) => {
for (const row of api.getRows())
if (api.isDetailExpanded(row.id))
api.collapseDetail(row.id);
},
};
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('closeAll').addEventListener('click', () => actions.closeAll(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.mode(api, event.target.value)}
>
<option value="free">마음대로 여러 개</option>
<option value="one">하나만 열기</option>
<option value="follow">행을 고르면 따라가기</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.closeAll(api)}
>모두 닫기</button>
</div>
<Grid style={{ height: 460 }} ref={gridRef} options={options} />
</>
);
}import type { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
customer: string;
city: string;
orders: number;
total: number;
}
interface Order {
date: string;
product: string;
qty: number;
amount: number;
}
const customers = [
'한빛물류',
'푸른식품',
'북촌상회',
'단풍리테일',
'정상테크',
'바다수산',
'새봄약품',
'은하전자',
];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const products = [
'A4 복사지',
'라벨 스티커',
'박스 테이프',
'포장 완충재',
'바코드 라벨러',
'스트레치 필름',
];
// 고객마다 주문이 2~5건. 상세 패널에서 보여 줄 주문 내역을 고객 번호로 만들어요.
// 실제로는 고객 번호로 서버에 요청해서 받아 오는 자리예요.
function ordersOf(index: number): Order[] {
return Array.from({ length: 2 + (index % 4) }, (_, k) => {
const qty = 1 + ((index * 3 + k * 5) % 9);
const price = 4000 + ((index + k) % 6) * 2500;
return {
date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
product: products[(index + k * 2) % products.length],
qty,
amount: qty * price,
};
});
}
const rows: Row[] = customers.map((customer, i) => ({
id: `cust${i + 1}`,
customer,
city: cities[i],
orders: ordersOf(i).length,
total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const won = (value: number) => `${value.toLocaleString('ko-KR')}원`;
// 상세 패널은 어댑터가 만들어요. 값은 항상 textContent로 넣어서 HTML로 해석되지 않아요.
const panel = (): DetailRendererAdapter<Row> => {
let box: HTMLElement;
const fill = (row: Row): void => {
const index = rows.findIndex((r) => r.id === row.id);
const head = document.createElement('strong');
head.textContent = `${row.customer} 주문 내역 (${row.orders}건)`;
const table = document.createElement('table');
table.style.cssText =
'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
const line = (cells: string[], bold: boolean): HTMLTableRowElement => {
const tr = document.createElement('tr');
cells.forEach((text, c) => {
const td = document.createElement(bold ? 'th' : 'td');
td.textContent = text;
td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
tr.append(td);
});
return tr;
};
table.append(line(['주문일', '상품', '수량', '금액'], true));
for (const o of ordersOf(index))
table.append(line([o.date, o.product, String(o.qty), won(o.amount)], false));
// 좁은 화면에서는 표만 옆으로 스크롤돼요.
const scroller = document.createElement('div');
scroller.style.overflowX = 'auto';
scroller.append(table);
box.replaceChildren(head, scroller);
};
return {
mount(element, { row }) {
box = element;
element.style.padding = '8px 16px';
fill(row);
},
update({ row }) {
fill(row);
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객', width: 150 },
{ id: 'city', title: '지역', width: 90 },
{ id: 'orders', title: '주문 수', kind: 'number', width: 90, align: 'end' },
{
id: 'total',
title: '주문 합계',
kind: 'number',
width: 130,
align: 'end',
formatValue: (v) => won(Number(v)),
},
],
rows,
rowKey: 'id',
selection: 'single',
// 주문이 많은 고객일수록 패널을 더 높게. 처음에는 3번 고객(cust3)이 열려 있어요.
detail: {
renderer: panel,
height: (row) => 62 + row.orders * 25,
expanded: ['cust3'],
},
};
type Mode = 'free' | 'one' | 'follow';
let mode: Mode = 'free';
let busy = false; // 우리가 열고 닫는 동안 오는 이벤트는 무시해서 서로 부르지 않게 해요.
function openOnly(api: GridApi<Row>, key: string): void {
busy = true;
for (const row of api.getRows())
if (row.id !== key && api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
if (!api.isDetailExpanded(key)) api.expandDetail(key);
busy = false;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const nameOf = (key: string) => api.getRowByKey(key)?.customer ?? key;
const offs = [
api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${nameOf(String(rowKey))} 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`,
});
if (!busy && expanded && mode === 'one') openOnly(api, String(rowKey));
}),
api.on('selectionChanged', ({ selectedKeys }) => {
const key = selectedKeys[0];
if (mode === 'follow' && key !== undefined && !busy) openOnly(api, String(key));
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = value === 'one' || value === 'follow' ? value : 'free';
const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
if (mode !== 'free' && open.length > 1) openOnly(api, open[0].id);
},
closeAll: (api: GridApi<Row>) => {
for (const row of api.getRows()) if (api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
},
};버튼을 누르면 이 예제의 코드가 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.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="free" selected>마음대로 여러 개</option>
<option value="one">하나만 열기</option>
<option value="follow">행을 고르면 따라가기</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.closeAll(api)"
>모두 닫기</button>
</div>
<Grid style="height: 460px" :options="options" @ready="onReady" />
</template>import type { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
customer: string;
city: string;
orders: number;
total: number;
}
interface Order {
date: string;
product: string;
qty: number;
amount: number;
}
const customers = [
'한빛물류',
'푸른식품',
'북촌상회',
'단풍리테일',
'정상테크',
'바다수산',
'새봄약품',
'은하전자',
];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const products = [
'A4 복사지',
'라벨 스티커',
'박스 테이프',
'포장 완충재',
'바코드 라벨러',
'스트레치 필름',
];
// 고객마다 주문이 2~5건. 상세 패널에서 보여 줄 주문 내역을 고객 번호로 만들어요.
// 실제로는 고객 번호로 서버에 요청해서 받아 오는 자리예요.
function ordersOf(index: number): Order[] {
return Array.from({ length: 2 + (index % 4) }, (_, k) => {
const qty = 1 + ((index * 3 + k * 5) % 9);
const price = 4000 + ((index + k) % 6) * 2500;
return {
date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
product: products[(index + k * 2) % products.length],
qty,
amount: qty * price,
};
});
}
const rows: Row[] = customers.map((customer, i) => ({
id: `cust${i + 1}`,
customer,
city: cities[i],
orders: ordersOf(i).length,
total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const won = (value: number) => `${value.toLocaleString('ko-KR')}원`;
// 상세 패널은 어댑터가 만들어요. 값은 항상 textContent로 넣어서 HTML로 해석되지 않아요.
const panel = (): DetailRendererAdapter<Row> => {
let box: HTMLElement;
const fill = (row: Row): void => {
const index = rows.findIndex((r) => r.id === row.id);
const head = document.createElement('strong');
head.textContent = `${row.customer} 주문 내역 (${row.orders}건)`;
const table = document.createElement('table');
table.style.cssText =
'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
const line = (cells: string[], bold: boolean): HTMLTableRowElement => {
const tr = document.createElement('tr');
cells.forEach((text, c) => {
const td = document.createElement(bold ? 'th' : 'td');
td.textContent = text;
td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
tr.append(td);
});
return tr;
};
table.append(line(['주문일', '상품', '수량', '금액'], true));
for (const o of ordersOf(index))
table.append(line([o.date, o.product, String(o.qty), won(o.amount)], false));
// 좁은 화면에서는 표만 옆으로 스크롤돼요.
const scroller = document.createElement('div');
scroller.style.overflowX = 'auto';
scroller.append(table);
box.replaceChildren(head, scroller);
};
return {
mount(element, { row }) {
box = element;
element.style.padding = '8px 16px';
fill(row);
},
update({ row }) {
fill(row);
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객', width: 150 },
{ id: 'city', title: '지역', width: 90 },
{ id: 'orders', title: '주문 수', kind: 'number', width: 90, align: 'end' },
{
id: 'total',
title: '주문 합계',
kind: 'number',
width: 130,
align: 'end',
formatValue: (v) => won(Number(v)),
},
],
rows,
rowKey: 'id',
selection: 'single',
// 주문이 많은 고객일수록 패널을 더 높게. 처음에는 3번 고객(cust3)이 열려 있어요.
detail: {
renderer: panel,
height: (row) => 62 + row.orders * 25,
expanded: ['cust3'],
},
};
type Mode = 'free' | 'one' | 'follow';
let mode: Mode = 'free';
let busy = false; // 우리가 열고 닫는 동안 오는 이벤트는 무시해서 서로 부르지 않게 해요.
function openOnly(api: GridApi<Row>, key: string): void {
busy = true;
for (const row of api.getRows())
if (row.id !== key && api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
if (!api.isDetailExpanded(key)) api.expandDetail(key);
busy = false;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const nameOf = (key: string) => api.getRowByKey(key)?.customer ?? key;
const offs = [
api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${nameOf(String(rowKey))} 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`,
});
if (!busy && expanded && mode === 'one') openOnly(api, String(rowKey));
}),
api.on('selectionChanged', ({ selectedKeys }) => {
const key = selectedKeys[0];
if (mode === 'follow' && key !== undefined && !busy) openOnly(api, String(key));
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = value === 'one' || value === 'follow' ? value : 'free';
const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
if (mode !== 'free' && open.length > 1) openOnly(api, open[0].id);
},
closeAll: (api: GridApi<Row>) => {
for (const row of api.getRows()) if (api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
},
};버튼을 누르면 이 예제의 코드가 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.mode(api, $any($event.target).value)"
>
<option value="free" selected>마음대로 여러 개</option>
<option value="one">하나만 열기</option>
<option value="follow">행을 고르면 따라가기</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.closeAll(api)"
>모두 닫기</button>
</div>
<mx-grid style="height: 460px" [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 { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
customer: string;
city: string;
orders: number;
total: number;
}
interface Order {
date: string;
product: string;
qty: number;
amount: number;
}
const customers = [
'한빛물류',
'푸른식품',
'북촌상회',
'단풍리테일',
'정상테크',
'바다수산',
'새봄약품',
'은하전자',
];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const products = [
'A4 복사지',
'라벨 스티커',
'박스 테이프',
'포장 완충재',
'바코드 라벨러',
'스트레치 필름',
];
// 고객마다 주문이 2~5건. 상세 패널에서 보여 줄 주문 내역을 고객 번호로 만들어요.
// 실제로는 고객 번호로 서버에 요청해서 받아 오는 자리예요.
function ordersOf(index: number): Order[] {
return Array.from({ length: 2 + (index % 4) }, (_, k) => {
const qty = 1 + ((index * 3 + k * 5) % 9);
const price = 4000 + ((index + k) % 6) * 2500;
return {
date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
product: products[(index + k * 2) % products.length],
qty,
amount: qty * price,
};
});
}
const rows: Row[] = customers.map((customer, i) => ({
id: `cust${i + 1}`,
customer,
city: cities[i],
orders: ordersOf(i).length,
total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const won = (value: number) => `${value.toLocaleString('ko-KR')}원`;
// 상세 패널은 어댑터가 만들어요. 값은 항상 textContent로 넣어서 HTML로 해석되지 않아요.
const panel = (): DetailRendererAdapter<Row> => {
let box: HTMLElement;
const fill = (row: Row): void => {
const index = rows.findIndex((r) => r.id === row.id);
const head = document.createElement('strong');
head.textContent = `${row.customer} 주문 내역 (${row.orders}건)`;
const table = document.createElement('table');
table.style.cssText =
'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
const line = (cells: string[], bold: boolean): HTMLTableRowElement => {
const tr = document.createElement('tr');
cells.forEach((text, c) => {
const td = document.createElement(bold ? 'th' : 'td');
td.textContent = text;
td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
tr.append(td);
});
return tr;
};
table.append(line(['주문일', '상품', '수량', '금액'], true));
for (const o of ordersOf(index))
table.append(line([o.date, o.product, String(o.qty), won(o.amount)], false));
// 좁은 화면에서는 표만 옆으로 스크롤돼요.
const scroller = document.createElement('div');
scroller.style.overflowX = 'auto';
scroller.append(table);
box.replaceChildren(head, scroller);
};
return {
mount(element, { row }) {
box = element;
element.style.padding = '8px 16px';
fill(row);
},
update({ row }) {
fill(row);
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객', width: 150 },
{ id: 'city', title: '지역', width: 90 },
{ id: 'orders', title: '주문 수', kind: 'number', width: 90, align: 'end' },
{
id: 'total',
title: '주문 합계',
kind: 'number',
width: 130,
align: 'end',
formatValue: (v) => won(Number(v)),
},
],
rows,
rowKey: 'id',
selection: 'single',
// 주문이 많은 고객일수록 패널을 더 높게. 처음에는 3번 고객(cust3)이 열려 있어요.
detail: {
renderer: panel,
height: (row) => 62 + row.orders * 25,
expanded: ['cust3'],
},
};
type Mode = 'free' | 'one' | 'follow';
let mode: Mode = 'free';
let busy = false; // 우리가 열고 닫는 동안 오는 이벤트는 무시해서 서로 부르지 않게 해요.
function openOnly(api: GridApi<Row>, key: string): void {
busy = true;
for (const row of api.getRows())
if (row.id !== key && api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
if (!api.isDetailExpanded(key)) api.expandDetail(key);
busy = false;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const nameOf = (key: string) => api.getRowByKey(key)?.customer ?? key;
const offs = [
api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${nameOf(String(rowKey))} 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`,
});
if (!busy && expanded && mode === 'one') openOnly(api, String(rowKey));
}),
api.on('selectionChanged', ({ selectedKeys }) => {
const key = selectedKeys[0];
if (mode === 'follow' && key !== undefined && !busy) openOnly(api, String(key));
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = value === 'one' || value === 'follow' ? value : 'free';
const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
if (mode !== 'free' && open.length > 1) openOnly(api, open[0].id);
},
closeAll: (api: GridApi<Row>) => {
for (const row of api.getRows()) if (api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
},
};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="Open mode" id="mode">
<option value="free" selected>Any number</option>
<option value="one">One at a time</option>
<option value="follow">Follow the selected row</option>
</select>
<button type="button" id="closeAll">Close all</button>
</div>
<div id="grid" style="height: 460px"></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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('closeAll').addEventListener('click', () => actions.closeAll(api));const customers = [
'Northwind Logistics',
'Greenfield Foods',
'Maple Trading',
'Autumn Retail',
'Summit Tech',
'Ocean Seafood',
'Springtime Pharma',
'Galaxy Electronics',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const products = [
'A4 Copy Paper',
'Label Stickers',
'Packing Tape',
'Bubble Wrap',
'Barcode Labeler',
'Stretch Film',
];
// Each customer has 2 to 5 orders. The order history for the detail panel is built from the customer index.
// In practice this is where you would request it from the server by customer number.
function ordersOf(index) {
return Array.from({ length: 2 + (index % 4) }, (_, k) => {
const qty = 1 + ((index * 3 + k * 5) % 9);
const price = 4 + ((index + k) % 6) * 2.5;
return {
date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
product: products[(index + k * 2) % products.length],
qty,
amount: qty * price,
};
});
}
const rows = customers.map((customer, i) => ({
id: `cust${i + 1}`,
customer,
city: cities[i],
orders: ordersOf(i).length,
total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const money = (value) => `$${value.toLocaleString('en-US')}`;
// The detail panel is built by an adapter. Values always go in via textContent, so they are never parsed as HTML.
const panel = () => {
let box;
const fill = (row) => {
const index = rows.findIndex((r) => r.id === row.id);
const head = document.createElement('strong');
head.textContent = `${row.customer} orders (${row.orders})`;
const table = document.createElement('table');
table.style.cssText =
'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
const line = (cells, bold) => {
const tr = document.createElement('tr');
cells.forEach((text, c) => {
const td = document.createElement(bold ? 'th' : 'td');
td.textContent = text;
td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
tr.append(td);
});
return tr;
};
table.append(line(['Order date', 'Product', 'Qty', 'Amount'], true));
for (const o of ordersOf(index))
table.append(line([o.date, o.product, String(o.qty), money(o.amount)], false));
// On a narrow screen only the table scrolls sideways.
const scroller = document.createElement('div');
scroller.style.overflowX = 'auto';
scroller.append(table);
box.replaceChildren(head, scroller);
};
return {
mount(element, { row }) {
box = element;
element.style.padding = '8px 16px';
fill(row);
},
update({ row }) {
fill(row);
},
destroy() { },
};
};
export const options = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{ id: 'city', title: 'City', width: 90 },
{ id: 'orders', title: 'Orders', kind: 'number', width: 90, align: 'end' },
{
id: 'total',
title: 'Order total',
kind: 'number',
width: 130,
align: 'end',
formatValue: (v) => money(Number(v)),
},
],
rows,
rowKey: 'id',
selection: 'single',
// The more orders a customer has, the taller the panel. At first customer 3 (cust3) is open.
detail: {
renderer: panel,
height: (row) => 62 + row.orders * 25,
expanded: ['cust3'],
},
};
let mode = 'free';
let busy = false; // Ignore events that arrive while we open and close panels, so they do not trigger each other.
function openOnly(api, key) {
busy = true;
for (const row of api.getRows())
if (row.id !== key && api.isDetailExpanded(row.id))
api.collapseDetail(row.id);
if (!api.isDetailExpanded(key))
api.expandDetail(key);
busy = false;
}
export function setup(api, log) {
const nameOf = (key) => api.getRowByKey(key)?.customer ?? key;
const offs = [
api.on('detailChanged', ({ rowKey, expanded }) => {
log(`${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`);
if (!busy && expanded && mode === 'one')
openOnly(api, String(rowKey));
}),
api.on('selectionChanged', ({ selectedKeys }) => {
const key = selectedKeys[0];
if (mode === 'follow' && key !== undefined && !busy)
openOnly(api, String(key));
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
mode: (api, value) => {
mode = value === 'one' || value === 'follow' ? value : 'free';
const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
if (mode !== 'free' && open.length > 1)
openOnly(api, open[0].id);
},
closeAll: (api) => {
for (const row of api.getRows())
if (api.isDetailExpanded(row.id))
api.collapseDetail(row.id);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Open a customer to see their orders</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Open mode" id="mode">
<option value="free" selected>Any number</option>
<option value="one">One at a time</option>
<option value="follow">Follow the selected row</option>
</select>
<button type="button" id="closeAll">Close all</button>
</div>
<div id="grid" style="height: 460px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const customers = [
'Northwind Logistics',
'Greenfield Foods',
'Maple Trading',
'Autumn Retail',
'Summit Tech',
'Ocean Seafood',
'Springtime Pharma',
'Galaxy Electronics',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const products = [
'A4 Copy Paper',
'Label Stickers',
'Packing Tape',
'Bubble Wrap',
'Barcode Labeler',
'Stretch Film',
];
// Each customer has 2 to 5 orders. The order history for the detail panel is built from the customer index.
// In practice this is where you would request it from the server by customer number.
function ordersOf(index) {
return Array.from({ length: 2 + (index % 4) }, (_, k) => {
const qty = 1 + ((index * 3 + k * 5) % 9);
const price = 4 + ((index + k) % 6) * 2.5;
return {
date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
product: products[(index + k * 2) % products.length],
qty,
amount: qty * price,
};
});
}
const rows = customers.map((customer, i) => ({
id: `cust${i + 1}`,
customer,
city: cities[i],
orders: ordersOf(i).length,
total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const money = (value) => `$${value.toLocaleString('en-US')}`;
// The detail panel is built by an adapter. Values always go in via textContent, so they are never parsed as HTML.
const panel = () => {
let box;
const fill = (row) => {
const index = rows.findIndex((r) => r.id === row.id);
const head = document.createElement('strong');
head.textContent = `${row.customer} orders (${row.orders})`;
const table = document.createElement('table');
table.style.cssText =
'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
const line = (cells, bold) => {
const tr = document.createElement('tr');
cells.forEach((text, c) => {
const td = document.createElement(bold ? 'th' : 'td');
td.textContent = text;
td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
tr.append(td);
});
return tr;
};
table.append(line(['Order date', 'Product', 'Qty', 'Amount'], true));
for (const o of ordersOf(index))
table.append(line([o.date, o.product, String(o.qty), money(o.amount)], false));
// On a narrow screen only the table scrolls sideways.
const scroller = document.createElement('div');
scroller.style.overflowX = 'auto';
scroller.append(table);
box.replaceChildren(head, scroller);
};
return {
mount(element, { row }) {
box = element;
element.style.padding = '8px 16px';
fill(row);
},
update({ row }) {
fill(row);
},
destroy() { },
};
};
const options = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{ id: 'city', title: 'City', width: 90 },
{ id: 'orders', title: 'Orders', kind: 'number', width: 90, align: 'end' },
{
id: 'total',
title: 'Order total',
kind: 'number',
width: 130,
align: 'end',
formatValue: (v) => money(Number(v)),
},
],
rows,
rowKey: 'id',
selection: 'single',
// The more orders a customer has, the taller the panel. At first customer 3 (cust3) is open.
detail: {
renderer: panel,
height: (row) => 62 + row.orders * 25,
expanded: ['cust3'],
},
};
let mode = 'free';
let busy = false; // Ignore events that arrive while we open and close panels, so they do not trigger each other.
function openOnly(api, key) {
busy = true;
for (const row of api.getRows())
if (row.id !== key && api.isDetailExpanded(row.id))
api.collapseDetail(row.id);
if (!api.isDetailExpanded(key))
api.expandDetail(key);
busy = false;
}
function setup(api, log) {
const nameOf = (key) => api.getRowByKey(key)?.customer ?? key;
const offs = [
api.on('detailChanged', ({ rowKey, expanded }) => {
log(`${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`);
if (!busy && expanded && mode === 'one')
openOnly(api, String(rowKey));
}),
api.on('selectionChanged', ({ selectedKeys }) => {
const key = selectedKeys[0];
if (mode === 'follow' && key !== undefined && !busy)
openOnly(api, String(key));
}),
];
return () => offs.forEach((off) => off());
}
const actions = {
mode: (api, value) => {
mode = value === 'one' || value === 'follow' ? value : 'free';
const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
if (mode !== 'free' && open.length > 1)
openOnly(api, open[0].id);
},
closeAll: (api) => {
for (const row of api.getRows())
if (api.isDetailExpanded(row.id))
api.collapseDetail(row.id);
},
};
options.ariaLabel = "Open a customer to see their orders";
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
document.getElementById('closeAll').addEventListener('click', () => actions.closeAll(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="Open mode"
disabled={!api}
onChange={(event) => api && actions.mode(api, event.target.value)}
>
<option value="free">Any number</option>
<option value="one">One at a time</option>
<option value="follow">Follow the selected row</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.closeAll(api)}
>Close all</button>
</div>
<Grid style={{ height: 460 }} ref={gridRef} options={options} />
</>
);
}import type { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
customer: string;
city: string;
orders: number;
total: number;
}
interface Order {
date: string;
product: string;
qty: number;
amount: number;
}
const customers = [
'Northwind Logistics',
'Greenfield Foods',
'Maple Trading',
'Autumn Retail',
'Summit Tech',
'Ocean Seafood',
'Springtime Pharma',
'Galaxy Electronics',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const products = [
'A4 Copy Paper',
'Label Stickers',
'Packing Tape',
'Bubble Wrap',
'Barcode Labeler',
'Stretch Film',
];
// Each customer has 2 to 5 orders. The order history for the detail panel is built from the customer index.
// In practice this is where you would request it from the server by customer number.
function ordersOf(index: number): Order[] {
return Array.from({ length: 2 + (index % 4) }, (_, k) => {
const qty = 1 + ((index * 3 + k * 5) % 9);
const price = 4 + ((index + k) % 6) * 2.5;
return {
date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
product: products[(index + k * 2) % products.length],
qty,
amount: qty * price,
};
});
}
const rows: Row[] = customers.map((customer, i) => ({
id: `cust${i + 1}`,
customer,
city: cities[i],
orders: ordersOf(i).length,
total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const money = (value: number) => `$${value.toLocaleString('en-US')}`;
// The detail panel is built by an adapter. Values always go in via textContent, so they are never parsed as HTML.
const panel = (): DetailRendererAdapter<Row> => {
let box: HTMLElement;
const fill = (row: Row): void => {
const index = rows.findIndex((r) => r.id === row.id);
const head = document.createElement('strong');
head.textContent = `${row.customer} orders (${row.orders})`;
const table = document.createElement('table');
table.style.cssText =
'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
const line = (cells: string[], bold: boolean): HTMLTableRowElement => {
const tr = document.createElement('tr');
cells.forEach((text, c) => {
const td = document.createElement(bold ? 'th' : 'td');
td.textContent = text;
td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
tr.append(td);
});
return tr;
};
table.append(line(['Order date', 'Product', 'Qty', 'Amount'], true));
for (const o of ordersOf(index))
table.append(line([o.date, o.product, String(o.qty), money(o.amount)], false));
// On a narrow screen only the table scrolls sideways.
const scroller = document.createElement('div');
scroller.style.overflowX = 'auto';
scroller.append(table);
box.replaceChildren(head, scroller);
};
return {
mount(element, { row }) {
box = element;
element.style.padding = '8px 16px';
fill(row);
},
update({ row }) {
fill(row);
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{ id: 'city', title: 'City', width: 90 },
{ id: 'orders', title: 'Orders', kind: 'number', width: 90, align: 'end' },
{
id: 'total',
title: 'Order total',
kind: 'number',
width: 130,
align: 'end',
formatValue: (v) => money(Number(v)),
},
],
rows,
rowKey: 'id',
selection: 'single',
// The more orders a customer has, the taller the panel. At first customer 3 (cust3) is open.
detail: {
renderer: panel,
height: (row) => 62 + row.orders * 25,
expanded: ['cust3'],
},
};
type Mode = 'free' | 'one' | 'follow';
let mode: Mode = 'free';
let busy = false; // Ignore events that arrive while we open and close panels, so they do not trigger each other.
function openOnly(api: GridApi<Row>, key: string): void {
busy = true;
for (const row of api.getRows())
if (row.id !== key && api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
if (!api.isDetailExpanded(key)) api.expandDetail(key);
busy = false;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const nameOf = (key: string) => api.getRowByKey(key)?.customer ?? key;
const offs = [
api.on('detailChanged', ({ rowKey, expanded }) => {
log(`${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`);
if (!busy && expanded && mode === 'one') openOnly(api, String(rowKey));
}),
api.on('selectionChanged', ({ selectedKeys }) => {
const key = selectedKeys[0];
if (mode === 'follow' && key !== undefined && !busy) openOnly(api, String(key));
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = value === 'one' || value === 'follow' ? value : 'free';
const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
if (mode !== 'free' && open.length > 1) openOnly(api, open[0].id);
},
closeAll: (api: GridApi<Row>) => {
for (const row of api.getRows()) if (api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
},
};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="Open mode"
:disabled="!api"
@change="api && actions.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="free" selected>Any number</option>
<option value="one">One at a time</option>
<option value="follow">Follow the selected row</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.closeAll(api)"
>Close all</button>
</div>
<Grid style="height: 460px" :options="options" @ready="onReady" />
</template>import type { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
customer: string;
city: string;
orders: number;
total: number;
}
interface Order {
date: string;
product: string;
qty: number;
amount: number;
}
const customers = [
'Northwind Logistics',
'Greenfield Foods',
'Maple Trading',
'Autumn Retail',
'Summit Tech',
'Ocean Seafood',
'Springtime Pharma',
'Galaxy Electronics',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const products = [
'A4 Copy Paper',
'Label Stickers',
'Packing Tape',
'Bubble Wrap',
'Barcode Labeler',
'Stretch Film',
];
// Each customer has 2 to 5 orders. The order history for the detail panel is built from the customer index.
// In practice this is where you would request it from the server by customer number.
function ordersOf(index: number): Order[] {
return Array.from({ length: 2 + (index % 4) }, (_, k) => {
const qty = 1 + ((index * 3 + k * 5) % 9);
const price = 4 + ((index + k) % 6) * 2.5;
return {
date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
product: products[(index + k * 2) % products.length],
qty,
amount: qty * price,
};
});
}
const rows: Row[] = customers.map((customer, i) => ({
id: `cust${i + 1}`,
customer,
city: cities[i],
orders: ordersOf(i).length,
total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const money = (value: number) => `$${value.toLocaleString('en-US')}`;
// The detail panel is built by an adapter. Values always go in via textContent, so they are never parsed as HTML.
const panel = (): DetailRendererAdapter<Row> => {
let box: HTMLElement;
const fill = (row: Row): void => {
const index = rows.findIndex((r) => r.id === row.id);
const head = document.createElement('strong');
head.textContent = `${row.customer} orders (${row.orders})`;
const table = document.createElement('table');
table.style.cssText =
'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
const line = (cells: string[], bold: boolean): HTMLTableRowElement => {
const tr = document.createElement('tr');
cells.forEach((text, c) => {
const td = document.createElement(bold ? 'th' : 'td');
td.textContent = text;
td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
tr.append(td);
});
return tr;
};
table.append(line(['Order date', 'Product', 'Qty', 'Amount'], true));
for (const o of ordersOf(index))
table.append(line([o.date, o.product, String(o.qty), money(o.amount)], false));
// On a narrow screen only the table scrolls sideways.
const scroller = document.createElement('div');
scroller.style.overflowX = 'auto';
scroller.append(table);
box.replaceChildren(head, scroller);
};
return {
mount(element, { row }) {
box = element;
element.style.padding = '8px 16px';
fill(row);
},
update({ row }) {
fill(row);
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{ id: 'city', title: 'City', width: 90 },
{ id: 'orders', title: 'Orders', kind: 'number', width: 90, align: 'end' },
{
id: 'total',
title: 'Order total',
kind: 'number',
width: 130,
align: 'end',
formatValue: (v) => money(Number(v)),
},
],
rows,
rowKey: 'id',
selection: 'single',
// The more orders a customer has, the taller the panel. At first customer 3 (cust3) is open.
detail: {
renderer: panel,
height: (row) => 62 + row.orders * 25,
expanded: ['cust3'],
},
};
type Mode = 'free' | 'one' | 'follow';
let mode: Mode = 'free';
let busy = false; // Ignore events that arrive while we open and close panels, so they do not trigger each other.
function openOnly(api: GridApi<Row>, key: string): void {
busy = true;
for (const row of api.getRows())
if (row.id !== key && api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
if (!api.isDetailExpanded(key)) api.expandDetail(key);
busy = false;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const nameOf = (key: string) => api.getRowByKey(key)?.customer ?? key;
const offs = [
api.on('detailChanged', ({ rowKey, expanded }) => {
log(`${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`);
if (!busy && expanded && mode === 'one') openOnly(api, String(rowKey));
}),
api.on('selectionChanged', ({ selectedKeys }) => {
const key = selectedKeys[0];
if (mode === 'follow' && key !== undefined && !busy) openOnly(api, String(key));
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = value === 'one' || value === 'follow' ? value : 'free';
const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
if (mode !== 'free' && open.length > 1) openOnly(api, open[0].id);
},
closeAll: (api: GridApi<Row>) => {
for (const row of api.getRows()) if (api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
},
};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="Open mode"
[disabled]="!api"
(change)="api && actions.mode(api, $any($event.target).value)"
>
<option value="free" selected>Any number</option>
<option value="one">One at a time</option>
<option value="follow">Follow the selected row</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.closeAll(api)"
>Close all</button>
</div>
<mx-grid style="height: 460px" [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 { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
customer: string;
city: string;
orders: number;
total: number;
}
interface Order {
date: string;
product: string;
qty: number;
amount: number;
}
const customers = [
'Northwind Logistics',
'Greenfield Foods',
'Maple Trading',
'Autumn Retail',
'Summit Tech',
'Ocean Seafood',
'Springtime Pharma',
'Galaxy Electronics',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const products = [
'A4 Copy Paper',
'Label Stickers',
'Packing Tape',
'Bubble Wrap',
'Barcode Labeler',
'Stretch Film',
];
// Each customer has 2 to 5 orders. The order history for the detail panel is built from the customer index.
// In practice this is where you would request it from the server by customer number.
function ordersOf(index: number): Order[] {
return Array.from({ length: 2 + (index % 4) }, (_, k) => {
const qty = 1 + ((index * 3 + k * 5) % 9);
const price = 4 + ((index + k) % 6) * 2.5;
return {
date: `2026-10-${String(3 + k * 6 + (index % 5)).padStart(2, '0')}`,
product: products[(index + k * 2) % products.length],
qty,
amount: qty * price,
};
});
}
const rows: Row[] = customers.map((customer, i) => ({
id: `cust${i + 1}`,
customer,
city: cities[i],
orders: ordersOf(i).length,
total: ordersOf(i).reduce((sum, o) => sum + o.amount, 0),
}));
const money = (value: number) => `$${value.toLocaleString('en-US')}`;
// The detail panel is built by an adapter. Values always go in via textContent, so they are never parsed as HTML.
const panel = (): DetailRendererAdapter<Row> => {
let box: HTMLElement;
const fill = (row: Row): void => {
const index = rows.findIndex((r) => r.id === row.id);
const head = document.createElement('strong');
head.textContent = `${row.customer} orders (${row.orders})`;
const table = document.createElement('table');
table.style.cssText =
'border-collapse: collapse; margin-top: 6px; width: 100%; min-width: 380px; max-width: 520px;';
const line = (cells: string[], bold: boolean): HTMLTableRowElement => {
const tr = document.createElement('tr');
cells.forEach((text, c) => {
const td = document.createElement(bold ? 'th' : 'td');
td.textContent = text;
td.style.cssText = `padding: 2px 8px; border-bottom: 1px solid var(--mxg-border); text-align: ${c >= 2 ? 'right' : 'left'}; font-weight: ${bold ? 600 : 400};`;
tr.append(td);
});
return tr;
};
table.append(line(['Order date', 'Product', 'Qty', 'Amount'], true));
for (const o of ordersOf(index))
table.append(line([o.date, o.product, String(o.qty), money(o.amount)], false));
// On a narrow screen only the table scrolls sideways.
const scroller = document.createElement('div');
scroller.style.overflowX = 'auto';
scroller.append(table);
box.replaceChildren(head, scroller);
};
return {
mount(element, { row }) {
box = element;
element.style.padding = '8px 16px';
fill(row);
},
update({ row }) {
fill(row);
},
destroy() {},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{ id: 'city', title: 'City', width: 90 },
{ id: 'orders', title: 'Orders', kind: 'number', width: 90, align: 'end' },
{
id: 'total',
title: 'Order total',
kind: 'number',
width: 130,
align: 'end',
formatValue: (v) => money(Number(v)),
},
],
rows,
rowKey: 'id',
selection: 'single',
// The more orders a customer has, the taller the panel. At first customer 3 (cust3) is open.
detail: {
renderer: panel,
height: (row) => 62 + row.orders * 25,
expanded: ['cust3'],
},
};
type Mode = 'free' | 'one' | 'follow';
let mode: Mode = 'free';
let busy = false; // Ignore events that arrive while we open and close panels, so they do not trigger each other.
function openOnly(api: GridApi<Row>, key: string): void {
busy = true;
for (const row of api.getRows())
if (row.id !== key && api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
if (!api.isDetailExpanded(key)) api.expandDetail(key);
busy = false;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const nameOf = (key: string) => api.getRowByKey(key)?.customer ?? key;
const offs = [
api.on('detailChanged', ({ rowKey, expanded }) => {
log(`${nameOf(String(rowKey))} details ${expanded ? 'opened' : 'closed'}`);
if (!busy && expanded && mode === 'one') openOnly(api, String(rowKey));
}),
api.on('selectionChanged', ({ selectedKeys }) => {
const key = selectedKeys[0];
if (mode === 'follow' && key !== undefined && !busy) openOnly(api, String(key));
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
mode: (api: GridApi<Row>, value?: string) => {
mode = value === 'one' || value === 'follow' ? value : 'free';
const open = api.getRows().filter((r) => api.isDetailExpanded(r.id));
if (mode !== 'free' && open.length > 1) openOnly(api, open[0].id);
},
closeAll: (api: GridApi<Row>) => {
for (const row of api.getRows()) if (api.isDetailExpanded(row.id)) api.collapseDetail(row.id);
},
};