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

그룹을 접어도 남길 컬럼 정하기Choose which column stays when a group collapses

헤더 그룹에 collapsible을 주면 제목 옆 ▾로 접고 펼 수 있고, collapsedKeep에 적은 컬럼은 접어도 남아요. collapseHeaderGroup, expandHeaderGroup, isHeaderGroupCollapsed로 코드에서도 다루고, beforeHeaderGroupToggle이 false를 돌려주면 접기·펴기를 막아요.Give a header group collapsible and it folds with the arrow in its title, and the columns listed in collapsedKeep stay when it folds. Use collapseHeaderGroup, expandHeaderGroup and isHeaderGroupCollapsed from code, and beforeHeaderGroupToggle blocks the toggle when it returns false.

입문Beginner
직접 써 보기Live preview그룹을 접어도 남길 컬럼 정하기Choose which column stays when a group collapses

코드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="collapseContact">연락처 접기</button>
    <button type="button" id="expandAll">모두 펴기</button>
    <button type="button" id="check">접힘 상태 보기</button>
    <select aria-label="접기·펴기" id="lock">
      <option value="free" selected>허용</option>
      <option value="locked">막기</option>
    </select>
  </div>
  <div id="grid" style="height: 330px"></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('collapseContact').addEventListener('click', () => actions.collapseContact(api));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('check').addEventListener('click', () => actions.check(api));
document.getElementById('lock').addEventListener('change', (event) => actions.lock(api, event.target.value));
example.js
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후', '윤서아', '임태민'];
const cities = ['서울', '부산', '대구', '인천', '광주'];
const depts = ['개발', '디자인', '영업', '인사'];
const roles = ['사원', '대리', '과장', '팀장'];
// 연락처 그룹은 접으면 collapsedKeep에 적은 이메일만 남고, 업무 그룹은 첫 컬럼(부서)만 남아요.
// beforeHeaderGroupToggle은 false를 돌려주면 접기·펴기를 막아요.
let locked = false;
export const options = {
  columns: [
    { id: 'id', title: '번호', width: 70, align: 'end' },
    { id: 'name', title: '이름', width: 110 },
    { id: 'email', title: '이메일', width: 190 },
    { id: 'phone', title: '전화', width: 130 },
    { id: 'city', title: '지역', width: 90 },
    { id: 'dept', title: '부서', width: 100 },
    { id: 'role', title: '직급', width: 90 },
  ],
  headerGroups: [
    {
      id: 'contact',
      title: '연락처',
      collapsible: true,
      collapsedKeep: ['email'],
      children: ['email', 'phone', 'city'],
    },
    { id: 'work', title: '업무', collapsible: true, children: ['dept', 'role'] },
  ],
  rows: Array.from({ length: 10 }, (_, i) => ({
    id: i + 1,
    name: names[i % names.length],
    email: `user${i + 1}@example.com`,
    phone: `010-${String(1000 + i * 37).slice(-4)}-${String(2000 + i * 91).slice(-4)}`,
    city: cities[(i * 2) % cities.length],
    dept: depts[(i * 3) % depts.length],
    role: roles[i % roles.length],
  })),
  rowKey: 'id',
  hooks: { beforeHeaderGroupToggle: () => !locked },
};
let say = () => { };
export function setup(api, log) {
  say = log;
  locked = false;
  log({
    ko: '그룹 제목 옆 ▾를 눌러 접어 보세요. 연락처는 이메일이 남아요.',
    en: 'Press the arrow next to a group title. The contact group keeps its email column.',
  });
  const off = api.on('headerGroupToggled', ({ groupId, collapsed }) => log({
    ko: `${groupId} 그룹을 ${collapsed ? '접었어요' : '펼쳤어요'}`,
    en: `Group ${groupId} ${collapsed ? 'collapsed' : 'expanded'}`,
  }));
  return () => off();
}
export const actions = {
  collapseContact: (api) => api.collapseHeaderGroup('contact'),
  expandAll: (api) => {
    api.expandHeaderGroup('contact');
    api.expandHeaderGroup('work');
  },
  // isHeaderGroupCollapsed(id)는 지금 접혀 있는지 돌려줘요.
  check: (api) => say({
    ko: `연락처 접힘: ${api.isHeaderGroupCollapsed('contact')}, 업무 접힘: ${api.isHeaderGroupCollapsed('work')}`,
    en: `Contact collapsed: ${api.isHeaderGroupCollapsed('contact')}, Work collapsed: ${api.isHeaderGroupCollapsed('work')}`,
  }),
  lock: (_api, value) => {
    locked = value === 'locked';
    say({
      ko: locked ? '접기·펴기를 막았어요(훅이 false를 돌려줘요).' : '접기·펴기를 다시 허용했어요.',
      en: locked ? 'Toggling is blocked (the hook returns false).' : 'Toggling is allowed again.',
    });
  },
};

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="collapseContact">Collapse Contact</button>
    <button type="button" id="expandAll">Expand all</button>
    <button type="button" id="check">Show collapsed state</button>
    <select aria-label="Toggling" id="lock">
      <option value="free" selected>Allowed</option>
      <option value="locked">Blocked</option>
    </select>
  </div>
  <div id="grid" style="height: 330px"></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('collapseContact').addEventListener('click', () => actions.collapseContact(api));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('check').addEventListener('click', () => actions.check(api));
