머리글·본문·합계 그리드 셋 맞추기Align a header, a body and a totals grid
alignGrids는 그리드를 2~4개까지 이어요. 머리글만 있는 그리드, 본문 그리드, 합계 그리드를 쌓아 두고 맨 위 머리글에서 컬럼 폭이나 순서를 바꾸면 셋이 함께 바뀌고 스크롤도 같이 움직여요.alignGrids links two to four grids. Stack a header-only grid, a body grid and a totals grid and a width or order change in the top header applies to all three, and the scroll moves together.
코드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">
<button type="button" id="widen">항목 넓히기</button>
<button type="button" id="move">차이 맨 앞으로</button>
<button type="button" id="plan">계획 숨기기/보이기</button>
</div>
<div id="grid" style="height: 240px"></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('widen').addEventListener('click', () => actions.widen(api));
document.getElementById('move').addEventListener('click', () => actions.move(api));
document.getElementById('plan').addEventListener('click', () => actions.plan(api));// 머리글만 있는 그리드, 본문 그리드, 합계 그리드를 위아래로 쌓고 컬럼 폭·순서·숨김·스크롤을 서로 맞춰요.
const ITEMS = [
'노트북',
'태블릿',
'스마트워치',
'이어폰',
'보조배터리',
'스피커',
'키보드',
'모니터',
];
const COLUMNS = [
{ id: 'item', title: '항목', width: 150 },
{
id: 'q1',
title: '1분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q2',
title: '2분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q3',
title: '3분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q4',
title: '4분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'plan',
title: '계획',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'gap',
title: '차이',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
];
const body = ITEMS.map((item, i) => {
const q = [1, 2, 3, 4].map((k) => 40 + ((i * 17 + k * 29) % 60));
const plan = 190 + i * 5;
return {
id: i + 1,
item,
q1: q[0] ?? 0,
q2: q[1] ?? 0,
q3: q[2] ?? 0,
q4: q[3] ?? 0,
plan,
gap: q.reduce((a, b) => a + b, 0) - plan,
};
});
const sum = (key) => body.reduce((total, row) => total + (row[key] ?? 0), 0);
// 갤러리 틀이 만드는 그리드가 본문 그리드예요(머리글 없음). 머리글만 있는 그리드를 위에, 합계 그리드를 아래에 놓아요.
export const options = {
columns: COLUMNS,
rows: body,
rowKey: 'id',
showHeader: false,
};
let grids = [];
let hosts = [];
let link = null;
export function setup(api, log) {
const gridEl = document.getElementById('grid');
const place = (where, opts) => {
const host = document.createElement('div');
host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
if (gridEl !== null)
gridEl[where](host);
else
document.body.append(host);
hosts.push(host);
return MaxGrid.createGrid(host, opts);
};
const header = place('before', {
columns: COLUMNS,
rows: [],
rowKey: 'id',
overlays: false,
autoGridHeight: true,
ariaLabel: '머리글 그리드',
});
const bottom = place('after', {
columns: COLUMNS,
rows: [
{
id: 0,
item: '합계',
q1: sum('q1'),
q2: sum('q2'),
q3: sum('q3'),
q4: sum('q4'),
plan: sum('plan'),
gap: sum('gap'),
},
],
rowKey: 'id',
showHeader: false,
autoGridHeight: true,
ariaLabel: '합계 그리드',
});
// 첫 그리드(header)가 기준이라 컬럼 폭은 머리글에서 끌어 바꿔요.
grids = [header, api, bottom];
link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
const offs = grids.map((grid, index) => grid.on('gridsAligned', (e) => log({
ko: `${['머리글', '본문', '합계'][index]} 그리드가 맞춰졌어요(${e.count}개)`,
en: `${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`,
})));
log({
ko: '맨 위 머리글에서 컬럼 폭을 끌거나 제목을 옮기면 본문과 합계 그리드가 따라가요.',
en: 'Drag a column width or move a title in the top header and the body and totals grids follow.',
});
return () => {
offs.forEach((off) => off());
link?.unlink();
[grids[0], grids[2]].forEach((grid) => grid?.destroy());
hosts.forEach((host) => host.remove());
grids = [];
hosts = [];
link = null;
};
}
export const actions = {
// 항목 컬럼을 넓혀요.
widen: (api) => {
const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
api.resizeColumn('item', width + 50);
},
// 차이 컬럼을 맨 앞으로 옮겨요.
move: (api) => api.moveColumn('gap', 0),
// 계획 컬럼을 숨기거나 다시 보여요.
plan: (api) => {
const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
api.setColumnVisible('plan', hidden);
},
};<!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">
<button type="button" id="widen">항목 넓히기</button>
<button type="button" id="move">차이 맨 앞으로</button>
<button type="button" id="plan">계획 숨기기/보이기</button>
</div>
<div id="grid" style="height: 240px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 머리글만 있는 그리드, 본문 그리드, 합계 그리드를 위아래로 쌓고 컬럼 폭·순서·숨김·스크롤을 서로 맞춰요.
const ITEMS = [
'노트북',
'태블릿',
'스마트워치',
'이어폰',
'보조배터리',
'스피커',
'키보드',
'모니터',
];
const COLUMNS = [
{ id: 'item', title: '항목', width: 150 },
{
id: 'q1',
title: '1분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q2',
title: '2분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q3',
title: '3분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q4',
title: '4분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'plan',
title: '계획',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'gap',
title: '차이',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
];
const body = ITEMS.map((item, i) => {
const q = [1, 2, 3, 4].map((k) => 40 + ((i * 17 + k * 29) % 60));
const plan = 190 + i * 5;
return {
id: i + 1,
item,
q1: q[0] ?? 0,
q2: q[1] ?? 0,
q3: q[2] ?? 0,
q4: q[3] ?? 0,
plan,
gap: q.reduce((a, b) => a + b, 0) - plan,
};
});
const sum = (key) => body.reduce((total, row) => total + (row[key] ?? 0), 0);
// 갤러리 틀이 만드는 그리드가 본문 그리드예요(머리글 없음). 머리글만 있는 그리드를 위에, 합계 그리드를 아래에 놓아요.
const options = {
columns: COLUMNS,
rows: body,
rowKey: 'id',
showHeader: false,
};
let grids = [];
let hosts = [];
let link = null;
function setup(api, log) {
const gridEl = document.getElementById('grid');
const place = (where, opts) => {
const host = document.createElement('div');
host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
if (gridEl !== null)
gridEl[where](host);
else
document.body.append(host);
hosts.push(host);
return MaxGrid.createGrid(host, opts);
};
const header = place('before', {
columns: COLUMNS,
rows: [],
rowKey: 'id',
overlays: false,
autoGridHeight: true,
ariaLabel: '머리글 그리드',
});
const bottom = place('after', {
columns: COLUMNS,
rows: [
{
id: 0,
item: '합계',
q1: sum('q1'),
q2: sum('q2'),
q3: sum('q3'),
q4: sum('q4'),
plan: sum('plan'),
gap: sum('gap'),
},
],
rowKey: 'id',
showHeader: false,
autoGridHeight: true,
ariaLabel: '합계 그리드',
});
// 첫 그리드(header)가 기준이라 컬럼 폭은 머리글에서 끌어 바꿔요.
grids = [header, api, bottom];
link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
const offs = grids.map((grid, index) => grid.on('gridsAligned', (e) => log({
ko: `${['머리글', '본문', '합계'][index]} 그리드가 맞춰졌어요(${e.count}개)`,
en: `${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`,
})));
log({
ko: '맨 위 머리글에서 컬럼 폭을 끌거나 제목을 옮기면 본문과 합계 그리드가 따라가요.',
en: 'Drag a column width or move a title in the top header and the body and totals grids follow.',
});
return () => {
offs.forEach((off) => off());
link?.unlink();
[grids[0], grids[2]].forEach((grid) => grid?.destroy());
hosts.forEach((host) => host.remove());
grids = [];
hosts = [];
link = null;
};
}
const actions = {
// 항목 컬럼을 넓혀요.
widen: (api) => {
const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
api.resizeColumn('item', width + 50);
},
// 차이 컬럼을 맨 앞으로 옮겨요.
move: (api) => api.moveColumn('gap', 0),
// 계획 컬럼을 숨기거나 다시 보여요.
plan: (api) => {
const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
api.setColumnVisible('plan', hidden);
},
};
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('widen').addEventListener('click', () => actions.widen(api));
document.getElementById('move').addEventListener('click', () => actions.move(api));
document.getElementById('plan').addEventListener('click', () => actions.plan(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">
<button
type="button"
disabled={!api}
onClick={() => api && actions.widen(api)}
>항목 넓히기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.move(api)}
>차이 맨 앞으로</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.plan(api)}
>계획 숨기기/보이기</button>
</div>
<Grid style={{ height: 240 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
q1: number | null;
q2: number | null;
q3: number | null;
q4: number | null;
plan: number | null;
gap: number | null;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
alignGrids(grids: GridApi<Row>[], opts?: { columns?: string[] }): { unlink(): void };
};
// 머리글만 있는 그리드, 본문 그리드, 합계 그리드를 위아래로 쌓고 컬럼 폭·순서·숨김·스크롤을 서로 맞춰요.
const ITEMS = [
'노트북',
'태블릿',
'스마트워치',
'이어폰',
'보조배터리',
'스피커',
'키보드',
'모니터',
];
const COLUMNS: GridOptions<Row>['columns'] = [
{ id: 'item', title: '항목', width: 150 },
{
id: 'q1',
title: '1분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q2',
title: '2분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q3',
title: '3분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q4',
title: '4분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'plan',
title: '계획',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'gap',
title: '차이',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
];
const body: Row[] = ITEMS.map((item, i) => {
const q = [1, 2, 3, 4].map((k) => 40 + ((i * 17 + k * 29) % 60));
const plan = 190 + i * 5;
return {
id: i + 1,
item,
q1: q[0] ?? 0,
q2: q[1] ?? 0,
q3: q[2] ?? 0,
q4: q[3] ?? 0,
plan,
gap: q.reduce((a, b) => a + b, 0) - plan,
};
});
const sum = (key: 'q1' | 'q2' | 'q3' | 'q4' | 'plan' | 'gap'): number =>
body.reduce((total, row) => total + (row[key] ?? 0), 0);
// 갤러리 틀이 만드는 그리드가 본문 그리드예요(머리글 없음). 머리글만 있는 그리드를 위에, 합계 그리드를 아래에 놓아요.
export const options: GridOptions<Row> = {
columns: COLUMNS,
rows: body,
rowKey: 'id',
showHeader: false,
};
let grids: GridApi<Row>[] = [];
let hosts: HTMLElement[] = [];
let link: { unlink(): void } | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const gridEl = document.getElementById('grid');
const place = (where: 'before' | 'after', opts: GridOptions<Row>): GridApi<Row> => {
const host = document.createElement('div');
host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
if (gridEl !== null) gridEl[where](host);
else document.body.append(host);
hosts.push(host);
return MaxGrid.createGrid(host, opts);
};
const header = place('before', {
columns: COLUMNS,
rows: [],
rowKey: 'id',
overlays: false,
autoGridHeight: true,
ariaLabel: '머리글 그리드',
});
const bottom = place('after', {
columns: COLUMNS,
rows: [
{
id: 0,
item: '합계',
q1: sum('q1'),
q2: sum('q2'),
q3: sum('q3'),
q4: sum('q4'),
plan: sum('plan'),
gap: sum('gap'),
},
],
rowKey: 'id',
showHeader: false,
autoGridHeight: true,
ariaLabel: '합계 그리드',
});
// 첫 그리드(header)가 기준이라 컬럼 폭은 머리글에서 끌어 바꿔요.
grids = [header, api, bottom];
link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
const offs = grids.map((grid, index) =>
grid.on('gridsAligned', (e) =>
log({
ko: `${['머리글', '본문', '합계'][index]} 그리드가 맞춰졌어요(${e.count}개)`,
en: `${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`,
}),
),
);
log({
ko: '맨 위 머리글에서 컬럼 폭을 끌거나 제목을 옮기면 본문과 합계 그리드가 따라가요.',
en: 'Drag a column width or move a title in the top header and the body and totals grids follow.',
});
return () => {
offs.forEach((off) => off());
link?.unlink();
[grids[0], grids[2]].forEach((grid) => grid?.destroy());
hosts.forEach((host) => host.remove());
grids = [];
hosts = [];
link = null;
};
}
export const actions = {
// 항목 컬럼을 넓혀요.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
api.resizeColumn('item', width + 50);
},
// 차이 컬럼을 맨 앞으로 옮겨요.
move: (api: GridApi<Row>) => api.moveColumn('gap', 0),
// 계획 컬럼을 숨기거나 다시 보여요.
plan: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
api.setColumnVisible('plan', hidden);
},
};버튼을 누르면 이 예제의 코드가 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">
<button type="button" :disabled="!api" @click="api && actions.widen(api)">항목 넓히기</button>
<button type="button" :disabled="!api" @click="api && actions.move(api)">차이 맨 앞으로</button>
<button type="button" :disabled="!api" @click="api && actions.plan(api)">계획 숨기기/보이기</button>
</div>
<Grid style="height: 240px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
q1: number | null;
q2: number | null;
q3: number | null;
q4: number | null;
plan: number | null;
gap: number | null;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
alignGrids(grids: GridApi<Row>[], opts?: { columns?: string[] }): { unlink(): void };
};
// 머리글만 있는 그리드, 본문 그리드, 합계 그리드를 위아래로 쌓고 컬럼 폭·순서·숨김·스크롤을 서로 맞춰요.
const ITEMS = [
'노트북',
'태블릿',
'스마트워치',
'이어폰',
'보조배터리',
'스피커',
'키보드',
'모니터',
];
const COLUMNS: GridOptions<Row>['columns'] = [
{ id: 'item', title: '항목', width: 150 },
{
id: 'q1',
title: '1분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q2',
title: '2분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q3',
title: '3분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q4',
title: '4분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'plan',
title: '계획',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'gap',
title: '차이',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
];
const body: Row[] = ITEMS.map((item, i) => {
const q = [1, 2, 3, 4].map((k) => 40 + ((i * 17 + k * 29) % 60));
const plan = 190 + i * 5;
return {
id: i + 1,
item,
q1: q[0] ?? 0,
q2: q[1] ?? 0,
q3: q[2] ?? 0,
q4: q[3] ?? 0,
plan,
gap: q.reduce((a, b) => a + b, 0) - plan,
};
});
const sum = (key: 'q1' | 'q2' | 'q3' | 'q4' | 'plan' | 'gap'): number =>
body.reduce((total, row) => total + (row[key] ?? 0), 0);
// 갤러리 틀이 만드는 그리드가 본문 그리드예요(머리글 없음). 머리글만 있는 그리드를 위에, 합계 그리드를 아래에 놓아요.
export const options: GridOptions<Row> = {
columns: COLUMNS,
rows: body,
rowKey: 'id',
showHeader: false,
};
let grids: GridApi<Row>[] = [];
let hosts: HTMLElement[] = [];
let link: { unlink(): void } | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const gridEl = document.getElementById('grid');
const place = (where: 'before' | 'after', opts: GridOptions<Row>): GridApi<Row> => {
const host = document.createElement('div');
host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
if (gridEl !== null) gridEl[where](host);
else document.body.append(host);
hosts.push(host);
return MaxGrid.createGrid(host, opts);
};
const header = place('before', {
columns: COLUMNS,
rows: [],
rowKey: 'id',
overlays: false,
autoGridHeight: true,
ariaLabel: '머리글 그리드',
});
const bottom = place('after', {
columns: COLUMNS,
rows: [
{
id: 0,
item: '합계',
q1: sum('q1'),
q2: sum('q2'),
q3: sum('q3'),
q4: sum('q4'),
plan: sum('plan'),
gap: sum('gap'),
},
],
rowKey: 'id',
showHeader: false,
autoGridHeight: true,
ariaLabel: '합계 그리드',
});
// 첫 그리드(header)가 기준이라 컬럼 폭은 머리글에서 끌어 바꿔요.
grids = [header, api, bottom];
link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
const offs = grids.map((grid, index) =>
grid.on('gridsAligned', (e) =>
log({
ko: `${['머리글', '본문', '합계'][index]} 그리드가 맞춰졌어요(${e.count}개)`,
en: `${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`,
}),
),
);
log({
ko: '맨 위 머리글에서 컬럼 폭을 끌거나 제목을 옮기면 본문과 합계 그리드가 따라가요.',
en: 'Drag a column width or move a title in the top header and the body and totals grids follow.',
});
return () => {
offs.forEach((off) => off());
link?.unlink();
[grids[0], grids[2]].forEach((grid) => grid?.destroy());
hosts.forEach((host) => host.remove());
grids = [];
hosts = [];
link = null;
};
}
export const actions = {
// 항목 컬럼을 넓혀요.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
api.resizeColumn('item', width + 50);
},
// 차이 컬럼을 맨 앞으로 옮겨요.
move: (api: GridApi<Row>) => api.moveColumn('gap', 0),
// 계획 컬럼을 숨기거나 다시 보여요.
plan: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
api.setColumnVisible('plan', hidden);
},
};버튼을 누르면 이 예제의 코드가 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">
<button
type="button"
[disabled]="!api"
(click)="api && actions.widen(api)"
>항목 넓히기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.move(api)"
>차이 맨 앞으로</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.plan(api)"
>계획 숨기기/보이기</button>
</div>
<mx-grid style="height: 240px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
q1: number | null;
q2: number | null;
q3: number | null;
q4: number | null;
plan: number | null;
gap: number | null;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
alignGrids(grids: GridApi<Row>[], opts?: { columns?: string[] }): { unlink(): void };
};
// 머리글만 있는 그리드, 본문 그리드, 합계 그리드를 위아래로 쌓고 컬럼 폭·순서·숨김·스크롤을 서로 맞춰요.
const ITEMS = [
'노트북',
'태블릿',
'스마트워치',
'이어폰',
'보조배터리',
'스피커',
'키보드',
'모니터',
];
const COLUMNS: GridOptions<Row>['columns'] = [
{ id: 'item', title: '항목', width: 150 },
{
id: 'q1',
title: '1분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q2',
title: '2분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q3',
title: '3분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'q4',
title: '4분기',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'plan',
title: '계획',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
{
id: 'gap',
title: '차이',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}만원`,
},
];
const body: Row[] = ITEMS.map((item, i) => {
const q = [1, 2, 3, 4].map((k) => 40 + ((i * 17 + k * 29) % 60));
const plan = 190 + i * 5;
return {
id: i + 1,
item,
q1: q[0] ?? 0,
q2: q[1] ?? 0,
q3: q[2] ?? 0,
q4: q[3] ?? 0,
plan,
gap: q.reduce((a, b) => a + b, 0) - plan,
};
});
const sum = (key: 'q1' | 'q2' | 'q3' | 'q4' | 'plan' | 'gap'): number =>
body.reduce((total, row) => total + (row[key] ?? 0), 0);
// 갤러리 틀이 만드는 그리드가 본문 그리드예요(머리글 없음). 머리글만 있는 그리드를 위에, 합계 그리드를 아래에 놓아요.
export const options: GridOptions<Row> = {
columns: COLUMNS,
rows: body,
rowKey: 'id',
showHeader: false,
};
let grids: GridApi<Row>[] = [];
let hosts: HTMLElement[] = [];
let link: { unlink(): void } | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const gridEl = document.getElementById('grid');
const place = (where: 'before' | 'after', opts: GridOptions<Row>): GridApi<Row> => {
const host = document.createElement('div');
host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
if (gridEl !== null) gridEl[where](host);
else document.body.append(host);
hosts.push(host);
return MaxGrid.createGrid(host, opts);
};
const header = place('before', {
columns: COLUMNS,
rows: [],
rowKey: 'id',
overlays: false,
autoGridHeight: true,
ariaLabel: '머리글 그리드',
});
const bottom = place('after', {
columns: COLUMNS,
rows: [
{
id: 0,
item: '합계',
q1: sum('q1'),
q2: sum('q2'),
q3: sum('q3'),
q4: sum('q4'),
plan: sum('plan'),
gap: sum('gap'),
},
],
rowKey: 'id',
showHeader: false,
autoGridHeight: true,
ariaLabel: '합계 그리드',
});
// 첫 그리드(header)가 기준이라 컬럼 폭은 머리글에서 끌어 바꿔요.
grids = [header, api, bottom];
link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
const offs = grids.map((grid, index) =>
grid.on('gridsAligned', (e) =>
log({
ko: `${['머리글', '본문', '합계'][index]} 그리드가 맞춰졌어요(${e.count}개)`,
en: `${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`,
}),
),
);
log({
ko: '맨 위 머리글에서 컬럼 폭을 끌거나 제목을 옮기면 본문과 합계 그리드가 따라가요.',
en: 'Drag a column width or move a title in the top header and the body and totals grids follow.',
});
return () => {
offs.forEach((off) => off());
link?.unlink();
[grids[0], grids[2]].forEach((grid) => grid?.destroy());
hosts.forEach((host) => host.remove());
grids = [];
hosts = [];
link = null;
};
}
export const actions = {
// 항목 컬럼을 넓혀요.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
api.resizeColumn('item', width + 50);
},
// 차이 컬럼을 맨 앞으로 옮겨요.
move: (api: GridApi<Row>) => api.moveColumn('gap', 0),
// 계획 컬럼을 숨기거나 다시 보여요.
plan: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
api.setColumnVisible('plan', hidden);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="widen">Widen Item</button>
<button type="button" id="move">Move Gap first</button>
<button type="button" id="plan">Hide/Show Plan</button>
</div>
<div id="grid" style="height: 240px"></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('widen').addEventListener('click', () => actions.widen(api));
document.getElementById('move').addEventListener('click', () => actions.move(api));
document.getElementById('plan').addEventListener('click', () => actions.plan(api));// A header-only grid, a body grid and a totals grid are stacked, and their column widths, order, visibility and scroll are aligned.
const ITEMS = [
'Laptop',
'Tablet',
'Smart watch',
'Earbuds',
'Power bank',
'Speaker',
'Keyboard',
'Monitor',
];
const COLUMNS = [
{ id: 'item', title: 'Item', width: 150 },
{
id: 'q1',
title: 'Q1',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q2',
title: 'Q2',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q3',
title: 'Q3',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q4',
title: 'Q4',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'plan',
title: 'Plan',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'gap',
title: 'Gap',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
];
const body = ITEMS.map((item, i) => {
const q = [1, 2, 3, 4].map((k) => 10 * (40 + ((i * 17 + k * 29) % 60)));
const plan = 10 * (190 + i * 5);
return {
id: i + 1,
item,
q1: q[0] ?? 0,
q2: q[1] ?? 0,
q3: q[2] ?? 0,
q4: q[3] ?? 0,
plan,
gap: q.reduce((a, b) => a + b, 0) - plan,
};
});
const sum = (key) => body.reduce((total, row) => total + (row[key] ?? 0), 0);
// The grid the frame creates is the body grid (no header). The header-only grid goes above it and the totals grid below.
export const options = {
columns: COLUMNS,
rows: body,
rowKey: 'id',
showHeader: false,
};
let grids = [];
let hosts = [];
let link = null;
export function setup(api, log) {
const gridEl = document.getElementById('grid');
const place = (where, opts) => {
const host = document.createElement('div');
host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
if (gridEl !== null)
gridEl[where](host);
else
document.body.append(host);
hosts.push(host);
return MaxGrid.createGrid(host, opts);
};
const header = place('before', {
columns: COLUMNS,
rows: [],
rowKey: 'id',
overlays: false,
autoGridHeight: true,
ariaLabel: 'Header grid',
});
const bottom = place('after', {
columns: COLUMNS,
rows: [
{
id: 0,
item: 'Total',
q1: sum('q1'),
q2: sum('q2'),
q3: sum('q3'),
q4: sum('q4'),
plan: sum('plan'),
gap: sum('gap'),
},
],
rowKey: 'id',
showHeader: false,
autoGridHeight: true,
ariaLabel: 'Totals grid',
});
// The first grid (header) is the master, so drag column widths in the header.
grids = [header, api, bottom];
link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
const offs = grids.map((grid, index) => grid.on('gridsAligned', (e) => log(`${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`)));
log('Drag a column width or move a title in the top header and the body and totals grids follow.');
return () => {
offs.forEach((off) => off());
link?.unlink();
[grids[0], grids[2]].forEach((grid) => grid?.destroy());
hosts.forEach((host) => host.remove());
grids = [];
hosts = [];
link = null;
};
}
export const actions = {
// Widen the Item column.
widen: (api) => {
const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
api.resizeColumn('item', width + 50);
},
// Move the Gap column to the front.
move: (api) => api.moveColumn('gap', 0),
// Hide or show the Plan column.
plan: (api) => {
const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
api.setColumnVisible('plan', hidden);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Align a header, a body and a totals grid</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="widen">Widen Item</button>
<button type="button" id="move">Move Gap first</button>
<button type="button" id="plan">Hide/Show Plan</button>
</div>
<div id="grid" style="height: 240px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// A header-only grid, a body grid and a totals grid are stacked, and their column widths, order, visibility and scroll are aligned.
const ITEMS = [
'Laptop',
'Tablet',
'Smart watch',
'Earbuds',
'Power bank',
'Speaker',
'Keyboard',
'Monitor',
];
const COLUMNS = [
{ id: 'item', title: 'Item', width: 150 },
{
id: 'q1',
title: 'Q1',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q2',
title: 'Q2',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q3',
title: 'Q3',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q4',
title: 'Q4',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'plan',
title: 'Plan',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'gap',
title: 'Gap',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
];
const body = ITEMS.map((item, i) => {
const q = [1, 2, 3, 4].map((k) => 10 * (40 + ((i * 17 + k * 29) % 60)));
const plan = 10 * (190 + i * 5);
return {
id: i + 1,
item,
q1: q[0] ?? 0,
q2: q[1] ?? 0,
q3: q[2] ?? 0,
q4: q[3] ?? 0,
plan,
gap: q.reduce((a, b) => a + b, 0) - plan,
};
});
const sum = (key) => body.reduce((total, row) => total + (row[key] ?? 0), 0);
// The grid the frame creates is the body grid (no header). The header-only grid goes above it and the totals grid below.
const options = {
columns: COLUMNS,
rows: body,
rowKey: 'id',
showHeader: false,
};
let grids = [];
let hosts = [];
let link = null;
function setup(api, log) {
const gridEl = document.getElementById('grid');
const place = (where, opts) => {
const host = document.createElement('div');
host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
if (gridEl !== null)
gridEl[where](host);
else
document.body.append(host);
hosts.push(host);
return MaxGrid.createGrid(host, opts);
};
const header = place('before', {
columns: COLUMNS,
rows: [],
rowKey: 'id',
overlays: false,
autoGridHeight: true,
ariaLabel: 'Header grid',
});
const bottom = place('after', {
columns: COLUMNS,
rows: [
{
id: 0,
item: 'Total',
q1: sum('q1'),
q2: sum('q2'),
q3: sum('q3'),
q4: sum('q4'),
plan: sum('plan'),
gap: sum('gap'),
},
],
rowKey: 'id',
showHeader: false,
autoGridHeight: true,
ariaLabel: 'Totals grid',
});
// The first grid (header) is the master, so drag column widths in the header.
grids = [header, api, bottom];
link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
const offs = grids.map((grid, index) => grid.on('gridsAligned', (e) => log(`${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`)));
log('Drag a column width or move a title in the top header and the body and totals grids follow.');
return () => {
offs.forEach((off) => off());
link?.unlink();
[grids[0], grids[2]].forEach((grid) => grid?.destroy());
hosts.forEach((host) => host.remove());
grids = [];
hosts = [];
link = null;
};
}
const actions = {
// Widen the Item column.
widen: (api) => {
const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
api.resizeColumn('item', width + 50);
},
// Move the Gap column to the front.
move: (api) => api.moveColumn('gap', 0),
// Hide or show the Plan column.
plan: (api) => {
const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
api.setColumnVisible('plan', hidden);
},
};
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('widen').addEventListener('click', () => actions.widen(api));
document.getElementById('move').addEventListener('click', () => actions.move(api));
document.getElementById('plan').addEventListener('click', () => actions.plan(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">
<button
type="button"
disabled={!api}
onClick={() => api && actions.widen(api)}
>Widen Item</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.move(api)}
>Move Gap first</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.plan(api)}
>Hide/Show Plan</button>
</div>
<Grid style={{ height: 240 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
q1: number | null;
q2: number | null;
q3: number | null;
q4: number | null;
plan: number | null;
gap: number | null;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
alignGrids(grids: GridApi<Row>[], opts?: { columns?: string[] }): { unlink(): void };
};
// A header-only grid, a body grid and a totals grid are stacked, and their column widths, order, visibility and scroll are aligned.
const ITEMS = [
'Laptop',
'Tablet',
'Smart watch',
'Earbuds',
'Power bank',
'Speaker',
'Keyboard',
'Monitor',
];
const COLUMNS: GridOptions<Row>['columns'] = [
{ id: 'item', title: 'Item', width: 150 },
{
id: 'q1',
title: 'Q1',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q2',
title: 'Q2',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q3',
title: 'Q3',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q4',
title: 'Q4',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'plan',
title: 'Plan',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'gap',
title: 'Gap',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
];
const body: Row[] = ITEMS.map((item, i) => {
const q = [1, 2, 3, 4].map((k) => 10 * (40 + ((i * 17 + k * 29) % 60)));
const plan = 10 * (190 + i * 5);
return {
id: i + 1,
item,
q1: q[0] ?? 0,
q2: q[1] ?? 0,
q3: q[2] ?? 0,
q4: q[3] ?? 0,
plan,
gap: q.reduce((a, b) => a + b, 0) - plan,
};
});
const sum = (key: 'q1' | 'q2' | 'q3' | 'q4' | 'plan' | 'gap'): number =>
body.reduce((total, row) => total + (row[key] ?? 0), 0);
// The grid the frame creates is the body grid (no header). The header-only grid goes above it and the totals grid below.
export const options: GridOptions<Row> = {
columns: COLUMNS,
rows: body,
rowKey: 'id',
showHeader: false,
};
let grids: GridApi<Row>[] = [];
let hosts: HTMLElement[] = [];
let link: { unlink(): void } | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const gridEl = document.getElementById('grid');
const place = (where: 'before' | 'after', opts: GridOptions<Row>): GridApi<Row> => {
const host = document.createElement('div');
host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
if (gridEl !== null) gridEl[where](host);
else document.body.append(host);
hosts.push(host);
return MaxGrid.createGrid(host, opts);
};
const header = place('before', {
columns: COLUMNS,
rows: [],
rowKey: 'id',
overlays: false,
autoGridHeight: true,
ariaLabel: 'Header grid',
});
const bottom = place('after', {
columns: COLUMNS,
rows: [
{
id: 0,
item: 'Total',
q1: sum('q1'),
q2: sum('q2'),
q3: sum('q3'),
q4: sum('q4'),
plan: sum('plan'),
gap: sum('gap'),
},
],
rowKey: 'id',
showHeader: false,
autoGridHeight: true,
ariaLabel: 'Totals grid',
});
// The first grid (header) is the master, so drag column widths in the header.
grids = [header, api, bottom];
link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
const offs = grids.map((grid, index) =>
grid.on('gridsAligned', (e) =>
log(`${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`),
),
);
log(
'Drag a column width or move a title in the top header and the body and totals grids follow.',
);
return () => {
offs.forEach((off) => off());
link?.unlink();
[grids[0], grids[2]].forEach((grid) => grid?.destroy());
hosts.forEach((host) => host.remove());
grids = [];
hosts = [];
link = null;
};
}
export const actions = {
// Widen the Item column.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
api.resizeColumn('item', width + 50);
},
// Move the Gap column to the front.
move: (api: GridApi<Row>) => api.moveColumn('gap', 0),
// Hide or show the Plan column.
plan: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
api.setColumnVisible('plan', hidden);
},
};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">
<button type="button" :disabled="!api" @click="api && actions.widen(api)">Widen Item</button>
<button type="button" :disabled="!api" @click="api && actions.move(api)">Move Gap first</button>
<button type="button" :disabled="!api" @click="api && actions.plan(api)">Hide/Show Plan</button>
</div>
<Grid style="height: 240px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
q1: number | null;
q2: number | null;
q3: number | null;
q4: number | null;
plan: number | null;
gap: number | null;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
alignGrids(grids: GridApi<Row>[], opts?: { columns?: string[] }): { unlink(): void };
};
// A header-only grid, a body grid and a totals grid are stacked, and their column widths, order, visibility and scroll are aligned.
const ITEMS = [
'Laptop',
'Tablet',
'Smart watch',
'Earbuds',
'Power bank',
'Speaker',
'Keyboard',
'Monitor',
];
const COLUMNS: GridOptions<Row>['columns'] = [
{ id: 'item', title: 'Item', width: 150 },
{
id: 'q1',
title: 'Q1',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q2',
title: 'Q2',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q3',
title: 'Q3',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q4',
title: 'Q4',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'plan',
title: 'Plan',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'gap',
title: 'Gap',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
];
const body: Row[] = ITEMS.map((item, i) => {
const q = [1, 2, 3, 4].map((k) => 10 * (40 + ((i * 17 + k * 29) % 60)));
const plan = 10 * (190 + i * 5);
return {
id: i + 1,
item,
q1: q[0] ?? 0,
q2: q[1] ?? 0,
q3: q[2] ?? 0,
q4: q[3] ?? 0,
plan,
gap: q.reduce((a, b) => a + b, 0) - plan,
};
});
const sum = (key: 'q1' | 'q2' | 'q3' | 'q4' | 'plan' | 'gap'): number =>
body.reduce((total, row) => total + (row[key] ?? 0), 0);
// The grid the frame creates is the body grid (no header). The header-only grid goes above it and the totals grid below.
export const options: GridOptions<Row> = {
columns: COLUMNS,
rows: body,
rowKey: 'id',
showHeader: false,
};
let grids: GridApi<Row>[] = [];
let hosts: HTMLElement[] = [];
let link: { unlink(): void } | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const gridEl = document.getElementById('grid');
const place = (where: 'before' | 'after', opts: GridOptions<Row>): GridApi<Row> => {
const host = document.createElement('div');
host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
if (gridEl !== null) gridEl[where](host);
else document.body.append(host);
hosts.push(host);
return MaxGrid.createGrid(host, opts);
};
const header = place('before', {
columns: COLUMNS,
rows: [],
rowKey: 'id',
overlays: false,
autoGridHeight: true,
ariaLabel: 'Header grid',
});
const bottom = place('after', {
columns: COLUMNS,
rows: [
{
id: 0,
item: 'Total',
q1: sum('q1'),
q2: sum('q2'),
q3: sum('q3'),
q4: sum('q4'),
plan: sum('plan'),
gap: sum('gap'),
},
],
rowKey: 'id',
showHeader: false,
autoGridHeight: true,
ariaLabel: 'Totals grid',
});
// The first grid (header) is the master, so drag column widths in the header.
grids = [header, api, bottom];
link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
const offs = grids.map((grid, index) =>
grid.on('gridsAligned', (e) =>
log(`${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`),
),
);
log(
'Drag a column width or move a title in the top header and the body and totals grids follow.',
);
return () => {
offs.forEach((off) => off());
link?.unlink();
[grids[0], grids[2]].forEach((grid) => grid?.destroy());
hosts.forEach((host) => host.remove());
grids = [];
hosts = [];
link = null;
};
}
export const actions = {
// Widen the Item column.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
api.resizeColumn('item', width + 50);
},
// Move the Gap column to the front.
move: (api: GridApi<Row>) => api.moveColumn('gap', 0),
// Hide or show the Plan column.
plan: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
api.setColumnVisible('plan', hidden);
},
};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">
<button
type="button"
[disabled]="!api"
(click)="api && actions.widen(api)"
>Widen Item</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.move(api)"
>Move Gap first</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.plan(api)"
>Hide/Show Plan</button>
</div>
<mx-grid style="height: 240px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
q1: number | null;
q2: number | null;
q3: number | null;
q4: number | null;
plan: number | null;
gap: number | null;
}
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
alignGrids(grids: GridApi<Row>[], opts?: { columns?: string[] }): { unlink(): void };
};
// A header-only grid, a body grid and a totals grid are stacked, and their column widths, order, visibility and scroll are aligned.
const ITEMS = [
'Laptop',
'Tablet',
'Smart watch',
'Earbuds',
'Power bank',
'Speaker',
'Keyboard',
'Monitor',
];
const COLUMNS: GridOptions<Row>['columns'] = [
{ id: 'item', title: 'Item', width: 150 },
{
id: 'q1',
title: 'Q1',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q2',
title: 'Q2',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q3',
title: 'Q3',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'q4',
title: 'Q4',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'plan',
title: 'Plan',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{
id: 'gap',
title: 'Gap',
width: 120,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
];
const body: Row[] = ITEMS.map((item, i) => {
const q = [1, 2, 3, 4].map((k) => 10 * (40 + ((i * 17 + k * 29) % 60)));
const plan = 10 * (190 + i * 5);
return {
id: i + 1,
item,
q1: q[0] ?? 0,
q2: q[1] ?? 0,
q3: q[2] ?? 0,
q4: q[3] ?? 0,
plan,
gap: q.reduce((a, b) => a + b, 0) - plan,
};
});
const sum = (key: 'q1' | 'q2' | 'q3' | 'q4' | 'plan' | 'gap'): number =>
body.reduce((total, row) => total + (row[key] ?? 0), 0);
// The grid the frame creates is the body grid (no header). The header-only grid goes above it and the totals grid below.
export const options: GridOptions<Row> = {
columns: COLUMNS,
rows: body,
rowKey: 'id',
showHeader: false,
};
let grids: GridApi<Row>[] = [];
let hosts: HTMLElement[] = [];
let link: { unlink(): void } | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const gridEl = document.getElementById('grid');
const place = (where: 'before' | 'after', opts: GridOptions<Row>): GridApi<Row> => {
const host = document.createElement('div');
host.style.cssText = `margin-${where === 'before' ? 'bottom' : 'top'}:4px`;
if (gridEl !== null) gridEl[where](host);
else document.body.append(host);
hosts.push(host);
return MaxGrid.createGrid(host, opts);
};
const header = place('before', {
columns: COLUMNS,
rows: [],
rowKey: 'id',
overlays: false,
autoGridHeight: true,
ariaLabel: 'Header grid',
});
const bottom = place('after', {
columns: COLUMNS,
rows: [
{
id: 0,
item: 'Total',
q1: sum('q1'),
q2: sum('q2'),
q3: sum('q3'),
q4: sum('q4'),
plan: sum('plan'),
gap: sum('gap'),
},
],
rowKey: 'id',
showHeader: false,
autoGridHeight: true,
ariaLabel: 'Totals grid',
});
// The first grid (header) is the master, so drag column widths in the header.
grids = [header, api, bottom];
link = MaxGrid.alignGrids(grids, { columns: ['width', 'order', 'visibility'] });
const offs = grids.map((grid, index) =>
grid.on('gridsAligned', (e) =>
log(`${['Header', 'Body', 'Totals'][index]} grid aligned (${e.count} grids)`),
),
);
log(
'Drag a column width or move a title in the top header and the body and totals grids follow.',
);
return () => {
offs.forEach((off) => off());
link?.unlink();
[grids[0], grids[2]].forEach((grid) => grid?.destroy());
hosts.forEach((host) => host.remove());
grids = [];
hosts = [];
link = null;
};
}
export const actions = {
// Widen the Item column.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'item')?.width ?? 150;
api.resizeColumn('item', width + 50);
},
// Move the Gap column to the front.
move: (api: GridApi<Row>) => api.moveColumn('gap', 0),
// Hide or show the Plan column.
plan: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'plan')?.hidden === true;
api.setColumnVisible('plan', hidden);
},
};