주문 내역과 합계 그리드를 나란히 맞추기Align an order list with a totals grid
alignGrids나 api.alignWith로 그리드 둘을 이으면 한쪽에서 바꾼 컬럼 폭·순서·숨김이 다른 쪽에도 적용되고, 가로 스크롤도 서로 따라가요. 위는 주문 내역, 아래는 같은 컬럼의 합계 한 줄이에요.Link two grids with alignGrids or api.alignWith and a column width, order or visibility changed in one is applied to the other, and horizontal scrolling follows both ways. The top grid lists orders and the bottom one is a totals row with the same columns.
코드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="region">지역 숨기기/보이기</button>
<select aria-label="연결" id="link">
<option value="on" selected>이어 두기</option>
<option value="off">연결 끊기</option>
</select>
</div>
<div id="grid" style="height: 230px"></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('region').addEventListener('click', () => actions.region(api));
document.getElementById('link').addEventListener('change', (event) => actions.link(api, event.target.value));const customers = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후'];
const products = [
'무선 이어폰',
'노트북 14형',
'스마트워치',
'태블릿 11형',
'보조배터리',
'블루투스 스피커',
];
const regions = ['서울', '부산', '대구', '인천', '광주', '대전'];
const statuses = ['완료', '배송 중', '접수'];
const prices = [29000, 129000, 89000, 59000, 24000, 49000];
const qtys = [3, 1, 2, 4, 5, 2];
const columns = [
{ id: 'no', title: '번호', width: 70, align: 'end' },
{ id: 'customer', title: '고객', width: 150 },
{ id: 'product', title: '상품', width: 160 },
{ id: 'region', title: '지역', width: 110 },
{ id: 'qty', title: '수량', width: 100, kind: 'number', align: 'end' },
{
id: 'price',
title: '단가',
width: 130,
kind: 'number',
align: 'end',
formatValue: (v) => (v === null ? '' : `${Number(v).toLocaleString('ko-KR')}원`),
},
{
id: 'amount',
title: '금액',
width: 140,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
{ id: 'status', title: '상태', width: 120 },
];
// 위 그리드는 주문 내역, 아래 그리드는 같은 컬럼의 합계 한 줄이에요.
export const options = {
columns,
rows: customers.map((customer, i) => ({
no: i + 1,
customer,
product: products[i],
region: regions[i],
qty: qtys[i],
price: prices[i],
amount: prices[i] * qtys[i],
status: statuses[i % statuses.length],
})),
rowKey: 'no',
};
let totals = null;
let host = null;
let link = null;
const totalRow = {
no: '합계',
customer: '',
product: '',
region: '',
qty: 17,
price: null,
amount: 848000,
status: '',
};
export function setup(api, log) {
const first = document.getElementById('grid');
host = document.createElement('div');
host.style.cssText = 'margin-top:6px';
if (first !== null)
first.after(host);
else
document.body.append(host);
totals = MaxGrid.createGrid(host, {
columns: columns.map((c) => ({ ...c, sortable: false })),
rows: [totalRow],
rowKey: 'no',
showHeader: false,
ariaLabel: '합계 그리드',
});
const offs = [api, totals].map((grid, i) => {
const where = i === 0 ? '위' : '아래';
return grid.on('gridsAligned', (e) => log({
ko: `${where} 그리드가 맞춰졌어요(${e.count}개${e.master ? ', 기준' : ''})`,
en: `${where} grid aligned (${e.count} grids${e.master ? ', master' : ''})`,
}));
});
offs.push(totals.on('gridsUnaligned', () => log({ ko: '연결이 끊겼어요.', en: 'The link was removed.' })));
link = api.alignWith(totals);
return () => {
offs.forEach((off) => off());
link?.unlink();
totals?.destroy();
host?.remove();
totals = null;
host = null;
link = null;
};
}
export const actions = {
// 위 그리드에서 상품 컬럼을 넓혀요. 아래 그리드도 같은 폭이 돼요.
widen: (api) => {
const width = api.getColumnState().find((s) => s.id === 'product')?.width ?? 160;
api.resizeColumn('product', width + 60);
},
// 금액을 두 번째로 옮겨요.
move: (api) => api.moveColumn('amount', 1),
// 지역 컬럼을 숨기거나 다시 보여요.
region: (api) => {
const hidden = api.getColumnState().find((s) => s.id === 'region')?.hidden === true;
api.setColumnVisible('region', hidden);
},
// 연결을 끊거나 다시 이어요. 끊으면 두 그리드가 따로 움직여요.
link: (api, value) => {
if (totals === null)
return;
if (value === 'off') {
link?.unlink();
link = null;
}
else if (link === null)
link = api.alignWith(totals);
},
};<!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="region">지역 숨기기/보이기</button>
<select aria-label="연결" id="link">
<option value="on" selected>이어 두기</option>
<option value="off">연결 끊기</option>
</select>
</div>
<div id="grid" style="height: 230px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const customers = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후'];
const products = [
'무선 이어폰',
'노트북 14형',
'스마트워치',
'태블릿 11형',
'보조배터리',
'블루투스 스피커',
];
const regions = ['서울', '부산', '대구', '인천', '광주', '대전'];
const statuses = ['완료', '배송 중', '접수'];
const prices = [29000, 129000, 89000, 59000, 24000, 49000];
const qtys = [3, 1, 2, 4, 5, 2];
const columns = [
{ id: 'no', title: '번호', width: 70, align: 'end' },
{ id: 'customer', title: '고객', width: 150 },
{ id: 'product', title: '상품', width: 160 },
{ id: 'region', title: '지역', width: 110 },
{ id: 'qty', title: '수량', width: 100, kind: 'number', align: 'end' },
{
id: 'price',
title: '단가',
width: 130,
kind: 'number',
align: 'end',
formatValue: (v) => (v === null ? '' : `${Number(v).toLocaleString('ko-KR')}원`),
},
{
id: 'amount',
title: '금액',
width: 140,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
{ id: 'status', title: '상태', width: 120 },
];
// 위 그리드는 주문 내역, 아래 그리드는 같은 컬럼의 합계 한 줄이에요.
const options = {
columns,
rows: customers.map((customer, i) => ({
no: i + 1,
customer,
product: products[i],
region: regions[i],
qty: qtys[i],
price: prices[i],
amount: prices[i] * qtys[i],
status: statuses[i % statuses.length],
})),
rowKey: 'no',
};
let totals = null;
let host = null;
let link = null;
const totalRow = {
no: '합계',
customer: '',
product: '',
region: '',
qty: 17,
price: null,
amount: 848000,
status: '',
};
function setup(api, log) {
const first = document.getElementById('grid');
host = document.createElement('div');
host.style.cssText = 'margin-top:6px';
if (first !== null)
first.after(host);
else
document.body.append(host);
totals = MaxGrid.createGrid(host, {
columns: columns.map((c) => ({ ...c, sortable: false })),
rows: [totalRow],
rowKey: 'no',
showHeader: false,
ariaLabel: '합계 그리드',
});
const offs = [api, totals].map((grid, i) => {
const where = i === 0 ? '위' : '아래';
return grid.on('gridsAligned', (e) => log({
ko: `${where} 그리드가 맞춰졌어요(${e.count}개${e.master ? ', 기준' : ''})`,
en: `${where} grid aligned (${e.count} grids${e.master ? ', master' : ''})`,
}));
});
offs.push(totals.on('gridsUnaligned', () => log({ ko: '연결이 끊겼어요.', en: 'The link was removed.' })));
link = api.alignWith(totals);
return () => {
offs.forEach((off) => off());
link?.unlink();
totals?.destroy();
host?.remove();
totals = null;
host = null;
link = null;
};
}
const actions = {
// 위 그리드에서 상품 컬럼을 넓혀요. 아래 그리드도 같은 폭이 돼요.
widen: (api) => {
const width = api.getColumnState().find((s) => s.id === 'product')?.width ?? 160;
api.resizeColumn('product', width + 60);
},
// 금액을 두 번째로 옮겨요.
move: (api) => api.moveColumn('amount', 1),
// 지역 컬럼을 숨기거나 다시 보여요.
region: (api) => {
const hidden = api.getColumnState().find((s) => s.id === 'region')?.hidden === true;
api.setColumnVisible('region', hidden);
},
// 연결을 끊거나 다시 이어요. 끊으면 두 그리드가 따로 움직여요.
link: (api, value) => {
if (totals === null)
return;
if (value === 'off') {
link?.unlink();
link = null;
}
else if (link === null)
link = api.alignWith(totals);
},
};
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('region').addEventListener('click', () => actions.region(api));
document.getElementById('link').addEventListener('change', (event) => actions.link(api, event.target.value));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<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.region(api)}
>지역 숨기기/보이기</button>
<select
aria-label="연결"
disabled={!api}
onChange={(event) => api && actions.link(api, event.target.value)}
>
<option value="on">이어 두기</option>
<option value="off">연결 끊기</option>
</select>
</div>
<Grid style={{ height: 230 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
no: number | string;
customer: string;
product: string;
region: string;
qty: number | null;
price: number | null;
amount: number;
status: string;
}
// 갤러리 틀이 불러 둔 전역 MaxGrid. 아래 합계 그리드를 만들 때 써요.
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
};
const customers = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후'];
const products = [
'무선 이어폰',
'노트북 14형',
'스마트워치',
'태블릿 11형',
'보조배터리',
'블루투스 스피커',
];
const regions = ['서울', '부산', '대구', '인천', '광주', '대전'];
const statuses = ['완료', '배송 중', '접수'];
const prices = [29000, 129000, 89000, 59000, 24000, 49000];
const qtys = [3, 1, 2, 4, 5, 2];
const columns: GridOptions<Row>['columns'] = [
{ id: 'no', title: '번호', width: 70, align: 'end' },
{ id: 'customer', title: '고객', width: 150 },
{ id: 'product', title: '상품', width: 160 },
{ id: 'region', title: '지역', width: 110 },
{ id: 'qty', title: '수량', width: 100, kind: 'number', align: 'end' },
{
id: 'price',
title: '단가',
width: 130,
kind: 'number',
align: 'end',
formatValue: (v) => (v === null ? '' : `${Number(v).toLocaleString('ko-KR')}원`),
},
{
id: 'amount',
title: '금액',
width: 140,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
{ id: 'status', title: '상태', width: 120 },
];
// 위 그리드는 주문 내역, 아래 그리드는 같은 컬럼의 합계 한 줄이에요.
export const options: GridOptions<Row> = {
columns,
rows: customers.map((customer, i) => ({
no: i + 1,
customer,
product: products[i],
region: regions[i],
qty: qtys[i],
price: prices[i],
amount: prices[i] * qtys[i],
status: statuses[i % statuses.length],
})),
rowKey: 'no',
};
let totals: GridApi<Row> | null = null;
let host: HTMLElement | null = null;
let link: { unlink(): void } | null = null;
const totalRow: Row = {
no: '합계',
customer: '',
product: '',
region: '',
qty: 17,
price: null,
amount: 848000,
status: '',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const first = document.getElementById('grid');
host = document.createElement('div');
host.style.cssText = 'margin-top:6px';
if (first !== null) first.after(host);
else document.body.append(host);
totals = MaxGrid.createGrid(host, {
columns: columns.map((c) => ({ ...c, sortable: false })),
rows: [totalRow],
rowKey: 'no',
showHeader: false,
ariaLabel: '합계 그리드',
});
const offs = [api, totals].map((grid, i) => {
const where = i === 0 ? '위' : '아래';
return grid.on('gridsAligned', (e) =>
log({
ko: `${where} 그리드가 맞춰졌어요(${e.count}개${e.master ? ', 기준' : ''})`,
en: `${where} grid aligned (${e.count} grids${e.master ? ', master' : ''})`,
}),
);
});
offs.push(
totals.on('gridsUnaligned', () => log({ ko: '연결이 끊겼어요.', en: 'The link was removed.' })),
);
link = api.alignWith(totals);
return () => {
offs.forEach((off) => off());
link?.unlink();
totals?.destroy();
host?.remove();
totals = null;
host = null;
link = null;
};
}
export const actions = {
// 위 그리드에서 상품 컬럼을 넓혀요. 아래 그리드도 같은 폭이 돼요.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'product')?.width ?? 160;
api.resizeColumn('product', width + 60);
},
// 금액을 두 번째로 옮겨요.
move: (api: GridApi<Row>) => api.moveColumn('amount', 1),
// 지역 컬럼을 숨기거나 다시 보여요.
region: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'region')?.hidden === true;
api.setColumnVisible('region', hidden);
},
// 연결을 끊거나 다시 이어요. 끊으면 두 그리드가 따로 움직여요.
link: (api: GridApi<Row>, value?: string) => {
if (totals === null) return;
if (value === 'off') {
link?.unlink();
link = null;
} else if (link === null) link = api.alignWith(totals);
},
};버튼을 누르면 이 예제의 코드가 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.region(api)">지역 숨기기/보이기</button>
<select
aria-label="연결"
:disabled="!api"
@change="api && actions.link(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>이어 두기</option>
<option value="off">연결 끊기</option>
</select>
</div>
<Grid style="height: 230px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
no: number | string;
customer: string;
product: string;
region: string;
qty: number | null;
price: number | null;
amount: number;
status: string;
}
// 갤러리 틀이 불러 둔 전역 MaxGrid. 아래 합계 그리드를 만들 때 써요.
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
};
const customers = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후'];
const products = [
'무선 이어폰',
'노트북 14형',
'스마트워치',
'태블릿 11형',
'보조배터리',
'블루투스 스피커',
];
const regions = ['서울', '부산', '대구', '인천', '광주', '대전'];
const statuses = ['완료', '배송 중', '접수'];
const prices = [29000, 129000, 89000, 59000, 24000, 49000];
const qtys = [3, 1, 2, 4, 5, 2];
const columns: GridOptions<Row>['columns'] = [
{ id: 'no', title: '번호', width: 70, align: 'end' },
{ id: 'customer', title: '고객', width: 150 },
{ id: 'product', title: '상품', width: 160 },
{ id: 'region', title: '지역', width: 110 },
{ id: 'qty', title: '수량', width: 100, kind: 'number', align: 'end' },
{
id: 'price',
title: '단가',
width: 130,
kind: 'number',
align: 'end',
formatValue: (v) => (v === null ? '' : `${Number(v).toLocaleString('ko-KR')}원`),
},
{
id: 'amount',
title: '금액',
width: 140,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
{ id: 'status', title: '상태', width: 120 },
];
// 위 그리드는 주문 내역, 아래 그리드는 같은 컬럼의 합계 한 줄이에요.
export const options: GridOptions<Row> = {
columns,
rows: customers.map((customer, i) => ({
no: i + 1,
customer,
product: products[i],
region: regions[i],
qty: qtys[i],
price: prices[i],
amount: prices[i] * qtys[i],
status: statuses[i % statuses.length],
})),
rowKey: 'no',
};
let totals: GridApi<Row> | null = null;
let host: HTMLElement | null = null;
let link: { unlink(): void } | null = null;
const totalRow: Row = {
no: '합계',
customer: '',
product: '',
region: '',
qty: 17,
price: null,
amount: 848000,
status: '',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const first = document.getElementById('grid');
host = document.createElement('div');
host.style.cssText = 'margin-top:6px';
if (first !== null) first.after(host);
else document.body.append(host);
totals = MaxGrid.createGrid(host, {
columns: columns.map((c) => ({ ...c, sortable: false })),
rows: [totalRow],
rowKey: 'no',
showHeader: false,
ariaLabel: '합계 그리드',
});
const offs = [api, totals].map((grid, i) => {
const where = i === 0 ? '위' : '아래';
return grid.on('gridsAligned', (e) =>
log({
ko: `${where} 그리드가 맞춰졌어요(${e.count}개${e.master ? ', 기준' : ''})`,
en: `${where} grid aligned (${e.count} grids${e.master ? ', master' : ''})`,
}),
);
});
offs.push(
totals.on('gridsUnaligned', () => log({ ko: '연결이 끊겼어요.', en: 'The link was removed.' })),
);
link = api.alignWith(totals);
return () => {
offs.forEach((off) => off());
link?.unlink();
totals?.destroy();
host?.remove();
totals = null;
host = null;
link = null;
};
}
export const actions = {
// 위 그리드에서 상품 컬럼을 넓혀요. 아래 그리드도 같은 폭이 돼요.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'product')?.width ?? 160;
api.resizeColumn('product', width + 60);
},
// 금액을 두 번째로 옮겨요.
move: (api: GridApi<Row>) => api.moveColumn('amount', 1),
// 지역 컬럼을 숨기거나 다시 보여요.
region: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'region')?.hidden === true;
api.setColumnVisible('region', hidden);
},
// 연결을 끊거나 다시 이어요. 끊으면 두 그리드가 따로 움직여요.
link: (api: GridApi<Row>, value?: string) => {
if (totals === null) return;
if (value === 'off') {
link?.unlink();
link = null;
} else if (link === null) link = api.alignWith(totals);
},
};버튼을 누르면 이 예제의 코드가 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.region(api)"
>지역 숨기기/보이기</button>
<select
aria-label="연결"
[disabled]="!api"
(change)="api && actions.link(api, $any($event.target).value)"
>
<option value="on" selected>이어 두기</option>
<option value="off">연결 끊기</option>
</select>
</div>
<mx-grid style="height: 230px" [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 {
no: number | string;
customer: string;
product: string;
region: string;
qty: number | null;
price: number | null;
amount: number;
status: string;
}
// 갤러리 틀이 불러 둔 전역 MaxGrid. 아래 합계 그리드를 만들 때 써요.
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
};
const customers = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후'];
const products = [
'무선 이어폰',
'노트북 14형',
'스마트워치',
'태블릿 11형',
'보조배터리',
'블루투스 스피커',
];
const regions = ['서울', '부산', '대구', '인천', '광주', '대전'];
const statuses = ['완료', '배송 중', '접수'];
const prices = [29000, 129000, 89000, 59000, 24000, 49000];
const qtys = [3, 1, 2, 4, 5, 2];
const columns: GridOptions<Row>['columns'] = [
{ id: 'no', title: '번호', width: 70, align: 'end' },
{ id: 'customer', title: '고객', width: 150 },
{ id: 'product', title: '상품', width: 160 },
{ id: 'region', title: '지역', width: 110 },
{ id: 'qty', title: '수량', width: 100, kind: 'number', align: 'end' },
{
id: 'price',
title: '단가',
width: 130,
kind: 'number',
align: 'end',
formatValue: (v) => (v === null ? '' : `${Number(v).toLocaleString('ko-KR')}원`),
},
{
id: 'amount',
title: '금액',
width: 140,
kind: 'number',
align: 'end',
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
{ id: 'status', title: '상태', width: 120 },
];
// 위 그리드는 주문 내역, 아래 그리드는 같은 컬럼의 합계 한 줄이에요.
export const options: GridOptions<Row> = {
columns,
rows: customers.map((customer, i) => ({
no: i + 1,
customer,
product: products[i],
region: regions[i],
qty: qtys[i],
price: prices[i],
amount: prices[i] * qtys[i],
status: statuses[i % statuses.length],
})),
rowKey: 'no',
};
let totals: GridApi<Row> | null = null;
let host: HTMLElement | null = null;
let link: { unlink(): void } | null = null;
const totalRow: Row = {
no: '합계',
customer: '',
product: '',
region: '',
qty: 17,
price: null,
amount: 848000,
status: '',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const first = document.getElementById('grid');
host = document.createElement('div');
host.style.cssText = 'margin-top:6px';
if (first !== null) first.after(host);
else document.body.append(host);
totals = MaxGrid.createGrid(host, {
columns: columns.map((c) => ({ ...c, sortable: false })),
rows: [totalRow],
rowKey: 'no',
showHeader: false,
ariaLabel: '합계 그리드',
});
const offs = [api, totals].map((grid, i) => {
const where = i === 0 ? '위' : '아래';
return grid.on('gridsAligned', (e) =>
log({
ko: `${where} 그리드가 맞춰졌어요(${e.count}개${e.master ? ', 기준' : ''})`,
en: `${where} grid aligned (${e.count} grids${e.master ? ', master' : ''})`,
}),
);
});
offs.push(
totals.on('gridsUnaligned', () => log({ ko: '연결이 끊겼어요.', en: 'The link was removed.' })),
);
link = api.alignWith(totals);
return () => {
offs.forEach((off) => off());
link?.unlink();
totals?.destroy();
host?.remove();
totals = null;
host = null;
link = null;
};
}
export const actions = {
// 위 그리드에서 상품 컬럼을 넓혀요. 아래 그리드도 같은 폭이 돼요.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'product')?.width ?? 160;
api.resizeColumn('product', width + 60);
},
// 금액을 두 번째로 옮겨요.
move: (api: GridApi<Row>) => api.moveColumn('amount', 1),
// 지역 컬럼을 숨기거나 다시 보여요.
region: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'region')?.hidden === true;
api.setColumnVisible('region', hidden);
},
// 연결을 끊거나 다시 이어요. 끊으면 두 그리드가 따로 움직여요.
link: (api: GridApi<Row>, value?: string) => {
if (totals === null) return;
if (value === 'off') {
link?.unlink();
link = null;
} else if (link === null) link = api.alignWith(totals);
},
};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 Product</button>
<button type="button" id="move">Move Amount first</button>
<button type="button" id="region">Hide/Show Region</button>
<select aria-label="Link" id="link">
<option value="on" selected>Linked</option>
<option value="off">Remove link</option>
</select>
</div>
<div id="grid" style="height: 230px"></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('region').addEventListener('click', () => actions.region(api));
document.getElementById('link').addEventListener('change', (event) => actions.link(api, event.target.value));const customers = [
'Emma Stone',
'Liam Carter',
'Olivia Reed',
'Noah Hayes',
'Ava Foster',
'Mason Clark',
];
const products = [
'Wireless earbuds',
'Laptop 14"',
'Smart watch',
'Tablet 11"',
'Power bank',
'Bluetooth speaker',
];
const regions = ['Austin', 'Boston', 'Denver', 'Seattle', 'Portland', 'Dallas'];
const statuses = ['Done', 'Shipping', 'Received'];
const prices = [29, 129, 89, 59, 24, 49];
const qtys = [3, 1, 2, 4, 5, 2];
const columns = [
{ id: 'no', title: 'No.', width: 70, align: 'end' },
{ id: 'customer', title: 'Customer', width: 150 },
{ id: 'product', title: 'Product', width: 160 },
{ id: 'region', title: 'Region', width: 110 },
{ id: 'qty', title: 'Qty', width: 100, kind: 'number', align: 'end' },
{
id: 'price',
title: 'Unit price',
width: 130,
kind: 'number',
align: 'end',
formatValue: (v) => (v === null ? '' : `$${Number(v).toLocaleString('en-US')}`),
},
{
id: 'amount',
title: 'Amount',
width: 140,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{ id: 'status', title: 'Status', width: 120 },
];
// The top grid lists the orders; the bottom grid is one totals row with the same columns.
export const options = {
columns,
rows: customers.map((customer, i) => ({
no: i + 1,
customer,
product: products[i],
region: regions[i],
qty: qtys[i],
price: prices[i],
amount: prices[i] * qtys[i],
status: statuses[i % statuses.length],
})),
rowKey: 'no',
};
let totals = null;
let host = null;
let link = null;
const totalRow = {
no: 'Total',
customer: '',
product: '',
region: '',
qty: 17,
price: null,
amount: 848,
status: '',
};
export function setup(api, log) {
const first = document.getElementById('grid');
host = document.createElement('div');
host.style.cssText = 'margin-top:6px';
if (first !== null)
first.after(host);
else
document.body.append(host);
totals = MaxGrid.createGrid(host, {
columns: columns.map((c) => ({ ...c, sortable: false })),
rows: [totalRow],
rowKey: 'no',
showHeader: false,
autoGridHeight: true,
ariaLabel: 'Totals grid',
});
const offs = [api, totals].map((grid, i) => {
const where = i === 0 ? 'Top' : 'Bottom';
return grid.on('gridsAligned', (e) => log(`${where} grid aligned (${e.count} grids${e.master ? ', master' : ''})`));
});
offs.push(totals.on('gridsUnaligned', () => log('The link was removed.')));
link = api.alignWith(totals);
return () => {
offs.forEach((off) => off());
link?.unlink();
totals?.destroy();
host?.remove();
totals = null;
host = null;
link = null;
};
}
export const actions = {
// Widen the Product column in the top grid. The bottom grid gets the same width.
widen: (api) => {
const width = api.getColumnState().find((s) => s.id === 'product')?.width ?? 160;
api.resizeColumn('product', width + 60);
},
// Move Amount to the second place.
move: (api) => api.moveColumn('amount', 1),
// Hide or show the Region column.
region: (api) => {
const hidden = api.getColumnState().find((s) => s.id === 'region')?.hidden === true;
api.setColumnVisible('region', hidden);
},
// Remove or restore the link. Without it the two grids move on their own.
link: (api, value) => {
if (totals === null)
return;
if (value === 'off') {
link?.unlink();
link = null;
}
else if (link === null)
link = api.alignWith(totals);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Align an order list with a totals grid</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="widen">Widen Product</button>
<button type="button" id="move">Move Amount first</button>
<button type="button" id="region">Hide/Show Region</button>
<select aria-label="Link" id="link">
<option value="on" selected>Linked</option>
<option value="off">Remove link</option>
</select>
</div>
<div id="grid" style="height: 230px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const customers = [
'Emma Stone',
'Liam Carter',
'Olivia Reed',
'Noah Hayes',
'Ava Foster',
'Mason Clark',
];
const products = [
'Wireless earbuds',
'Laptop 14"',
'Smart watch',
'Tablet 11"',
'Power bank',
'Bluetooth speaker',
];
const regions = ['Austin', 'Boston', 'Denver', 'Seattle', 'Portland', 'Dallas'];
const statuses = ['Done', 'Shipping', 'Received'];
const prices = [29, 129, 89, 59, 24, 49];
const qtys = [3, 1, 2, 4, 5, 2];
const columns = [
{ id: 'no', title: 'No.', width: 70, align: 'end' },
{ id: 'customer', title: 'Customer', width: 150 },
{ id: 'product', title: 'Product', width: 160 },
{ id: 'region', title: 'Region', width: 110 },
{ id: 'qty', title: 'Qty', width: 100, kind: 'number', align: 'end' },
{
id: 'price',
title: 'Unit price',
width: 130,
kind: 'number',
align: 'end',
formatValue: (v) => (v === null ? '' : `$${Number(v).toLocaleString('en-US')}`),
},
{
id: 'amount',
title: 'Amount',
width: 140,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{ id: 'status', title: 'Status', width: 120 },
];
// The top grid lists the orders; the bottom grid is one totals row with the same columns.
const options = {
columns,
rows: customers.map((customer, i) => ({
no: i + 1,
customer,
product: products[i],
region: regions[i],
qty: qtys[i],
price: prices[i],
amount: prices[i] * qtys[i],
status: statuses[i % statuses.length],
})),
rowKey: 'no',
};
let totals = null;
let host = null;
let link = null;
const totalRow = {
no: 'Total',
customer: '',
product: '',
region: '',
qty: 17,
price: null,
amount: 848,
status: '',
};
function setup(api, log) {
const first = document.getElementById('grid');
host = document.createElement('div');
host.style.cssText = 'margin-top:6px';
if (first !== null)
first.after(host);
else
document.body.append(host);
totals = MaxGrid.createGrid(host, {
columns: columns.map((c) => ({ ...c, sortable: false })),
rows: [totalRow],
rowKey: 'no',
showHeader: false,
autoGridHeight: true,
ariaLabel: 'Totals grid',
});
const offs = [api, totals].map((grid, i) => {
const where = i === 0 ? 'Top' : 'Bottom';
return grid.on('gridsAligned', (e) => log(`${where} grid aligned (${e.count} grids${e.master ? ', master' : ''})`));
});
offs.push(totals.on('gridsUnaligned', () => log('The link was removed.')));
link = api.alignWith(totals);
return () => {
offs.forEach((off) => off());
link?.unlink();
totals?.destroy();
host?.remove();
totals = null;
host = null;
link = null;
};
}
const actions = {
// Widen the Product column in the top grid. The bottom grid gets the same width.
widen: (api) => {
const width = api.getColumnState().find((s) => s.id === 'product')?.width ?? 160;
api.resizeColumn('product', width + 60);
},
// Move Amount to the second place.
move: (api) => api.moveColumn('amount', 1),
// Hide or show the Region column.
region: (api) => {
const hidden = api.getColumnState().find((s) => s.id === 'region')?.hidden === true;
api.setColumnVisible('region', hidden);
},
// Remove or restore the link. Without it the two grids move on their own.
link: (api, value) => {
if (totals === null)
return;
if (value === 'off') {
link?.unlink();
link = null;
}
else if (link === null)
link = api.alignWith(totals);
},
};
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('region').addEventListener('click', () => actions.region(api));
document.getElementById('link').addEventListener('change', (event) => actions.link(api, event.target.value));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.widen(api)}
>Widen Product</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.move(api)}
>Move Amount first</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.region(api)}
>Hide/Show Region</button>
<select
aria-label="Link"
disabled={!api}
onChange={(event) => api && actions.link(api, event.target.value)}
>
<option value="on">Linked</option>
<option value="off">Remove link</option>
</select>
</div>
<Grid style={{ height: 230 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
no: number | string;
customer: string;
product: string;
region: string;
qty: number | null;
price: number | null;
amount: number;
status: string;
}
// The global MaxGrid that the gallery frame loads. It builds the totals grid below.
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
};
const customers = [
'Emma Stone',
'Liam Carter',
'Olivia Reed',
'Noah Hayes',
'Ava Foster',
'Mason Clark',
];
const products = [
'Wireless earbuds',
'Laptop 14"',
'Smart watch',
'Tablet 11"',
'Power bank',
'Bluetooth speaker',
];
const regions = ['Austin', 'Boston', 'Denver', 'Seattle', 'Portland', 'Dallas'];
const statuses = ['Done', 'Shipping', 'Received'];
const prices = [29, 129, 89, 59, 24, 49];
const qtys = [3, 1, 2, 4, 5, 2];
const columns: GridOptions<Row>['columns'] = [
{ id: 'no', title: 'No.', width: 70, align: 'end' },
{ id: 'customer', title: 'Customer', width: 150 },
{ id: 'product', title: 'Product', width: 160 },
{ id: 'region', title: 'Region', width: 110 },
{ id: 'qty', title: 'Qty', width: 100, kind: 'number', align: 'end' },
{
id: 'price',
title: 'Unit price',
width: 130,
kind: 'number',
align: 'end',
formatValue: (v) => (v === null ? '' : `$${Number(v).toLocaleString('en-US')}`),
},
{
id: 'amount',
title: 'Amount',
width: 140,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{ id: 'status', title: 'Status', width: 120 },
];
// The top grid lists the orders; the bottom grid is one totals row with the same columns.
export const options: GridOptions<Row> = {
columns,
rows: customers.map((customer, i) => ({
no: i + 1,
customer,
product: products[i],
region: regions[i],
qty: qtys[i],
price: prices[i],
amount: prices[i] * qtys[i],
status: statuses[i % statuses.length],
})),
rowKey: 'no',
};
let totals: GridApi<Row> | null = null;
let host: HTMLElement | null = null;
let link: { unlink(): void } | null = null;
const totalRow: Row = {
no: 'Total',
customer: '',
product: '',
region: '',
qty: 17,
price: null,
amount: 848,
status: '',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const first = document.getElementById('grid');
host = document.createElement('div');
host.style.cssText = 'margin-top:6px';
if (first !== null) first.after(host);
else document.body.append(host);
totals = MaxGrid.createGrid(host, {
columns: columns.map((c) => ({ ...c, sortable: false })),
rows: [totalRow],
rowKey: 'no',
showHeader: false,
autoGridHeight: true,
ariaLabel: 'Totals grid',
});
const offs = [api, totals].map((grid, i) => {
const where = i === 0 ? 'Top' : 'Bottom';
return grid.on('gridsAligned', (e) =>
log(`${where} grid aligned (${e.count} grids${e.master ? ', master' : ''})`),
);
});
offs.push(totals.on('gridsUnaligned', () => log('The link was removed.')));
link = api.alignWith(totals);
return () => {
offs.forEach((off) => off());
link?.unlink();
totals?.destroy();
host?.remove();
totals = null;
host = null;
link = null;
};
}
export const actions = {
// Widen the Product column in the top grid. The bottom grid gets the same width.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'product')?.width ?? 160;
api.resizeColumn('product', width + 60);
},
// Move Amount to the second place.
move: (api: GridApi<Row>) => api.moveColumn('amount', 1),
// Hide or show the Region column.
region: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'region')?.hidden === true;
api.setColumnVisible('region', hidden);
},
// Remove or restore the link. Without it the two grids move on their own.
link: (api: GridApi<Row>, value?: string) => {
if (totals === null) return;
if (value === 'off') {
link?.unlink();
link = null;
} else if (link === null) link = api.alignWith(totals);
},
};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 Product</button>
<button type="button" :disabled="!api" @click="api && actions.move(api)">Move Amount first</button>
<button type="button" :disabled="!api" @click="api && actions.region(api)">Hide/Show Region</button>
<select
aria-label="Link"
:disabled="!api"
@change="api && actions.link(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>Linked</option>
<option value="off">Remove link</option>
</select>
</div>
<Grid style="height: 230px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
no: number | string;
customer: string;
product: string;
region: string;
qty: number | null;
price: number | null;
amount: number;
status: string;
}
// The global MaxGrid that the gallery frame loads. It builds the totals grid below.
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
};
const customers = [
'Emma Stone',
'Liam Carter',
'Olivia Reed',
'Noah Hayes',
'Ava Foster',
'Mason Clark',
];
const products = [
'Wireless earbuds',
'Laptop 14"',
'Smart watch',
'Tablet 11"',
'Power bank',
'Bluetooth speaker',
];
const regions = ['Austin', 'Boston', 'Denver', 'Seattle', 'Portland', 'Dallas'];
const statuses = ['Done', 'Shipping', 'Received'];
const prices = [29, 129, 89, 59, 24, 49];
const qtys = [3, 1, 2, 4, 5, 2];
const columns: GridOptions<Row>['columns'] = [
{ id: 'no', title: 'No.', width: 70, align: 'end' },
{ id: 'customer', title: 'Customer', width: 150 },
{ id: 'product', title: 'Product', width: 160 },
{ id: 'region', title: 'Region', width: 110 },
{ id: 'qty', title: 'Qty', width: 100, kind: 'number', align: 'end' },
{
id: 'price',
title: 'Unit price',
width: 130,
kind: 'number',
align: 'end',
formatValue: (v) => (v === null ? '' : `$${Number(v).toLocaleString('en-US')}`),
},
{
id: 'amount',
title: 'Amount',
width: 140,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{ id: 'status', title: 'Status', width: 120 },
];
// The top grid lists the orders; the bottom grid is one totals row with the same columns.
export const options: GridOptions<Row> = {
columns,
rows: customers.map((customer, i) => ({
no: i + 1,
customer,
product: products[i],
region: regions[i],
qty: qtys[i],
price: prices[i],
amount: prices[i] * qtys[i],
status: statuses[i % statuses.length],
})),
rowKey: 'no',
};
let totals: GridApi<Row> | null = null;
let host: HTMLElement | null = null;
let link: { unlink(): void } | null = null;
const totalRow: Row = {
no: 'Total',
customer: '',
product: '',
region: '',
qty: 17,
price: null,
amount: 848,
status: '',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const first = document.getElementById('grid');
host = document.createElement('div');
host.style.cssText = 'margin-top:6px';
if (first !== null) first.after(host);
else document.body.append(host);
totals = MaxGrid.createGrid(host, {
columns: columns.map((c) => ({ ...c, sortable: false })),
rows: [totalRow],
rowKey: 'no',
showHeader: false,
autoGridHeight: true,
ariaLabel: 'Totals grid',
});
const offs = [api, totals].map((grid, i) => {
const where = i === 0 ? 'Top' : 'Bottom';
return grid.on('gridsAligned', (e) =>
log(`${where} grid aligned (${e.count} grids${e.master ? ', master' : ''})`),
);
});
offs.push(totals.on('gridsUnaligned', () => log('The link was removed.')));
link = api.alignWith(totals);
return () => {
offs.forEach((off) => off());
link?.unlink();
totals?.destroy();
host?.remove();
totals = null;
host = null;
link = null;
};
}
export const actions = {
// Widen the Product column in the top grid. The bottom grid gets the same width.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'product')?.width ?? 160;
api.resizeColumn('product', width + 60);
},
// Move Amount to the second place.
move: (api: GridApi<Row>) => api.moveColumn('amount', 1),
// Hide or show the Region column.
region: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'region')?.hidden === true;
api.setColumnVisible('region', hidden);
},
// Remove or restore the link. Without it the two grids move on their own.
link: (api: GridApi<Row>, value?: string) => {
if (totals === null) return;
if (value === 'off') {
link?.unlink();
link = null;
} else if (link === null) link = api.alignWith(totals);
},
};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 Product</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.move(api)"
>Move Amount first</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.region(api)"
>Hide/Show Region</button>
<select
aria-label="Link"
[disabled]="!api"
(change)="api && actions.link(api, $any($event.target).value)"
>
<option value="on" selected>Linked</option>
<option value="off">Remove link</option>
</select>
</div>
<mx-grid style="height: 230px" [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 {
no: number | string;
customer: string;
product: string;
region: string;
qty: number | null;
price: number | null;
amount: number;
status: string;
}
// The global MaxGrid that the gallery frame loads. It builds the totals grid below.
declare const MaxGrid: {
createGrid(container: HTMLElement, options: GridOptions<Row>): GridApi<Row>;
};
const customers = [
'Emma Stone',
'Liam Carter',
'Olivia Reed',
'Noah Hayes',
'Ava Foster',
'Mason Clark',
];
const products = [
'Wireless earbuds',
'Laptop 14"',
'Smart watch',
'Tablet 11"',
'Power bank',
'Bluetooth speaker',
];
const regions = ['Austin', 'Boston', 'Denver', 'Seattle', 'Portland', 'Dallas'];
const statuses = ['Done', 'Shipping', 'Received'];
const prices = [29, 129, 89, 59, 24, 49];
const qtys = [3, 1, 2, 4, 5, 2];
const columns: GridOptions<Row>['columns'] = [
{ id: 'no', title: 'No.', width: 70, align: 'end' },
{ id: 'customer', title: 'Customer', width: 150 },
{ id: 'product', title: 'Product', width: 160 },
{ id: 'region', title: 'Region', width: 110 },
{ id: 'qty', title: 'Qty', width: 100, kind: 'number', align: 'end' },
{
id: 'price',
title: 'Unit price',
width: 130,
kind: 'number',
align: 'end',
formatValue: (v) => (v === null ? '' : `$${Number(v).toLocaleString('en-US')}`),
},
{
id: 'amount',
title: 'Amount',
width: 140,
kind: 'number',
align: 'end',
formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
},
{ id: 'status', title: 'Status', width: 120 },
];
// The top grid lists the orders; the bottom grid is one totals row with the same columns.
export const options: GridOptions<Row> = {
columns,
rows: customers.map((customer, i) => ({
no: i + 1,
customer,
product: products[i],
region: regions[i],
qty: qtys[i],
price: prices[i],
amount: prices[i] * qtys[i],
status: statuses[i % statuses.length],
})),
rowKey: 'no',
};
let totals: GridApi<Row> | null = null;
let host: HTMLElement | null = null;
let link: { unlink(): void } | null = null;
const totalRow: Row = {
no: 'Total',
customer: '',
product: '',
region: '',
qty: 17,
price: null,
amount: 848,
status: '',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const first = document.getElementById('grid');
host = document.createElement('div');
host.style.cssText = 'margin-top:6px';
if (first !== null) first.after(host);
else document.body.append(host);
totals = MaxGrid.createGrid(host, {
columns: columns.map((c) => ({ ...c, sortable: false })),
rows: [totalRow],
rowKey: 'no',
showHeader: false,
autoGridHeight: true,
ariaLabel: 'Totals grid',
});
const offs = [api, totals].map((grid, i) => {
const where = i === 0 ? 'Top' : 'Bottom';
return grid.on('gridsAligned', (e) =>
log(`${where} grid aligned (${e.count} grids${e.master ? ', master' : ''})`),
);
});
offs.push(totals.on('gridsUnaligned', () => log('The link was removed.')));
link = api.alignWith(totals);
return () => {
offs.forEach((off) => off());
link?.unlink();
totals?.destroy();
host?.remove();
totals = null;
host = null;
link = null;
};
}
export const actions = {
// Widen the Product column in the top grid. The bottom grid gets the same width.
widen: (api: GridApi<Row>) => {
const width = api.getColumnState().find((s) => s.id === 'product')?.width ?? 160;
api.resizeColumn('product', width + 60);
},
// Move Amount to the second place.
move: (api: GridApi<Row>) => api.moveColumn('amount', 1),
// Hide or show the Region column.
region: (api: GridApi<Row>) => {
const hidden = api.getColumnState().find((s) => s.id === 'region')?.hidden === true;
api.setColumnVisible('region', hidden);
},
// Remove or restore the link. Without it the two grids move on their own.
link: (api: GridApi<Row>, value?: string) => {
if (totals === null) return;
if (value === 'off') {
link?.unlink();
link = null;
} else if (link === null) link = api.alignWith(totals);
},
};