본문으로 건너뛰기Skip to content
예제 첫화면Examples home

주문 내역과 합계 그리드를 나란히 맞추기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.

심화Advanced
직접 써 보기Live preview주문 내역과 합계 그리드를 나란히 맞추기Align an order list with a totals grid

코드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)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<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>
main.js
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));
example.js
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);
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<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>
main.js
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));
example.js
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);
  },
};