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

코드로 필터 트리 걸고 읽고 지우기Set, read and clear a filter tree from code

setFilterTree로 겹친 조건을 코드로 걸고, getFilterTree로 읽고, null을 주면 지워요. 컬럼·연산자·값이 틀린 트리는 상태를 바꾸기 전에 invalid-option 오류로 거절돼요. 빌더 화면 없이도 쓸 수 있어서 filterBuilder 옵션은 필요 없어요.setFilterTree sets a nested condition from code, getFilterTree reads it and null clears it. A tree with a wrong column, operator or value is rejected with an invalid-option error before any state changes. It works without the builder dialog, so the filterBuilder option is not needed.

심화Advanced
직접 써 보기Live preview코드로 필터 트리 걸고 읽고 지우기Set, read and clear a filter tree from code

코드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="treeA">트리 A 걸기</button>
    <button type="button" id="treeB">트리 B 걸기</button>
    <button type="button" id="read">트리 읽기</button>
    <button type="button" id="invalid">잘못된 트리 걸기</button>
    <button type="button" id="clear">지우기</button>
  </div>
  <div id="grid" style="height: 460px"></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('treeA').addEventListener('click', () => actions.treeA(api));
document.getElementById('treeB').addEventListener('click', () => actions.treeB(api));
document.getElementById('read').addEventListener('click', () => actions.read(api));
document.getElementById('invalid').addEventListener('click', () => actions.invalid(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
const depts = ['개발', '디자인', '영업', '인사'];
// 코드로 트리를 걸고(setFilterTree), 읽고(getFilterTree), 지워요. 빌더 화면 없이도 쓸 수 있어서 옵션은 필요 없어요.
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 110 },
    { id: 'dept', title: '부서', width: 100 },
    { id: 'salary', title: '연봉(만원)', kind: 'number', width: 130, align: 'end' },
  ],
  rows: Array.from({ length: 24 }, (_, i) => ({
    id: i + 1,
    name: names[i % 6],
    dept: depts[(i * 3) % 4],
    salary: 3600 + ((i * 530) % 4600),
  })),
  rowKey: 'id',
};
let say = () => undefined;
// 개발 또는 디자인이면서 연봉이 5000 이상.
const A = {
  match: 'all',
  children: [
    {
      match: 'any',
      children: [
        { columnId: 'dept', operator: 'equals', value: '개발' },
        { columnId: 'dept', operator: 'equals', value: '디자인' },
      ],
    },
    { columnId: 'salary', operator: 'gte', value: 5000 },
  ],
};
// 영업이 아니고(NOT), 이름에 "서"가 들어 있지 않은 사람.
const B = {
  match: 'all',
  children: [
    {
      match: 'all',
      not: true,
      children: [{ columnId: 'dept', operator: 'equals', value: '영업' }],
    },
    { columnId: 'name', operator: 'notContains', value: '서' },
  ],
};
export function setup(api, log) {
  say = log;
  log({
    ko: '버튼으로 트리를 걸어 보세요. 잘못된 트리는 상태를 바꾸기 전에 오류로 거절돼요.',
    en: 'Use the buttons to set a tree. An invalid tree is rejected with an error before anything changes.',
  });
  const off = api.on('filterChanged', () => log({
    ko: `${api.getVisibleRowCount()}행이 보여요`,
    en: `${api.getVisibleRowCount()} rows shown`,
  }));
  return () => {
    off();
    say = () => undefined;
  };
}
export const actions = {
  treeA: (api) => api.setFilterTree(A),
  treeB: (api) => api.setFilterTree(B),
  read: (api) => {
    const tree = api.getFilterTree();
    say(tree === null ? { ko: '걸린 트리가 없어요.', en: 'No tree is set.' } : JSON.stringify(tree));
  },
  invalid: (api) => {
    try {
      api.setFilterTree({
        match: 'all',
        children: [{ columnId: 'nope', operator: 'equals', value: 1 }],
      });
    }
    catch (error) {
      say(error instanceof Error
        ? `${error.code ?? 'error'}: ${error.message}`
        : String(error));
    }
  },
  clear: (api) => api.setFilterTree(null),
};

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="treeA">Set tree A</button>
    <button type="button" id="treeB">Set tree B</button>
    <button type="button" id="read">Read tree</button>
    <button type="button" id="invalid">Set invalid tree</button>
    <button type="button" id="clear">Clear</button>
  </div>
  <div id="grid" style="height: 460px"></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('treeA').addEventListener('click', () => actions.treeA(api));
document.getElementById('treeB').addEventListener('click', () => actions.treeB(api));
document.getElementById('read').addEventListener('click', () => actions.read(api));
document.getElementById('invalid').addEventListener('click', () => actions.invalid(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Brooks',
  'Olivia Reed',
  'Ethan Hayes',
  'Sophia Lane',
];
const depts = ['Dev', 'Design', 'Sales', 'HR'];
// Set a tree from code (setFilterTree), read it (getFilterTree) and clear it. This works without the builder dialog, so no option is needed.
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 130 },
    { id: 'dept', title: 'Dept', width: 100 },
    {
      id: 'salary',
      title: 'Salary (USD)',
      kind: 'number',
      width: 140,
      align: 'end',
      formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
    },
  ],
  rows: Array.from({ length: 24 }, (_, i) => ({
    id: i + 1,
    name: names[i % 6],
    dept: depts[(i * 3) % 4],
    salary: 36000 + ((i * 5300) % 46000),
  })),
  rowKey: 'id',
};
let say = () => undefined;
// Dev or Design, and a salary of at least 50,000.
const A = {
  match: 'all',
  children: [
    {
      match: 'any',
      children: [
        { columnId: 'dept', operator: 'equals', value: 'Dev' },
        { columnId: 'dept', operator: 'equals', value: 'Design' },
      ],
    },
    { columnId: 'salary', operator: 'gte', value: 50000 },
  ],
};
// Not in Sales (NOT), and a name that does not contain "son".
const B = {
  match: 'all',
  children: [
    {
      match: 'all',
      not: true,
      children: [{ columnId: 'dept', operator: 'equals', value: 'Sales' }],
    },
    { columnId: 'name', operator: 'notContains', value: 'son' },
  ],
};
export function setup(api, log) {
  say = log;
  log('Use the buttons to set a tree. An invalid tree is rejected with an error before anything changes.');
  const off = api.on('filterChanged', () => log(`${api.getVisibleRowCount()} rows shown`));
  return () => {
    off();
    say = () => undefined;
  };
}
export const actions = {
  treeA: (api) => api.setFilterTree(A),
  treeB: (api) => api.setFilterTree(B),
  read: (api) => {
    const tree = api.getFilterTree();
    say(tree === null ? 'No tree is set.' : JSON.stringify(tree));
  },
  invalid: (api) => {
    try {
      api.setFilterTree({
        match: 'all',
        children: [{ columnId: 'nope', operator: 'equals', value: 1 }],
      });
    }
    catch (error) {
      say(error instanceof Error
        ? `${error.code ?? 'error'}: ${error.message}`
        : String(error));
    }
  },
  clear: (api) => api.setFilterTree(null),
};