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

그룹으로 묶은 표도 걸러져요Filtering grouped rows

지역별로 묶은 표에 필터를 걸면 그룹 줄의 개수와 합계가 걸러진 행 기준으로 다시 계산돼요. 맞는 행이 없는 그룹은 사라지니, 어디에 해당 건이 몰려 있는지 한눈에 보여요.Filter a table grouped by region and the group counts and totals recompute from the matching rows only. Groups with no match disappear.

활용Intermediate
직접 써 보기Live preview그룹으로 묶은 표도 걸러져요Filtering grouped rows

코드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="cond">
      <option value="all" selected>조건 없음 (전체)</option>
      <option value="o1">담당: 김민준</option>
      <option value="o2">담당: 이서연</option>
      <option value="o3">담당: 박지호</option>
      <option value="long">소요 7시간 이상</option>
    </select>
    <button type="button" id="openAll">그룹 모두 펼치기</button>
  </div>
  <div id="grid" style="height: 470px"></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('cond').addEventListener('change', (event) => actions.cond(api, event.target.value));
document.getElementById('openAll').addEventListener('click', () => actions.openAll(api));
example.js
const regions = ['서울', '부산', '대구', '제주'];
const owners = ['김민준', '이서연', '박지호'];
const products = ['A/S 접수', '설치 지원', '정기 점검', '원격 상담'];
// 행을 지역별로 묶은 상태에서 필터를 걸어요. 그룹 줄의 개수와 합계는 필터에 걸린 행만으로 다시 계산되고,
// 맞는 행이 하나도 없는 그룹은 줄 자체가 사라져요.
export const options = {
  columns: [
    { id: 'region', title: '지역', width: 170, aggregate: 'rowCount' },
    { id: 'owner', title: '담당', width: 110 },
    { id: 'product', title: '업무', width: 140 },
    {
      id: 'hours',
      title: '소요(시간)',
      kind: 'number',
      width: 130,
      align: 'end',
      aggregate: 'sum',
    },
  ],
  rows: Array.from({ length: 20 }, (_, i) => ({
    id: i + 1,
    region: regions[(i * 3) % 4],
    owner: owners[i % 3],
    product: products[(i * 5) % 4],
    hours: 1 + ((i * 7) % 9),
  })),
  rowKey: 'id',
  grouping: { by: ['region'], expandDepth: 0 },
  summary: { label: '조건에 맞는 전체' },
};
export function setup(api, log) {
  const off = api.on('filterChanged', () => log({
    ko: `보이는 줄 ${api.getVisibleRowCount()}개(그룹 줄 포함)`,
    en: `${api.getVisibleRowCount()} rows visible (including group rows)`,
  }));
  return () => off();
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 담당자 이름으로 바꿔 써요.
const OWNER_BY_KEY = { o1: '김민준', o2: '이서연', o3: '박지호' };
export const actions = {
  // 한 번에 조건 하나만 걸어요. '조건 없음'이 곧 필터 해제라서 화면의 선택과 실제 필터가 늘 같아요.
  cond: (api, value) => {
    if (value === 'long') {
      api.setFilterModel({
        match: 'all',
        items: [{ columnId: 'hours', operator: 'gte', value: 7 }],
      });
    }
    else if (value && OWNER_BY_KEY[value]) {
      api.setFilterModel({
        match: 'all',
        items: [{ columnId: 'owner', operator: 'equals', value: OWNER_BY_KEY[value] }],
      });
    }
    else {
      api.setFilterModel(null);
    }
  },
  openAll: (api) => api.expandAll(),
};

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="Condition" id="cond">
      <option value="all" selected>No filter</option>
      <option value="o1">Owner: Liam Carter</option>
      <option value="o2">Owner: Emma Stone</option>
      <option value="o3">Owner: Noah Kim</option>
      <option value="long">7+ hours</option>
    </select>
    <button type="button" id="openAll">Expand all groups</button>
  </div>
  <div id="grid" style="height: 470px"></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('cond').addEventListener('change', (event) => actions.cond(api, event.target.value));
document.getElementById('openAll').addEventListener('click', () => actions.openAll(api));
example.js
const regions = ['New York', 'Boston', 'Austin', 'Seattle'];
const owners = ['Liam Carter', 'Emma Stone', 'Noah Kim'];
const products = [
  'Service request',
  'Installation support',
  'Regular inspection',
  'Remote consulting',
];
// Filter while the rows are grouped by region. The counts and totals on group rows are recomputed from the matching rows only,
// and a group with no matching row disappears completely.
export const options = {
  columns: [
    { id: 'region', title: 'Region', width: 170, aggregate: 'rowCount' },
    { id: 'owner', title: 'Owner', width: 130 },
    { id: 'product', title: 'Task', width: 170 },
    {
      id: 'hours',
      title: 'Time (hours)',
      kind: 'number',
      width: 140,
      align: 'end',
      aggregate: 'sum',
    },
  ],
  rows: Array.from({ length: 20 }, (_, i) => ({
    id: i + 1,
    region: regions[(i * 3) % 4],
    owner: owners[i % 3],
    product: products[(i * 5) % 4],
    hours: 1 + ((i * 7) % 9),
  })),
  rowKey: 'id',
  grouping: { by: ['region'], expandDepth: 0 },
  summary: { label: 'Total matching' },
};
export function setup(api, log) {
  const off = api.on('filterChanged', () => log(`${api.getVisibleRowCount()} rows visible (including group rows)`));
  return () => off();
}
// The control values are language-neutral keys; map them to the values in the table.
const OWNER_BY_KEY = {
  o1: 'Liam Carter',
  o2: 'Emma Stone',
  o3: 'Noah Kim',
};
export const actions = {
  // Only one condition at a time. "No filter" means clearing the filter, so the choice on screen always matches the real filter.
  cond: (api, value) => {
    if (value === 'long') {
      api.setFilterModel({
        match: 'all',
        items: [{ columnId: 'hours', operator: 'gte', value: 7 }],
      });
    }
    else if (value && OWNER_BY_KEY[value]) {
      api.setFilterModel({
        match: 'all',
        items: [{ columnId: 'owner', operator: 'equals', value: OWNER_BY_KEY[value] }],
      });
    }
    else {
      api.setFilterModel(null);
    }
  },
  openAll: (api) => api.expandAll(),
};