접었다 펴도 상세 패널 입력 그대로 두기Keep detail panels alive when collapsed
주문 줄을 보여 주는 상세 패널을 접어도 부수지 않고 보관해요. 다시 펼치면 안쪽 그리드에 고친 값이 그대로 있어요. 보관은 최대 2개까지예요.Collapsing a detail panel with order lines keeps it instead of destroying it. Expand it again and the edited values are still in the inner grid. At most 2 panels are kept.
코드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="keep">
<option value="on" selected>켜기</option>
<option value="off">끄기</option>
</select>
<button type="button" id="showState">상태 보기</button>
<button type="button" id="destroyFirst">펼친 패널 부수기</button>
</div>
<div id="grid" style="height: 480px"></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('keep').addEventListener('change', (event) => actions.keep(api, event.target.value));
document.getElementById('showState').addEventListener('click', () => actions.showState(api));
document.getElementById('destroyFirst').addEventListener('click', () => actions.destroyFirst(api));const rows = [
{ id: 1, customer: '김하늘', status: '준비' },
{ id: 2, customer: '이도윤', status: '배송' },
{ id: 3, customer: '박서연', status: '완료' },
{ id: 4, customer: '최지우', status: '준비' },
];
const lines = [
{ id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
{ id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
{ id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
{ id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
{ id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
{ id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
{ id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
{ id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
{ id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
{ id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
// 렌더러 함수는 한 번만 만들어서 옵션을 다시 만들어도 같은 것을 써요.
const renderer = () => {
let grid = null;
let off;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: '상품', width: 140 },
{ id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 110,
editable: true,
formatValue: won,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} 주문 줄`,
});
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// 보관 옵션만 바꿔서 setOptions로 다시 넘겨요.
const detailOf = (keepAlive) => ({
keepAlive,
maxKeepAlive: 2,
renderer,
height: 190,
});
export const options = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
detail: { ...detailOf(true), expanded: [1] },
};
let logger = () => { };
export function setup(api, log) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
});
});
return () => off();
}
export const actions = {
keep: (api, value) => {
api.setOptions({ detail: detailOf(value !== 'off') });
},
showState: (api) => {
for (const row of api.getRows()) {
const s = api.getDetailState(row.id);
logger({
ko: `${row.id}번: 펼침 ${s.expanded ? '예' : '아니오'}, 만들어짐 ${s.mounted ? '예' : '아니오'}, 저장 안 된 편집 ${s.dirty ? '있음' : '없음'}`,
en: `Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`,
});
}
},
destroyFirst: (api) => {
const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
api.destroyDetail(row.id);
logger({ ko: `${row.id}번 패널을 부쉈어요`, en: `Destroyed the panel of order ${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="keep">
<option value="on" selected>켜기</option>
<option value="off">끄기</option>
</select>
<button type="button" id="showState">상태 보기</button>
<button type="button" id="destroyFirst">펼친 패널 부수기</button>
</div>
<div id="grid" style="height: 480px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, customer: '김하늘', status: '준비' },
{ id: 2, customer: '이도윤', status: '배송' },
{ id: 3, customer: '박서연', status: '완료' },
{ id: 4, customer: '최지우', status: '준비' },
];
const lines = [
{ id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
{ id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
{ id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
{ id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
{ id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
{ id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
{ id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
{ id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
{ id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
{ id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
// 렌더러 함수는 한 번만 만들어서 옵션을 다시 만들어도 같은 것을 써요.
const renderer = () => {
let grid = null;
let off;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: '상품', width: 140 },
{ id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 110,
editable: true,
formatValue: won,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} 주문 줄`,
});
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// 보관 옵션만 바꿔서 setOptions로 다시 넘겨요.
const detailOf = (keepAlive) => ({
keepAlive,
maxKeepAlive: 2,
renderer,
height: 190,
});
const options = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
detail: { ...detailOf(true), expanded: [1] },
};
let logger = () => { };
function setup(api, log) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
});
});
return () => off();
}
const actions = {
keep: (api, value) => {
api.setOptions({ detail: detailOf(value !== 'off') });
},
showState: (api) => {
for (const row of api.getRows()) {
const s = api.getDetailState(row.id);
logger({
ko: `${row.id}번: 펼침 ${s.expanded ? '예' : '아니오'}, 만들어짐 ${s.mounted ? '예' : '아니오'}, 저장 안 된 편집 ${s.dirty ? '있음' : '없음'}`,
en: `Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`,
});
}
},
destroyFirst: (api) => {
const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
api.destroyDetail(row.id);
logger({ ko: `${row.id}번 패널을 부쉈어요`, en: `Destroyed the panel of order ${row.id}` });
},
};
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('keep').addEventListener('change', (event) => actions.keep(api, event.target.value));
document.getElementById('showState').addEventListener('click', () => actions.showState(api));
document.getElementById('destroyFirst').addEventListener('click', () => actions.destroyFirst(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.keep(api, event.target.value)}
>
<option value="on">켜기</option>
<option value="off">끄기</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.showState(api)}
>상태 보기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.destroyFirst(api)}
>펼친 패널 부수기</button>
</div>
<Grid style={{ height: 480 }} ref={gridRef} options={options} />
</>
);
}import type { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: '김하늘', status: '준비' },
{ id: 2, customer: '이도윤', status: '배송' },
{ id: 3, customer: '박서연', status: '완료' },
{ id: 4, customer: '최지우', status: '준비' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
{ id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
{ id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
{ id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
{ id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
{ id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
{ id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
{ id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
{ id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
{ id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v: unknown) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
// 렌더러 함수는 한 번만 만들어서 옵션을 다시 만들어도 같은 것을 써요.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: '상품', width: 140 },
{ id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 110,
editable: true,
formatValue: won,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} 주문 줄`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// 보관 옵션만 바꿔서 setOptions로 다시 넘겨요.
const detailOf = (keepAlive: boolean): NonNullable<GridOptions<Row>['detail']> => ({
keepAlive,
maxKeepAlive: 2,
renderer,
height: 190,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
detail: { ...detailOf(true), expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
});
});
return () => off();
}
export const actions = {
keep: (api: GridApi<Row>, value?: string) => {
api.setOptions({ detail: detailOf(value !== 'off') });
},
showState: (api: GridApi<Row>) => {
for (const row of api.getRows()) {
const s = api.getDetailState(row.id);
logger({
ko: `${row.id}번: 펼침 ${s.expanded ? '예' : '아니오'}, 만들어짐 ${s.mounted ? '예' : '아니오'}, 저장 안 된 편집 ${s.dirty ? '있음' : '없음'}`,
en: `Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`,
});
}
},
destroyFirst: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
api.destroyDetail(row.id);
logger({ ko: `${row.id}번 패널을 부쉈어요`, en: `Destroyed the panel of order ${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.keep(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>켜기</option>
<option value="off">끄기</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.showState(api)"
>상태 보기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.destroyFirst(api)"
>펼친 패널 부수기</button>
</div>
<Grid style="height: 480px" :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: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: '김하늘', status: '준비' },
{ id: 2, customer: '이도윤', status: '배송' },
{ id: 3, customer: '박서연', status: '완료' },
{ id: 4, customer: '최지우', status: '준비' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
{ id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
{ id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
{ id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
{ id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
{ id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
{ id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
{ id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
{ id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
{ id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v: unknown) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
// 렌더러 함수는 한 번만 만들어서 옵션을 다시 만들어도 같은 것을 써요.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: '상품', width: 140 },
{ id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 110,
editable: true,
formatValue: won,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} 주문 줄`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// 보관 옵션만 바꿔서 setOptions로 다시 넘겨요.
const detailOf = (keepAlive: boolean): NonNullable<GridOptions<Row>['detail']> => ({
keepAlive,
maxKeepAlive: 2,
renderer,
height: 190,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
detail: { ...detailOf(true), expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
});
});
return () => off();
}
export const actions = {
keep: (api: GridApi<Row>, value?: string) => {
api.setOptions({ detail: detailOf(value !== 'off') });
},
showState: (api: GridApi<Row>) => {
for (const row of api.getRows()) {
const s = api.getDetailState(row.id);
logger({
ko: `${row.id}번: 펼침 ${s.expanded ? '예' : '아니오'}, 만들어짐 ${s.mounted ? '예' : '아니오'}, 저장 안 된 편집 ${s.dirty ? '있음' : '없음'}`,
en: `Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`,
});
}
},
destroyFirst: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
api.destroyDetail(row.id);
logger({ ko: `${row.id}번 패널을 부쉈어요`, en: `Destroyed the panel of order ${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.keep(api, $any($event.target).value)"
>
<option value="on" selected>켜기</option>
<option value="off">끄기</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.showState(api)"
>상태 보기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.destroyFirst(api)"
>펼친 패널 부수기</button>
</div>
<mx-grid style="height: 480px" [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: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: '김하늘', status: '준비' },
{ id: 2, customer: '이도윤', status: '배송' },
{ id: 3, customer: '박서연', status: '완료' },
{ id: 4, customer: '최지우', status: '준비' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
{ id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
{ id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
{ id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
{ id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
{ id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
{ id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
{ id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
{ id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
{ id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v: unknown) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
// 렌더러 함수는 한 번만 만들어서 옵션을 다시 만들어도 같은 것을 써요.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: '상품', width: 140 },
{ id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 110,
editable: true,
formatValue: won,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} 주문 줄`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// 보관 옵션만 바꿔서 setOptions로 다시 넘겨요.
const detailOf = (keepAlive: boolean): NonNullable<GridOptions<Row>['detail']> => ({
keepAlive,
maxKeepAlive: 2,
renderer,
height: 190,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '주문 번호', kind: 'number', width: 100 },
{ id: 'customer', title: '고객', width: 130 },
{ id: 'status', title: '상태', width: 90 },
],
rows,
rowKey: 'id',
detail: { ...detailOf(true), expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log({
ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
});
});
return () => off();
}
export const actions = {
keep: (api: GridApi<Row>, value?: string) => {
api.setOptions({ detail: detailOf(value !== 'off') });
},
showState: (api: GridApi<Row>) => {
for (const row of api.getRows()) {
const s = api.getDetailState(row.id);
logger({
ko: `${row.id}번: 펼침 ${s.expanded ? '예' : '아니오'}, 만들어짐 ${s.mounted ? '예' : '아니오'}, 저장 안 된 편집 ${s.dirty ? '있음' : '없음'}`,
en: `Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`,
});
}
},
destroyFirst: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
api.destroyDetail(row.id);
logger({ ko: `${row.id}번 패널을 부쉈어요`, en: `Destroyed the panel of order ${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="Keep" id="keep">
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<button type="button" id="showState">Show state</button>
<button type="button" id="destroyFirst">Destroy open panel</button>
</div>
<div id="grid" style="height: 480px"></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('keep').addEventListener('change', (event) => actions.keep(api, event.target.value));
document.getElementById('showState').addEventListener('click', () => actions.showState(api));
document.getElementById('destroyFirst').addEventListener('click', () => actions.destroyFirst(api));const rows = [
{ id: 1, customer: 'Liam Carter', status: 'Pending' },
{ id: 2, customer: 'Emma Stone', status: 'Shipping' },
{ id: 3, customer: 'Noah Reed', status: 'Done' },
{ id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines = [
{ id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
{ id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
{ id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
{ id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
{ id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
{ id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
{ id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
{ id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
{ id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
{ id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
// The renderer function is created once, so rebuilding the options reuses the same one.
const renderer = () => {
let grid = null;
let off;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: 'Item', width: 140 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: 'Unit price',
kind: 'number',
width: 110,
editable: true,
formatValue: dollars,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} order lines`,
});
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// Only the keep-alive flag changes; the object is passed again through setOptions.
const detailOf = (keepAlive) => ({
keepAlive,
maxKeepAlive: 2,
renderer,
height: 190,
});
export const options = {
columns: [
{ id: 'id', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'customer', title: 'Customer', width: 130 },
{ id: 'status', title: 'Status', width: 90 },
],
rows,
rowKey: 'id',
detail: { ...detailOf(true), expanded: [1] },
};
let logger = () => { };
export function setup(api, log) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
});
return () => off();
}
export const actions = {
keep: (api, value) => {
api.setOptions({ detail: detailOf(value !== 'off') });
},
showState: (api) => {
for (const row of api.getRows()) {
const s = api.getDetailState(row.id);
logger(`Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`);
}
},
destroyFirst: (api) => {
const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
api.destroyDetail(row.id);
logger(`Destroyed the panel of order ${row.id}`);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Keep detail panels alive when collapsed</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Keep" id="keep">
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<button type="button" id="showState">Show state</button>
<button type="button" id="destroyFirst">Destroy open panel</button>
</div>
<div id="grid" style="height: 480px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, customer: 'Liam Carter', status: 'Pending' },
{ id: 2, customer: 'Emma Stone', status: 'Shipping' },
{ id: 3, customer: 'Noah Reed', status: 'Done' },
{ id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines = [
{ id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
{ id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
{ id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
{ id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
{ id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
{ id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
{ id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
{ id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
{ id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
{ id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
// The renderer function is created once, so rebuilding the options reuses the same one.
const renderer = () => {
let grid = null;
let off;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: 'Item', width: 140 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: 'Unit price',
kind: 'number',
width: 110,
editable: true,
formatValue: dollars,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} order lines`,
});
off = attachGrid?.(grid);
},
update() { },
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// Only the keep-alive flag changes; the object is passed again through setOptions.
const detailOf = (keepAlive) => ({
keepAlive,
maxKeepAlive: 2,
renderer,
height: 190,
});
const options = {
columns: [
{ id: 'id', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'customer', title: 'Customer', width: 130 },
{ id: 'status', title: 'Status', width: 90 },
],
rows,
rowKey: 'id',
detail: { ...detailOf(true), expanded: [1] },
};
let logger = () => { };
function setup(api, log) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
});
return () => off();
}
const actions = {
keep: (api, value) => {
api.setOptions({ detail: detailOf(value !== 'off') });
},
showState: (api) => {
for (const row of api.getRows()) {
const s = api.getDetailState(row.id);
logger(`Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`);
}
},
destroyFirst: (api) => {
const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
api.destroyDetail(row.id);
logger(`Destroyed the panel of order ${row.id}`);
},
};
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('keep').addEventListener('change', (event) => actions.keep(api, event.target.value));
document.getElementById('showState').addEventListener('click', () => actions.showState(api));
document.getElementById('destroyFirst').addEventListener('click', () => actions.destroyFirst(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="Keep"
disabled={!api}
onChange={(event) => api && actions.keep(api, event.target.value)}
>
<option value="on">On</option>
<option value="off">Off</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.showState(api)}
>Show state</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.destroyFirst(api)}
>Destroy open panel</button>
</div>
<Grid style={{ height: 480 }} ref={gridRef} options={options} />
</>
);
}import type { DetailRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: 'Liam Carter', status: 'Pending' },
{ id: 2, customer: 'Emma Stone', status: 'Shipping' },
{ id: 3, customer: 'Noah Reed', status: 'Done' },
{ id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
{ id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
{ id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
{ id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
{ id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
{ id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
{ id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
{ id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
{ id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
{ id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v: unknown) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
// The renderer function is created once, so rebuilding the options reuses the same one.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: 'Item', width: 140 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: 'Unit price',
kind: 'number',
width: 110,
editable: true,
formatValue: dollars,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} order lines`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// Only the keep-alive flag changes; the object is passed again through setOptions.
const detailOf = (keepAlive: boolean): NonNullable<GridOptions<Row>['detail']> => ({
keepAlive,
maxKeepAlive: 2,
renderer,
height: 190,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'customer', title: 'Customer', width: 130 },
{ id: 'status', title: 'Status', width: 90 },
],
rows,
rowKey: 'id',
detail: { ...detailOf(true), expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
});
return () => off();
}
export const actions = {
keep: (api: GridApi<Row>, value?: string) => {
api.setOptions({ detail: detailOf(value !== 'off') });
},
showState: (api: GridApi<Row>) => {
for (const row of api.getRows()) {
const s = api.getDetailState(row.id);
logger(`Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`);
}
},
destroyFirst: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
api.destroyDetail(row.id);
logger(`Destroyed the panel of order ${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="Keep"
:disabled="!api"
@change="api && actions.keep(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.showState(api)"
>Show state</button>
<button
type="button"
:disabled="!api"
@click="api && actions.destroyFirst(api)"
>Destroy open panel</button>
</div>
<Grid style="height: 480px" :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: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: 'Liam Carter', status: 'Pending' },
{ id: 2, customer: 'Emma Stone', status: 'Shipping' },
{ id: 3, customer: 'Noah Reed', status: 'Done' },
{ id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
{ id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
{ id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
{ id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
{ id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
{ id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
{ id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
{ id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
{ id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
{ id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v: unknown) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
// The renderer function is created once, so rebuilding the options reuses the same one.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: 'Item', width: 140 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: 'Unit price',
kind: 'number',
width: 110,
editable: true,
formatValue: dollars,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} order lines`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// Only the keep-alive flag changes; the object is passed again through setOptions.
const detailOf = (keepAlive: boolean): NonNullable<GridOptions<Row>['detail']> => ({
keepAlive,
maxKeepAlive: 2,
renderer,
height: 190,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'customer', title: 'Customer', width: 130 },
{ id: 'status', title: 'Status', width: 90 },
],
rows,
rowKey: 'id',
detail: { ...detailOf(true), expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
});
return () => off();
}
export const actions = {
keep: (api: GridApi<Row>, value?: string) => {
api.setOptions({ detail: detailOf(value !== 'off') });
},
showState: (api: GridApi<Row>) => {
for (const row of api.getRows()) {
const s = api.getDetailState(row.id);
logger(`Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`);
}
},
destroyFirst: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
api.destroyDetail(row.id);
logger(`Destroyed the panel of order ${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="Keep"
[disabled]="!api"
(change)="api && actions.keep(api, $any($event.target).value)"
>
<option value="on" selected>On</option>
<option value="off">Off</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.showState(api)"
>Show state</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.destroyFirst(api)"
>Destroy open panel</button>
</div>
<mx-grid style="height: 480px" [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: number;
customer: string;
status: string;
}
export interface Line {
id: number;
orderId: number;
item: string;
qty: number;
price: number;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Line>): GridApi<Line>;
};
const rows: Row[] = [
{ id: 1, customer: 'Liam Carter', status: 'Pending' },
{ id: 2, customer: 'Emma Stone', status: 'Shipping' },
{ id: 3, customer: 'Noah Reed', status: 'Done' },
{ id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines: Line[] = [
{ id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
{ id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
{ id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
{ id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
{ id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
{ id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
{ id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
{ id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
{ id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
{ id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v: unknown) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
// The renderer function is created once, so rebuilding the options reuses the same one.
const renderer = (): DetailRendererAdapter<Row> => {
let grid: GridApi<Line> | null = null;
let off: (() => void) | undefined;
return {
mount(element, { row, attachGrid }) {
element.style.padding = '8px 16px';
const host = document.createElement('div');
host.style.height = '130px';
element.replaceChildren(host);
grid = MaxGrid.createGrid(host, {
columns: [
{ id: 'item', title: 'Item', width: 140 },
{ id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
{
id: 'price',
title: 'Unit price',
kind: 'number',
width: 110,
editable: true,
formatValue: dollars,
},
],
rows: lines.filter((l) => l.orderId === row.id),
rowKey: 'id',
saveMode: 'batch',
ariaLabel: `${row.customer} order lines`,
});
off = attachGrid?.(grid as unknown as GridApi<never>);
},
update() {},
destroy() {
off?.();
grid?.destroy();
grid = null;
},
};
};
// Only the keep-alive flag changes; the object is passed again through setOptions.
const detailOf = (keepAlive: boolean): NonNullable<GridOptions<Row>['detail']> => ({
keepAlive,
maxKeepAlive: 2,
renderer,
height: 190,
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'Order ID', kind: 'number', width: 100 },
{ id: 'customer', title: 'Customer', width: 130 },
{ id: 'status', title: 'Status', width: 90 },
],
rows,
rowKey: 'id',
detail: { ...detailOf(true), expanded: [1] },
};
let logger: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
logger = log;
const off = api.on('detailChanged', ({ rowKey, expanded }) => {
log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
});
return () => off();
}
export const actions = {
keep: (api: GridApi<Row>, value?: string) => {
api.setOptions({ detail: detailOf(value !== 'off') });
},
showState: (api: GridApi<Row>) => {
for (const row of api.getRows()) {
const s = api.getDetailState(row.id);
logger(`Order ${row.id}: expanded ${s.expanded}, mounted ${s.mounted}, dirty ${s.dirty}`);
}
},
destroyFirst: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => api.isDetailExpanded(r.id)) ?? api.getRows()[0];
api.destroyDetail(row.id);
logger(`Destroyed the panel of order ${row.id}`);
},
};