표의 선택·정렬을 화면 상태와 맞추기Keep the grid's selection and sort in step with screen state
표가 고른 행과 정렬을 알려 주면 화면이 그 값을 자기 상태로 들고 있고, 화면이 상태를 바꾸면 표도 따라 바뀌어요. React, Vue, Angular 탭에는 각 프레임워크의 방식으로 쓴 같은 예제가 들어 있어요.The grid reports the chosen rows and the sort, the screen keeps them as its own state, and when the screen changes its state the grid follows. The React, Vue and Angular tabs hold the same example written the way each framework does it.
실행 화면은 JavaScript 버전이에요. 아래 탭의 React·Vue·Angular 코드는 같은 예제를 각 프레임워크로 직접 쓴 코드예요.The preview runs the JavaScript version. The React, Vue, Angular tabs below hold the same example written for each framework.
코드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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="selectThree">앞의 3명 고르기</button>
<button type="button" id="sortBySalary">월급 큰 순</button>
<button type="button" id="reset">처음으로</button>
</div>
<div id="grid" style="height: 420px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api);
document.getElementById('selectThree').addEventListener('click', () => actions.selectThree(api));
document.getElementById('sortBySalary').addEventListener('click', () => actions.sortBySalary(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
export const options = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [
{ id: 1, name: '김민준', dept: '개발팀', salary: 520 },
{ id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
{ id: 3, name: '박지호', dept: '영업팀', salary: 450 },
{ id: 4, name: '최유나', dept: '개발팀', salary: 610 },
{ id: 5, name: '정도윤', dept: '영업팀', salary: 390 },
{ id: 6, name: '한소희', dept: '디자인팀', salary: 540 },
],
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// 표가 고른 행과 정렬을 알려 주면, 화면(바깥)은 그 값을 자기 상태로 들고 있어요.
// 거꾸로 화면이 상태를 바꾸면 표도 따라 바뀌어요. 아래 코드는 이 JavaScript 버전이에요.
const state = { selected: [], sort: [] };
let line = null;
/** 정렬 상태를 화면에 보여 줄 말로 바꿔요. 예: '월급 ▼'. 모든 탭이 같은 말을 써요. */
export function sortWords(sort, en = false) {
const names = en
? { name: 'Name', dept: 'Department', salary: 'Pay' }
: { name: '이름', dept: '부서', salary: '월급' };
return (sort
.map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(', ') || (en ? 'none' : '없음'));
}
const show = () => {
if (!line)
return;
line.textContent = L(`고른 행 ${state.selected.length}개 · 정렬 ${sortWords(state.sort)}`, `${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`);
};
export function setup(api) {
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
state.selected = [];
state.sort = [];
show();
const offs = [
api.on('selectionChanged', ({ selectedKeys }) => {
state.selected = selectedKeys;
show();
}),
api.on('sortChanged', ({ sortModel }) => {
state.sort = sortModel;
show();
}),
];
return () => {
offs.forEach((off) => off());
line?.remove();
line = null;
};
}
export const actions = {
selectThree: (api) => api.setSelectedKeys([1, 2, 3]),
sortBySalary: (api) => api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
reset: (api) => {
api.clearSelection();
api.setSortModel([]);
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>표의 선택·정렬을 화면 상태와 맞추기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="selectThree">앞의 3명 고르기</button>
<button type="button" id="sortBySalary">월급 큰 순</button>
<button type="button" id="reset">처음으로</button>
</div>
<div id="grid" style="height: 420px"></div>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const options = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [
{ id: 1, name: '김민준', dept: '개발팀', salary: 520 },
{ id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
{ id: 3, name: '박지호', dept: '영업팀', salary: 450 },
{ id: 4, name: '최유나', dept: '개발팀', salary: 610 },
{ id: 5, name: '정도윤', dept: '영업팀', salary: 390 },
{ id: 6, name: '한소희', dept: '디자인팀', salary: 540 },
],
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// 표가 고른 행과 정렬을 알려 주면, 화면(바깥)은 그 값을 자기 상태로 들고 있어요.
// 거꾸로 화면이 상태를 바꾸면 표도 따라 바뀌어요. 아래 코드는 이 JavaScript 버전이에요.
const state = { selected: [], sort: [] };
let line = null;
/** 정렬 상태를 화면에 보여 줄 말로 바꿔요. 예: '월급 ▼'. 모든 탭이 같은 말을 써요. */
function sortWords(sort, en = false) {
const names = en
? { name: 'Name', dept: 'Department', salary: 'Pay' }
: { name: '이름', dept: '부서', salary: '월급' };
return (sort
.map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(', ') || (en ? 'none' : '없음'));
}
const show = () => {
if (!line)
return;
line.textContent = L(`고른 행 ${state.selected.length}개 · 정렬 ${sortWords(state.sort)}`, `${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`);
};
function setup(api) {
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
state.selected = [];
state.sort = [];
show();
const offs = [
api.on('selectionChanged', ({ selectedKeys }) => {
state.selected = selectedKeys;
show();
}),
api.on('sortChanged', ({ sortModel }) => {
state.sort = sortModel;
show();
}),
];
return () => {
offs.forEach((off) => off());
line?.remove();
line = null;
};
}
const actions = {
selectThree: (api) => api.setSelectedKeys([1, 2, 3]),
sortBySalary: (api) => api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
reset: (api) => {
api.clearSelection();
api.setSortModel([]);
},
};
options.ariaLabel = "표의 선택·정렬을 화면 상태와 맞추기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api);
document.getElementById('selectThree').addEventListener('click', () => actions.selectThree(api));
document.getElementById('sortBySalary').addEventListener('click', () => actions.sortBySalary(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Grid, useGridApi, type RowKey, type SortItem } from '@maxgrid/react';
import { useState } from 'react';
import { options, sortWords, type Row } from './example';
// 표가 고른 행과 정렬을 알려 주면 React 상태에 담아 두고, 버튼은 표 쪽(api)을 바꿔요.
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
const [selected, setSelected] = useState<RowKey[]>([]);
const [sort, setSort] = useState<SortItem[]>([]);
return (
<>
<div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
<button type="button" disabled={!api} onClick={() => api?.setSelectedKeys([1, 2, 3])}>
앞의 3명 고르기
</button>
<button
type="button"
disabled={!api}
onClick={() => api?.setSortModel([{ columnId: 'salary', direction: 'desc' }])}
>
월급 큰 순
</button>
<button
type="button"
disabled={!api}
onClick={() => {
api?.clearSelection();
api?.setSortModel([]);
}}
>
처음으로
</button>
</div>
<div style={{ height: 260 }}>
<Grid<Row>
ref={gridRef}
options={options}
onSelectionChanged={({ selectedKeys }) => setSelected(selectedKeys)}
onSortChanged={({ sortModel }) => setSort(sortModel)}
/>
</div>
<p>
고른 행 {selected.length}개 · 정렬 {sortWords(sort)}
</p>
</>
);
}import type { GridApi, GridOptions, RowKey, SortItem } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [
{ id: 1, name: '김민준', dept: '개발팀', salary: 520 },
{ id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
{ id: 3, name: '박지호', dept: '영업팀', salary: 450 },
{ id: 4, name: '최유나', dept: '개발팀', salary: 610 },
{ id: 5, name: '정도윤', dept: '영업팀', salary: 390 },
{ id: 6, name: '한소희', dept: '디자인팀', salary: 540 },
],
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// 표가 고른 행과 정렬을 알려 주면, 화면(바깥)은 그 값을 자기 상태로 들고 있어요.
// 거꾸로 화면이 상태를 바꾸면 표도 따라 바뀌어요. 아래 코드는 이 JavaScript 버전이에요.
const state: { selected: RowKey[]; sort: SortItem[] } = { selected: [], sort: [] };
let line: HTMLElement | null = null;
/** 정렬 상태를 화면에 보여 줄 말로 바꿔요. 예: '월급 ▼'. 모든 탭이 같은 말을 써요. */
export function sortWords(sort: readonly SortItem[], en = false): string {
const names: Record<string, string> = en
? { name: 'Name', dept: 'Department', salary: 'Pay' }
: { name: '이름', dept: '부서', salary: '월급' };
return (
sort
.map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(', ') || (en ? 'none' : '없음')
);
}
const show = (): void => {
if (!line) return;
line.textContent = L(
`고른 행 ${state.selected.length}개 · 정렬 ${sortWords(state.sort)}`,
`${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`,
);
};
export function setup(api: GridApi<Row>) {
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
state.selected = [];
state.sort = [];
show();
const offs = [
api.on('selectionChanged', ({ selectedKeys }) => {
state.selected = selectedKeys;
show();
}),
api.on('sortChanged', ({ sortModel }) => {
state.sort = sortModel;
show();
}),
];
return () => {
offs.forEach((off) => off());
line?.remove();
line = null;
};
}
export const actions = {
selectThree: (api: GridApi<Row>) => api.setSelectedKeys([1, 2, 3]),
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
reset: (api: GridApi<Row>) => {
api.clearSelection();
api.setSortModel([]);
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { Grid, type RowKey, type SortItem } from '@maxgrid/vue';
import { computed, ref } from 'vue';
import { options, sortWords } from './example';
// v-model로 연결하면 표와 이 화면의 상태가 서로 따라가요. 바깥에서 값을 바꾸면 표도 바뀌어요.
const selected = ref<RowKey[]>([]);
const sort = ref<SortItem[]>([]);
const summary = computed(() => {
return `고른 행 ${selected.value.length}개 · 정렬 ${sortWords(sort.value)}`;
});
const selectThree = () => (selected.value = [1, 2, 3]);
const sortBySalary = () => (sort.value = [{ columnId: 'salary', direction: 'desc' }]);
const reset = () => {
selected.value = [];
sort.value = [];
};
</script>
<template>
<div class="bar">
<button type="button" @click="selectThree">앞의 3명 고르기</button>
<button type="button" @click="sortBySalary">월급 큰 순</button>
<button type="button" @click="reset">처음으로</button>
</div>
<Grid
style="height: 260px"
:options="options"
v-model:selectedKeys="selected"
v-model:sortModel="sort"
/>
<p>{{ summary }}</p>
</template>
<style scoped>
.bar {
display: flex;
gap: 8px;
margin-bottom: 8px;
}
</style>import type { GridApi, GridOptions, RowKey, SortItem } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [
{ id: 1, name: '김민준', dept: '개발팀', salary: 520 },
{ id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
{ id: 3, name: '박지호', dept: '영업팀', salary: 450 },
{ id: 4, name: '최유나', dept: '개발팀', salary: 610 },
{ id: 5, name: '정도윤', dept: '영업팀', salary: 390 },
{ id: 6, name: '한소희', dept: '디자인팀', salary: 540 },
],
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// 표가 고른 행과 정렬을 알려 주면, 화면(바깥)은 그 값을 자기 상태로 들고 있어요.
// 거꾸로 화면이 상태를 바꾸면 표도 따라 바뀌어요. 아래 코드는 이 JavaScript 버전이에요.
const state: { selected: RowKey[]; sort: SortItem[] } = { selected: [], sort: [] };
let line: HTMLElement | null = null;
/** 정렬 상태를 화면에 보여 줄 말로 바꿔요. 예: '월급 ▼'. 모든 탭이 같은 말을 써요. */
export function sortWords(sort: readonly SortItem[], en = false): string {
const names: Record<string, string> = en
? { name: 'Name', dept: 'Department', salary: 'Pay' }
: { name: '이름', dept: '부서', salary: '월급' };
return (
sort
.map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(', ') || (en ? 'none' : '없음')
);
}
const show = (): void => {
if (!line) return;
line.textContent = L(
`고른 행 ${state.selected.length}개 · 정렬 ${sortWords(state.sort)}`,
`${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`,
);
};
export function setup(api: GridApi<Row>) {
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
state.selected = [];
state.sort = [];
show();
const offs = [
api.on('selectionChanged', ({ selectedKeys }) => {
state.selected = selectedKeys;
show();
}),
api.on('sortChanged', ({ sortModel }) => {
state.sort = sortModel;
show();
}),
];
return () => {
offs.forEach((off) => off());
line?.remove();
line = null;
};
}
export const actions = {
selectThree: (api: GridApi<Row>) => api.setSelectedKeys([1, 2, 3]),
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
reset: (api: GridApi<Row>) => {
api.clearSelection();
api.setSortModel([]);
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, ViewChild, signal } from '@angular/core';
import {
GridComponent,
isGridEvent,
type GridEventMessage,
type GridEventName,
type RowKey,
type SortItem,
} from '@maxgrid/angular';
import { options, sortWords, type Row } from './example';
// (gridEvent)로 오는 알림을 signal에 담아 두고, 버튼은 getApi()로 표 쪽을 바꿔요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div style="display: flex; gap: 8px; margin-bottom: 8px">
<button type="button" (click)="selectThree()">앞의 3명 고르기</button>
<button type="button" (click)="sortBySalary()">월급 큰 순</button>
<button type="button" (click)="reset()">처음으로</button>
</div>
<mx-grid
style="height: 260px"
[options]="options"
[events]="events"
(gridEvent)="onEvent($event)"
/>
<p>고른 행 {{ selected().length }}개 · 정렬 {{ sortText() }}</p>
`,
})
export class ExampleGridComponent {
readonly options = options;
readonly events: GridEventName[] = ['selectionChanged', 'sortChanged']; // 이 알림만 받아요
readonly selected = signal<RowKey[]>([]);
readonly sort = signal<SortItem[]>([]);
@ViewChild(GridComponent) private readonly gridRef?: GridComponent<Row>;
sortText = () => sortWords(this.sort());
onEvent(message: GridEventMessage<Row>): void {
if (isGridEvent(message, 'selectionChanged')) this.selected.set(message.payload.selectedKeys);
if (isGridEvent(message, 'sortChanged')) this.sort.set(message.payload.sortModel);
}
selectThree(): void {
this.gridRef?.getApi()?.setSelectedKeys([1, 2, 3]);
}
sortBySalary(): void {
this.gridRef?.getApi()?.setSortModel([{ columnId: 'salary', direction: 'desc' }]);
}
reset(): void {
this.gridRef?.getApi()?.clearSelection();
this.gridRef?.getApi()?.setSortModel([]);
}
}import type { GridApi, GridOptions, RowKey, SortItem } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'salary',
title: '월급(만원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [
{ id: 1, name: '김민준', dept: '개발팀', salary: 520 },
{ id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
{ id: 3, name: '박지호', dept: '영업팀', salary: 450 },
{ id: 4, name: '최유나', dept: '개발팀', salary: 610 },
{ id: 5, name: '정도윤', dept: '영업팀', salary: 390 },
{ id: 6, name: '한소희', dept: '디자인팀', salary: 540 },
],
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// 표가 고른 행과 정렬을 알려 주면, 화면(바깥)은 그 값을 자기 상태로 들고 있어요.
// 거꾸로 화면이 상태를 바꾸면 표도 따라 바뀌어요. 아래 코드는 이 JavaScript 버전이에요.
const state: { selected: RowKey[]; sort: SortItem[] } = { selected: [], sort: [] };
let line: HTMLElement | null = null;
/** 정렬 상태를 화면에 보여 줄 말로 바꿔요. 예: '월급 ▼'. 모든 탭이 같은 말을 써요. */
export function sortWords(sort: readonly SortItem[], en = false): string {
const names: Record<string, string> = en
? { name: 'Name', dept: 'Department', salary: 'Pay' }
: { name: '이름', dept: '부서', salary: '월급' };
return (
sort
.map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(', ') || (en ? 'none' : '없음')
);
}
const show = (): void => {
if (!line) return;
line.textContent = L(
`고른 행 ${state.selected.length}개 · 정렬 ${sortWords(state.sort)}`,
`${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`,
);
};
export function setup(api: GridApi<Row>) {
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
state.selected = [];
state.sort = [];
show();
const offs = [
api.on('selectionChanged', ({ selectedKeys }) => {
state.selected = selectedKeys;
show();
}),
api.on('sortChanged', ({ sortModel }) => {
state.sort = sortModel;
show();
}),
];
return () => {
offs.forEach((off) => off());
line?.remove();
line = null;
};
}
export const actions = {
selectThree: (api: GridApi<Row>) => api.setSelectedKeys([1, 2, 3]),
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
reset: (api: GridApi<Row>) => {
api.clearSelection();
api.setSortModel([]);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="selectThree">Select first three</button>
<button type="button" id="sortBySalary">Salary high to low</button>
<button type="button" id="reset">Reset</button>
</div>
<div id="grid" style="height: 420px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api);
document.getElementById('selectThree').addEventListener('click', () => actions.selectThree(api));
document.getElementById('sortBySalary').addEventListener('click', () => actions.sortBySalary(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));export const options = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'salary',
title: 'Pay ($100)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [
{ id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
{ id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
{ id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
{ id: 4, name: 'Olivia Hayes', dept: 'Dev', salary: 610 },
{ id: 5, name: 'Ethan Brooks', dept: 'Sales', salary: 390 },
{ id: 6, name: 'Sophia Bell', dept: 'Design', salary: 540 },
],
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// When the table reports the selected rows and the sort, the screen (outside) holds those values as its own state.
// Conversely, when the screen changes the state, the table follows. The code below is this JavaScript version.
const state = { selected: [], sort: [] };
let line = null;
/** Turns the sort state into text to show on screen. Example: 'Pay ▼'. Every tab uses the same text. */
export function sortWords(sort, _en = true) {
const names = { name: 'Name', dept: 'Department', salary: 'Pay' };
return (sort
.map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(', ') || 'none');
}
const show = () => {
if (!line)
return;
line.textContent = `${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`;
};
export function setup(api) {
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
state.selected = [];
state.sort = [];
show();
const offs = [
api.on('selectionChanged', ({ selectedKeys }) => {
state.selected = selectedKeys;
show();
}),
api.on('sortChanged', ({ sortModel }) => {
state.sort = sortModel;
show();
}),
];
return () => {
offs.forEach((off) => off());
line?.remove();
line = null;
};
}
export const actions = {
selectThree: (api) => api.setSelectedKeys([1, 2, 3]),
sortBySalary: (api) => api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
reset: (api) => {
api.clearSelection();
api.setSortModel([]);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Keep the grid's selection and sort in step with screen state</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="selectThree">Select first three</button>
<button type="button" id="sortBySalary">Salary high to low</button>
<button type="button" id="reset">Reset</button>
</div>
<div id="grid" style="height: 420px"></div>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const options = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'salary',
title: 'Pay ($100)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [
{ id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
{ id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
{ id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
{ id: 4, name: 'Olivia Hayes', dept: 'Dev', salary: 610 },
{ id: 5, name: 'Ethan Brooks', dept: 'Sales', salary: 390 },
{ id: 6, name: 'Sophia Bell', dept: 'Design', salary: 540 },
],
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// When the table reports the selected rows and the sort, the screen (outside) holds those values as its own state.
// Conversely, when the screen changes the state, the table follows. The code below is this JavaScript version.
const state = { selected: [], sort: [] };
let line = null;
/** Turns the sort state into text to show on screen. Example: 'Pay ▼'. Every tab uses the same text. */
function sortWords(sort, _en = true) {
const names = { name: 'Name', dept: 'Department', salary: 'Pay' };
return (sort
.map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(', ') || 'none');
}
const show = () => {
if (!line)
return;
line.textContent = `${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`;
};
function setup(api) {
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
state.selected = [];
state.sort = [];
show();
const offs = [
api.on('selectionChanged', ({ selectedKeys }) => {
state.selected = selectedKeys;
show();
}),
api.on('sortChanged', ({ sortModel }) => {
state.sort = sortModel;
show();
}),
];
return () => {
offs.forEach((off) => off());
line?.remove();
line = null;
};
}
const actions = {
selectThree: (api) => api.setSelectedKeys([1, 2, 3]),
sortBySalary: (api) => api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
reset: (api) => {
api.clearSelection();
api.setSortModel([]);
},
};
options.ariaLabel = "Keep the grid's selection and sort in step with screen state";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api);
document.getElementById('selectThree').addEventListener('click', () => actions.selectThree(api));
document.getElementById('sortBySalary').addEventListener('click', () => actions.sortBySalary(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Grid, useGridApi, type RowKey, type SortItem } from '@maxgrid/react';
import { useState } from 'react';
import { options, sortWords, type Row } from './example';
// 표가 고른 행과 정렬을 알려 주면 React 상태에 담아 두고, 버튼은 표 쪽(api)을 바꿔요.
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
const [selected, setSelected] = useState<RowKey[]>([]);
const [sort, setSort] = useState<SortItem[]>([]);
return (
<>
<div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
<button type="button" disabled={!api} onClick={() => api?.setSelectedKeys([1, 2, 3])}>
앞의 3명 고르기
</button>
<button
type="button"
disabled={!api}
onClick={() => api?.setSortModel([{ columnId: 'salary', direction: 'desc' }])}
>
월급 큰 순
</button>
<button
type="button"
disabled={!api}
onClick={() => {
api?.clearSelection();
api?.setSortModel([]);
}}
>
처음으로
</button>
</div>
<div style={{ height: 260 }}>
<Grid<Row>
ref={gridRef}
options={options}
onSelectionChanged={({ selectedKeys }) => setSelected(selectedKeys)}
onSortChanged={({ sortModel }) => setSort(sortModel)}
/>
</div>
<p>
고른 행 {selected.length}개 · 정렬 {sortWords(sort)}
</p>
</>
);
}import type { GridApi, GridOptions, RowKey, SortItem } from '@maxgrid/react';
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'salary',
title: 'Pay ($100)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [
{ id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
{ id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
{ id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
{ id: 4, name: 'Olivia Hayes', dept: 'Dev', salary: 610 },
{ id: 5, name: 'Ethan Brooks', dept: 'Sales', salary: 390 },
{ id: 6, name: 'Sophia Bell', dept: 'Design', salary: 540 },
],
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// When the table reports the selected rows and the sort, the screen (outside) holds those values as its own state.
// Conversely, when the screen changes the state, the table follows. The code below is this JavaScript version.
const state: { selected: RowKey[]; sort: SortItem[] } = { selected: [], sort: [] };
let line: HTMLElement | null = null;
/** Turns the sort state into text to show on screen. Example: 'Pay ▼'. Every tab uses the same text. */
export function sortWords(sort: readonly SortItem[], _en = true): string {
const names: Record<string, string> = { name: 'Name', dept: 'Department', salary: 'Pay' };
return (
sort
.map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(', ') || 'none'
);
}
const show = (): void => {
if (!line) return;
line.textContent = `${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`;
};
export function setup(api: GridApi<Row>) {
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
state.selected = [];
state.sort = [];
show();
const offs = [
api.on('selectionChanged', ({ selectedKeys }) => {
state.selected = selectedKeys;
show();
}),
api.on('sortChanged', ({ sortModel }) => {
state.sort = sortModel;
show();
}),
];
return () => {
offs.forEach((off) => off());
line?.remove();
line = null;
};
}
export const actions = {
selectThree: (api: GridApi<Row>) => api.setSelectedKeys([1, 2, 3]),
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
reset: (api: GridApi<Row>) => {
api.clearSelection();
api.setSortModel([]);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { Grid, type RowKey, type SortItem } from '@maxgrid/vue';
import { computed, ref } from 'vue';
import { options, sortWords } from './example';
// v-model로 연결하면 표와 이 화면의 상태가 서로 따라가요. 바깥에서 값을 바꾸면 표도 바뀌어요.
const selected = ref<RowKey[]>([]);
const sort = ref<SortItem[]>([]);
const summary = computed(() => {
return `고른 행 ${selected.value.length}개 · 정렬 ${sortWords(sort.value)}`;
});
const selectThree = () => (selected.value = [1, 2, 3]);
const sortBySalary = () => (sort.value = [{ columnId: 'salary', direction: 'desc' }]);
const reset = () => {
selected.value = [];
sort.value = [];
};
</script>
<template>
<div class="bar">
<button type="button" @click="selectThree">앞의 3명 고르기</button>
<button type="button" @click="sortBySalary">월급 큰 순</button>
<button type="button" @click="reset">처음으로</button>
</div>
<Grid
style="height: 260px"
:options="options"
v-model:selectedKeys="selected"
v-model:sortModel="sort"
/>
<p>{{ summary }}</p>
</template>
<style scoped>
.bar {
display: flex;
gap: 8px;
margin-bottom: 8px;
}
</style>import type { GridApi, GridOptions, RowKey, SortItem } from '@maxgrid/vue';
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'salary',
title: 'Pay ($100)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [
{ id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
{ id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
{ id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
{ id: 4, name: 'Olivia Hayes', dept: 'Dev', salary: 610 },
{ id: 5, name: 'Ethan Brooks', dept: 'Sales', salary: 390 },
{ id: 6, name: 'Sophia Bell', dept: 'Design', salary: 540 },
],
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// When the table reports the selected rows and the sort, the screen (outside) holds those values as its own state.
// Conversely, when the screen changes the state, the table follows. The code below is this JavaScript version.
const state: { selected: RowKey[]; sort: SortItem[] } = { selected: [], sort: [] };
let line: HTMLElement | null = null;
/** Turns the sort state into text to show on screen. Example: 'Pay ▼'. Every tab uses the same text. */
export function sortWords(sort: readonly SortItem[], _en = true): string {
const names: Record<string, string> = { name: 'Name', dept: 'Department', salary: 'Pay' };
return (
sort
.map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(', ') || 'none'
);
}
const show = (): void => {
if (!line) return;
line.textContent = `${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`;
};
export function setup(api: GridApi<Row>) {
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
state.selected = [];
state.sort = [];
show();
const offs = [
api.on('selectionChanged', ({ selectedKeys }) => {
state.selected = selectedKeys;
show();
}),
api.on('sortChanged', ({ sortModel }) => {
state.sort = sortModel;
show();
}),
];
return () => {
offs.forEach((off) => off());
line?.remove();
line = null;
};
}
export const actions = {
selectThree: (api: GridApi<Row>) => api.setSelectedKeys([1, 2, 3]),
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
reset: (api: GridApi<Row>) => {
api.clearSelection();
api.setSortModel([]);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, ViewChild, signal } from '@angular/core';
import {
GridComponent,
isGridEvent,
type GridEventMessage,
type GridEventName,
type RowKey,
type SortItem,
} from '@maxgrid/angular';
import { options, sortWords, type Row } from './example';
// (gridEvent)로 오는 알림을 signal에 담아 두고, 버튼은 getApi()로 표 쪽을 바꿔요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div style="display: flex; gap: 8px; margin-bottom: 8px">
<button type="button" (click)="selectThree()">앞의 3명 고르기</button>
<button type="button" (click)="sortBySalary()">월급 큰 순</button>
<button type="button" (click)="reset()">처음으로</button>
</div>
<mx-grid
style="height: 260px"
[options]="options"
[events]="events"
(gridEvent)="onEvent($event)"
/>
<p>고른 행 {{ selected().length }}개 · 정렬 {{ sortText() }}</p>
`,
})
export class ExampleGridComponent {
readonly options = options;
readonly events: GridEventName[] = ['selectionChanged', 'sortChanged']; // 이 알림만 받아요
readonly selected = signal<RowKey[]>([]);
readonly sort = signal<SortItem[]>([]);
@ViewChild(GridComponent) private readonly gridRef?: GridComponent<Row>;
sortText = () => sortWords(this.sort());
onEvent(message: GridEventMessage<Row>): void {
if (isGridEvent(message, 'selectionChanged')) this.selected.set(message.payload.selectedKeys);
if (isGridEvent(message, 'sortChanged')) this.sort.set(message.payload.sortModel);
}
selectThree(): void {
this.gridRef?.getApi()?.setSelectedKeys([1, 2, 3]);
}
sortBySalary(): void {
this.gridRef?.getApi()?.setSortModel([{ columnId: 'salary', direction: 'desc' }]);
}
reset(): void {
this.gridRef?.getApi()?.clearSelection();
this.gridRef?.getApi()?.setSortModel([]);
}
}import type { GridApi, GridOptions, RowKey, SortItem } from '@maxgrid/angular';
export interface Row {
id: number;
name: string;
dept: string;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'salary',
title: 'Pay ($100)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [
{ id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
{ id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
{ id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
{ id: 4, name: 'Olivia Hayes', dept: 'Dev', salary: 610 },
{ id: 5, name: 'Ethan Brooks', dept: 'Sales', salary: 390 },
{ id: 6, name: 'Sophia Bell', dept: 'Design', salary: 540 },
],
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// When the table reports the selected rows and the sort, the screen (outside) holds those values as its own state.
// Conversely, when the screen changes the state, the table follows. The code below is this JavaScript version.
const state: { selected: RowKey[]; sort: SortItem[] } = { selected: [], sort: [] };
let line: HTMLElement | null = null;
/** Turns the sort state into text to show on screen. Example: 'Pay ▼'. Every tab uses the same text. */
export function sortWords(sort: readonly SortItem[], _en = true): string {
const names: Record<string, string> = { name: 'Name', dept: 'Department', salary: 'Pay' };
return (
sort
.map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
.join(', ') || 'none'
);
}
const show = (): void => {
if (!line) return;
line.textContent = `${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`;
};
export function setup(api: GridApi<Row>) {
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
state.selected = [];
state.sort = [];
show();
const offs = [
api.on('selectionChanged', ({ selectedKeys }) => {
state.selected = selectedKeys;
show();
}),
api.on('sortChanged', ({ sortModel }) => {
state.sort = sortModel;
show();
}),
];
return () => {
offs.forEach((off) => off());
line?.remove();
line = null;
};
}
export const actions = {
selectThree: (api: GridApi<Row>) => api.setSelectedKeys([1, 2, 3]),
sortBySalary: (api: GridApi<Row>) =>
api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
reset: (api: GridApi<Row>) => {
api.clearSelection();
api.setSortModel([]);
},
};