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

필터·정렬해도 선택 유지, 저장했다가 복원Keep selection through filter and sort, save and restore

선택은 행마다 붙은 고유 번호로 기억해서, 필터로 가려지거나 정렬로 자리가 바뀌어도 고른 행이 그대로 남아요. 고른 번호를 저장해 두었다가 그대로 다시 고를 수도 있어요.Selection is remembered by each row's unique number, so filtering or sorting does not lose it. You can also save the chosen numbers and pick the same rows again later.

활용Intermediate
직접 써 보기Live preview필터·정렬해도 선택 유지, 저장했다가 복원Keep selection through filter and sort, save and restore

코드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">
    <select aria-label="상태 필터" id="status">
      <option value="all" selected>필터 해제 (전체)</option>
      <option value="paid">결제 완료</option>
      <option value="pending">대기</option>
      <option value="overdue">연체</option>
    </select>
    <button type="button" id="sortByAmount">금액 큰 순 정렬</button>
    <button type="button" id="save">지금 선택 저장</button>
    <button type="button" id="restore">저장한 선택 복원</button>
    <button type="button" id="clear">선택 지우기</button>
  </div>
  <div id="grid" style="height: 380px"></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('status').addEventListener('change', (event) => actions.status(api, event.target.value));
document.getElementById('sortByAmount').addEventListener('click', () => actions.sortByAmount(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const customers = [
  '한빛물류',
  '푸른하늘식품',
  '북극성무역',
  '다온상사',
  '새벽농원',
  '모아패션',
  '바다유통',
  '해든전자',
];
const statuses = ['결제 완료', '대기', '연체'];
export const options = {
  columns: [
    { id: 'customer', title: '고객사', width: 150 },
    { id: 'status', title: '상태', width: 110 },
    {
      id: 'amount',
      title: '금액(원)',
      kind: 'number',
      width: 120,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
  ],
  rows: customers.map((customer, i) => ({
    id: i + 1,
    customer,
    status: statuses[(i * 2) % 3],
    amount: 430000 + ((i * 613000) % 2900000),
  })),
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
};
let saved = [];
let say = () => { };
// 선택은 행의 키(id)로 기억해요. 필터로 가려지거나 정렬로 자리가 바뀌어도 고른 행은 그대로 고른 채로 남고,
// 다시 보이면 체크된 모습으로 돌아와요. 보이는 것만 세려면 getVisibleIndexOfKey가 0 이상인지 보면 돼요.
function report(api, log) {
  const keys = api.getSelectedKeys();
  const shown = keys.filter((key) => api.getVisibleIndexOfKey(key) >= 0);
  log({
    ko: `고른 행 ${keys.length}개 (지금 보이는 것 ${shown.length}개)`,
    en: `Selected rows: ${keys.length} (${shown.length} visible now)`,
  });
}
export function setup(api, log) {
  say = log;
  saved = [];
  const offs = [
    api.on('selectionChanged', () => report(api, log)),
    api.on('filterChanged', () => report(api, log)),
  ];
  return () => offs.forEach((off) => off());
}
// 컨트롤 값은 영문 id(paid·pending·overdue)이고, 표의 상태 글자로 바꿔서 걸러요.
const statusOf = { paid: '결제 완료', pending: '대기', overdue: '연체' };
export const actions = {
  status: (api, value) => api.setFilterModel(value && statusOf[value]
    ? {
      match: 'all',
      items: [{ columnId: 'status', operator: 'equals', value: statusOf[value] }],
    }
    : null),
  sortByAmount: (api) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
  save: (api) => {
    saved = api.getSelectedKeys();
    say({
      ko: `고른 행 ${saved.length}개의 키를 저장했어요: ${saved.join(', ') || '없음'}`,
      en: `Saved the keys of ${saved.length} selected rows: ${saved.join(', ') || 'none'}`,
    });
  },
  restore: (api) => {
    api.setSelectedKeys(saved);
    say({
      ko: `저장한 ${saved.length}개를 다시 골랐어요`,
      en: `Selected the ${saved.length} saved rows again`,
    });
  },
  clear: (api) => api.clearSelection(),
};

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">
    <select aria-label="Status filter" id="status">
      <option value="all" selected>No filter (all)</option>
      <option value="paid">Paid</option>
      <option value="pending">Pending</option>
      <option value="overdue">Overdue</option>
    </select>
    <button type="button" id="sortByAmount">Sort by amount</button>
    <button type="button" id="save">Save selection</button>
    <button type="button" id="restore">Restore saved selection</button>
    <button type="button" id="clear">Clear selection</button>
  </div>
  <div id="grid" style="height: 380px"></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('status').addEventListener('change', (event) => actions.status(api, event.target.value));
document.getElementById('sortByAmount').addEventListener('click', () => actions.sortByAmount(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const customers = [
  'Bright Logistics',
  'Blue Sky Foods',
  'Polaris Trading',
  'Dawn Corp',
  'Sunrise Farm',
  'Moa Fashion',
  'Ocean Retail',
  'Haeden Electronics',
];
const statuses = ['Paid', 'Pending', 'Overdue'];
// Control values are English ids (paid / pending / overdue); they are mapped to the status names in the table.
const STATUS_VALUES = {
  paid: 'Paid',
  pending: 'Pending',
  overdue: 'Overdue',
};
export const options = {
  columns: [
    { id: 'customer', title: 'Customer', width: 170 },
    { id: 'status', title: 'Status', width: 110 },
    {
      id: 'amount',
      title: 'Amount ($)',
      kind: 'number',
      width: 120,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('en-US'),
    },
  ],
  rows: customers.map((customer, i) => ({
    id: i + 1,
    customer,
    status: statuses[(i * 2) % 3],
    amount: 430 + ((i * 613) % 2900),
  })),
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
};
let saved = [];
let say = () => { };
// The selection is remembered by row key (id). Even when a filter hides a row or sorting moves it, the selected row stays selected,
// and it comes back ticked when shown again. To count only visible rows, check that getVisibleIndexOfKey is 0 or more.
function report(api, log) {
  const keys = api.getSelectedKeys();
  const shown = keys.filter((key) => api.getVisibleIndexOfKey(key) >= 0);
  log(`Selected rows: ${keys.length} (${shown.length} visible now)`);
}
export function setup(api, log) {
  say = log;
  saved = [];
  const offs = [
    api.on('selectionChanged', () => report(api, log)),
    api.on('filterChanged', () => report(api, log)),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  status: (api, value) => api.setFilterModel(value && STATUS_VALUES[value]
    ? {
      match: 'all',
      items: [
        { columnId: 'status', operator: 'equals', value: STATUS_VALUES[value] },
      ],
    }
    : null),
  sortByAmount: (api) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
  save: (api) => {
    saved = api.getSelectedKeys();
    say(`Saved the keys of ${saved.length} selected rows: ${saved.join(', ') || 'none'}`);
  },
  restore: (api) => {
    api.setSelectedKeys(saved);
    say(`Selected the ${saved.length} saved rows again`);
  },
  clear: (api) => api.clearSelection(),
};