document.getElementById('lock').addEventListener('change', (event) => actions.lock(api, event.target.value));
example.js
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Hayes',
  'Olivia Reed',
  'Ethan Brooks',
  'Ava Foster',
  'Mason Clark',
  'Mia Turner',
];
const cities = ['Austin', 'Boston', 'Denver', 'Seattle', 'Portland'];
const depts = ['Dev', 'Design', 'Sales', 'HR'];
const roles = ['Associate', 'Senior', 'Lead', 'Manager'];
// The Contact group keeps only the email column named in collapsedKeep when collapsed, and Work keeps its first column (Dept).
// beforeHeaderGroupToggle blocks the toggle when it returns false.
let locked = false;
export const options = {
  columns: [
    { id: 'id', title: 'No.', width: 70, align: 'end' },
    { id: 'name', title: 'Name', width: 130 },
    { id: 'email', title: 'Email', width: 190 },
    { id: 'phone', title: 'Phone', width: 130 },
    { id: 'city', title: 'City', width: 100 },
    { id: 'dept', title: 'Dept', width: 100 },
    { id: 'role', title: 'Role', width: 110 },
  ],
  headerGroups: [
    {
      id: 'contact',
      title: 'Contact',
      collapsible: true,
      collapsedKeep: ['email'],
      children: ['email', 'phone', 'city'],
    },
    { id: 'work', title: 'Work', collapsible: true, children: ['dept', 'role'] },
  ],
  rows: Array.from({ length: 10 }, (_, i) => ({
    id: i + 1,
    name: names[i % names.length],
    email: `user${i + 1}@example.com`,
    phone: `555-${String(1000 + i * 37).slice(-4)}-${String(2000 + i * 91).slice(-4)}`,
    city: cities[(i * 2) % cities.length],
    dept: depts[(i * 3) % depts.length],
    role: roles[i % roles.length],
  })),
  rowKey: 'id',
  hooks: { beforeHeaderGroupToggle: () => !locked },
};
let say = () => { };
export function setup(api, log) {
  say = log;
  locked = false;
  log('Press the arrow next to a group title. The Contact group keeps its Email column.');
  const off = api.on('headerGroupToggled', ({ groupId, collapsed }) => log(`Group ${groupId} ${collapsed ? 'collapsed' : 'expanded'}`));
  return () => off();
}
export const actions = {
  collapseContact: (api) => api.collapseHeaderGroup('contact'),
  expandAll: (api) => {
    api.expandHeaderGroup('contact');
    api.expandHeaderGroup('work');
  },
  // isHeaderGroupCollapsed(id) tells whether the group is collapsed right now.
  check: (api) => say(`Contact collapsed: ${api.isHeaderGroupCollapsed('contact')}, Work collapsed: ${api.isHeaderGroupCollapsed('work')}`),
  lock: (_api, value) => {
    locked = value === 'locked';
    say(locked ? 'Toggling is blocked (the hook returns false).' : 'Toggling is allowed again.');
  },
};