헤더를 눌러서 정렬하기Click a header to sort
헤더를 누르면 오름차순 → 내림차순 → 정렬 해제 순서로 바뀌어요. Shift+클릭으로 기준을 더하면 다중 정렬이고, 직급처럼 가나다순이 아닌 순서도 값만 바꿔 정렬할 수 있어요.Clicking a header cycles ascending, descending, off. Shift+click adds another sort key, and custom orders such as job grades only need a ranking value.
코드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="teamThenSalary">팀 → 연봉 높은 순</button>
<button type="button" id="byGrade">직급 높은 순</button>
<button type="button" id="byJoined">입사일 빠른 순</button>
<button type="button" id="clear">정렬 해제</button>
</div>
<div id="grid" style="height: 440px"></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, console.log);
document.getElementById('teamThenSalary').addEventListener('click', () => actions.teamThenSalary(api));
document.getElementById('byGrade').addEventListener('click', () => actions.byGrade(api));
document.getElementById('byJoined').addEventListener('click', () => actions.byJoined(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'윤지아',
'강태양',
'송하늘',
'임보라',
'배준서',
];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const GRADES = ['사원', '주임', '대리', '과장', '차장', '부장'];
const memos = [
'신규 프로젝트 투입',
'',
'육아휴직 복귀',
'',
'해외 출장 예정',
'',
'멘토링 담당',
'',
];
// '직급'은 가나다순이 아니라 사원 → 부장 순서로 정렬하고 싶어요. 그럴 땐 정렬에 쓰는 값(getValue)을
// 순번으로 돌려주고, 화면에 보이는 글자(formatValue)만 직급 이름으로 바꿔요.
export const options = {
columns: [
{ id: 'name', title: '이름', width: 100 },
{ id: 'team', title: '팀', width: 110 },
{
id: 'grade',
title: '직급 (서열순)',
kind: 'number',
width: 130,
align: 'start',
getValue: (row) => GRADES.indexOf(row.grade),
formatValue: (value) => GRADES[Number(value)] ?? '',
},
{ id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
{ id: 'joined', title: '입사일', width: 120 },
// sortable: false이면 헤더를 눌러도 정렬되지 않아요.
{ id: 'memo', title: '메모 (정렬 안 됨)', width: 170, sortable: false },
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i],
team: teams[(i * 3 + 1) % 4],
grade: GRADES[(i * 5) % 6],
salary: 3800 + ((i * 530) % 4200),
joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
memo: memos[i % 8],
})),
rowKey: 'id',
};
export function setup(api, log) {
const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// 정렬 기준을 우선순위 순서대로 풀어서 보여 줘요.
const off = api.on('sortChanged', ({ sortModel }) => log(sortModel.length === 0
? { ko: '정렬 없음 (원래 순서)', en: 'No sort (original order)' }
: {
ko: sortModel
.map((s, i) => `${i + 1}순위 ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ 오름차순' : '▼ 내림차순'}`)
.join(' → '),
en: sortModel
.map((s, i) => `#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`)
.join(' → '),
}));
return () => off();
}
export const actions = {
// 코드에서 정렬을 지정해요. 배열 순서가 우선순위예요.
teamThenSalary: (api) => api.setSortModel([
{ columnId: 'team', direction: 'asc' },
{ columnId: 'salary', direction: 'desc' },
]),
byGrade: (api) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
byJoined: (api) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
clear: (api) => 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="teamThenSalary">팀 → 연봉 높은 순</button>
<button type="button" id="byGrade">직급 높은 순</button>
<button type="button" id="byJoined">입사일 빠른 순</button>
<button type="button" id="clear">정렬 해제</button>
</div>
<div id="grid" style="height: 440px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'윤지아',
'강태양',
'송하늘',
'임보라',
'배준서',
];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const GRADES = ['사원', '주임', '대리', '과장', '차장', '부장'];
const memos = [
'신규 프로젝트 투입',
'',
'육아휴직 복귀',
'',
'해외 출장 예정',
'',
'멘토링 담당',
'',
];
// '직급'은 가나다순이 아니라 사원 → 부장 순서로 정렬하고 싶어요. 그럴 땐 정렬에 쓰는 값(getValue)을
// 순번으로 돌려주고, 화면에 보이는 글자(formatValue)만 직급 이름으로 바꿔요.
const options = {
columns: [
{ id: 'name', title: '이름', width: 100 },
{ id: 'team', title: '팀', width: 110 },
{
id: 'grade',
title: '직급 (서열순)',
kind: 'number',
width: 130,
align: 'start',
getValue: (row) => GRADES.indexOf(row.grade),
formatValue: (value) => GRADES[Number(value)] ?? '',
},
{ id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
{ id: 'joined', title: '입사일', width: 120 },
// sortable: false이면 헤더를 눌러도 정렬되지 않아요.
{ id: 'memo', title: '메모 (정렬 안 됨)', width: 170, sortable: false },
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i],
team: teams[(i * 3 + 1) % 4],
grade: GRADES[(i * 5) % 6],
salary: 3800 + ((i * 530) % 4200),
joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
memo: memos[i % 8],
})),
rowKey: 'id',
};
function setup(api, log) {
const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// 정렬 기준을 우선순위 순서대로 풀어서 보여 줘요.
const off = api.on('sortChanged', ({ sortModel }) => log(sortModel.length === 0
? { ko: '정렬 없음 (원래 순서)', en: 'No sort (original order)' }
: {
ko: sortModel
.map((s, i) => `${i + 1}순위 ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ 오름차순' : '▼ 내림차순'}`)
.join(' → '),
en: sortModel
.map((s, i) => `#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`)
.join(' → '),
}));
return () => off();
}
const actions = {
// 코드에서 정렬을 지정해요. 배열 순서가 우선순위예요.
teamThenSalary: (api) => api.setSortModel([
{ columnId: 'team', direction: 'asc' },
{ columnId: 'salary', direction: 'desc' },
]),
byGrade: (api) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
byJoined: (api) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
clear: (api) => api.setSortModel([]),
};
options.ariaLabel = "헤더를 눌러서 정렬하기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('teamThenSalary').addEventListener('click', () => actions.teamThenSalary(api));
document.getElementById('byGrade').addEventListener('click', () => actions.byGrade(api));
document.getElementById('byJoined').addEventListener('click', () => actions.byJoined(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.teamThenSalary(api)}
>팀 → 연봉 높은 순</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.byGrade(api)}
>직급 높은 순</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.byJoined(api)}
>입사일 빠른 순</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>정렬 해제</button>
</div>
<Grid style={{ height: 440 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
grade: string;
salary: number;
joined: string;
memo: string;
}
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'윤지아',
'강태양',
'송하늘',
'임보라',
'배준서',
];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const GRADES = ['사원', '주임', '대리', '과장', '차장', '부장'];
const memos = [
'신규 프로젝트 투입',
'',
'육아휴직 복귀',
'',
'해외 출장 예정',
'',
'멘토링 담당',
'',
];
// '직급'은 가나다순이 아니라 사원 → 부장 순서로 정렬하고 싶어요. 그럴 땐 정렬에 쓰는 값(getValue)을
// 순번으로 돌려주고, 화면에 보이는 글자(formatValue)만 직급 이름으로 바꿔요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 100 },
{ id: 'team', title: '팀', width: 110 },
{
id: 'grade',
title: '직급 (서열순)',
kind: 'number',
width: 130,
align: 'start',
getValue: (row) => GRADES.indexOf(row.grade),
formatValue: (value) => GRADES[Number(value)] ?? '',
},
{ id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
{ id: 'joined', title: '입사일', width: 120 },
// sortable: false이면 헤더를 눌러도 정렬되지 않아요.
{ id: 'memo', title: '메모 (정렬 안 됨)', width: 170, sortable: false },
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i] as string,
team: teams[(i * 3 + 1) % 4] as string,
grade: GRADES[(i * 5) % 6] as string,
salary: 3800 + ((i * 530) % 4200),
joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
memo: memos[i % 8] as string,
})),
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// 정렬 기준을 우선순위 순서대로 풀어서 보여 줘요.
const off = api.on('sortChanged', ({ sortModel }) =>
log(
sortModel.length === 0
? { ko: '정렬 없음 (원래 순서)', en: 'No sort (original order)' }
: {
ko: sortModel
.map(
(s, i) =>
`${i + 1}순위 ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ 오름차순' : '▼ 내림차순'}`,
)
.join(' → '),
en: sortModel
.map(
(s, i) =>
`#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`,
)
.join(' → '),
},
),
);
return () => off();
}
export const actions = {
// 코드에서 정렬을 지정해요. 배열 순서가 우선순위예요.
teamThenSalary: (api: GridApi<Row>) =>
api.setSortModel([
{ columnId: 'team', direction: 'asc' },
{ columnId: 'salary', direction: 'desc' },
]),
byGrade: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
byJoined: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
clear: (api: GridApi<Row>) => api.setSortModel([]),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.teamThenSalary(api)"
>팀 → 연봉 높은 순</button>
<button type="button" :disabled="!api" @click="api && actions.byGrade(api)">직급 높은 순</button>
<button
type="button"
:disabled="!api"
@click="api && actions.byJoined(api)"
>입사일 빠른 순</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">정렬 해제</button>
</div>
<Grid style="height: 440px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
grade: string;
salary: number;
joined: string;
memo: string;
}
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'윤지아',
'강태양',
'송하늘',
'임보라',
'배준서',
];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const GRADES = ['사원', '주임', '대리', '과장', '차장', '부장'];
const memos = [
'신규 프로젝트 투입',
'',
'육아휴직 복귀',
'',
'해외 출장 예정',
'',
'멘토링 담당',
'',
];
// '직급'은 가나다순이 아니라 사원 → 부장 순서로 정렬하고 싶어요. 그럴 땐 정렬에 쓰는 값(getValue)을
// 순번으로 돌려주고, 화면에 보이는 글자(formatValue)만 직급 이름으로 바꿔요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 100 },
{ id: 'team', title: '팀', width: 110 },
{
id: 'grade',
title: '직급 (서열순)',
kind: 'number',
width: 130,
align: 'start',
getValue: (row) => GRADES.indexOf(row.grade),
formatValue: (value) => GRADES[Number(value)] ?? '',
},
{ id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
{ id: 'joined', title: '입사일', width: 120 },
// sortable: false이면 헤더를 눌러도 정렬되지 않아요.
{ id: 'memo', title: '메모 (정렬 안 됨)', width: 170, sortable: false },
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i] as string,
team: teams[(i * 3 + 1) % 4] as string,
grade: GRADES[(i * 5) % 6] as string,
salary: 3800 + ((i * 530) % 4200),
joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
memo: memos[i % 8] as string,
})),
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// 정렬 기준을 우선순위 순서대로 풀어서 보여 줘요.
const off = api.on('sortChanged', ({ sortModel }) =>
log(
sortModel.length === 0
? { ko: '정렬 없음 (원래 순서)', en: 'No sort (original order)' }
: {
ko: sortModel
.map(
(s, i) =>
`${i + 1}순위 ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ 오름차순' : '▼ 내림차순'}`,
)
.join(' → '),
en: sortModel
.map(
(s, i) =>
`#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`,
)
.join(' → '),
},
),
);
return () => off();
}
export const actions = {
// 코드에서 정렬을 지정해요. 배열 순서가 우선순위예요.
teamThenSalary: (api: GridApi<Row>) =>
api.setSortModel([
{ columnId: 'team', direction: 'asc' },
{ columnId: 'salary', direction: 'desc' },
]),
byGrade: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
byJoined: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
clear: (api: GridApi<Row>) => api.setSortModel([]),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.teamThenSalary(api)"
>팀 → 연봉 높은 순</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.byGrade(api)"
>직급 높은 순</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.byJoined(api)"
>입사일 빠른 순</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>정렬 해제</button>
</div>
<mx-grid style="height: 440px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
grade: string;
salary: number;
joined: string;
memo: string;
}
const names = [
'김민준',
'이서연',
'박지호',
'최유나',
'정도윤',
'한소희',
'오세훈',
'윤지아',
'강태양',
'송하늘',
'임보라',
'배준서',
];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const GRADES = ['사원', '주임', '대리', '과장', '차장', '부장'];
const memos = [
'신규 프로젝트 투입',
'',
'육아휴직 복귀',
'',
'해외 출장 예정',
'',
'멘토링 담당',
'',
];
// '직급'은 가나다순이 아니라 사원 → 부장 순서로 정렬하고 싶어요. 그럴 땐 정렬에 쓰는 값(getValue)을
// 순번으로 돌려주고, 화면에 보이는 글자(formatValue)만 직급 이름으로 바꿔요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 100 },
{ id: 'team', title: '팀', width: 110 },
{
id: 'grade',
title: '직급 (서열순)',
kind: 'number',
width: 130,
align: 'start',
getValue: (row) => GRADES.indexOf(row.grade),
formatValue: (value) => GRADES[Number(value)] ?? '',
},
{ id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
{ id: 'joined', title: '입사일', width: 120 },
// sortable: false이면 헤더를 눌러도 정렬되지 않아요.
{ id: 'memo', title: '메모 (정렬 안 됨)', width: 170, sortable: false },
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i] as string,
team: teams[(i * 3 + 1) % 4] as string,
grade: GRADES[(i * 5) % 6] as string,
salary: 3800 + ((i * 530) % 4200),
joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
memo: memos[i % 8] as string,
})),
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// 정렬 기준을 우선순위 순서대로 풀어서 보여 줘요.
const off = api.on('sortChanged', ({ sortModel }) =>
log(
sortModel.length === 0
? { ko: '정렬 없음 (원래 순서)', en: 'No sort (original order)' }
: {
ko: sortModel
.map(
(s, i) =>
`${i + 1}순위 ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ 오름차순' : '▼ 내림차순'}`,
)
.join(' → '),
en: sortModel
.map(
(s, i) =>
`#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`,
)
.join(' → '),
},
),
);
return () => off();
}
export const actions = {
// 코드에서 정렬을 지정해요. 배열 순서가 우선순위예요.
teamThenSalary: (api: GridApi<Row>) =>
api.setSortModel([
{ columnId: 'team', direction: 'asc' },
{ columnId: 'salary', direction: 'desc' },
]),
byGrade: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
byJoined: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
clear: (api: GridApi<Row>) => 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="teamThenSalary">Team, then salary</button>
<button type="button" id="byGrade">Highest grade first</button>
<button type="button" id="byJoined">Earliest hire first</button>
<button type="button" id="clear">Clear sort</button>
</div>
<div id="grid" style="height: 440px"></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, console.log);
document.getElementById('teamThenSalary').addEventListener('click', () => actions.teamThenSalary(api));
document.getElementById('byGrade').addEventListener('click', () => actions.byGrade(api));
document.getElementById('byJoined').addEventListener('click', () => actions.byJoined(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const names = [
'Liam Carter',
'Emma Stone',
'Noah Brooks',
'Olivia Reed',
'Ethan Hall',
'Ava Morgan',
'Mason Gray',
'Mia Foster',
'Lucas Bell',
'Sophia Ward',
'Logan Price',
'Chloe Ross',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const GRADES = ['Junior', 'Associate', 'Senior', 'Lead', 'Manager', 'Director'];
const memos = [
'Joining a new project',
'',
'Back from parental leave',
'',
'Overseas trip planned',
'',
'Mentoring duty',
'',
];
// We want 'Grade' sorted Junior -> Director, not alphabetically. So the sort value (getValue)
// returns the rank number, and only the displayed text (formatValue) is turned into the grade name.
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 100 },
{ id: 'team', title: 'Team', width: 110 },
{
id: 'grade',
title: 'Grade (by rank)',
kind: 'number',
width: 130,
align: 'start',
getValue: (row) => GRADES.indexOf(row.grade),
formatValue: (value) => GRADES[Number(value)] ?? '',
},
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
{ id: 'joined', title: 'Joined', width: 120 },
// With sortable: false, clicking the header does not sort.
{ id: 'memo', title: 'Memo (not sortable)', width: 170, sortable: false },
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i],
team: teams[(i * 3 + 1) % 4],
grade: GRADES[(i * 5) % 6],
salary: 38000 + ((i * 530) % 4200) * 10,
joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
memo: memos[i % 8],
})),
rowKey: 'id',
};
export function setup(api, log) {
const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// List the sort keys in priority order.
const off = api.on('sortChanged', ({ sortModel }) => log(sortModel.length === 0
? 'No sort (original order)'
: sortModel
.map((s, i) => `#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`)
.join(' → ')));
return () => off();
}
export const actions = {
// Set the sort from code. The array order is the priority.
teamThenSalary: (api) => api.setSortModel([
{ columnId: 'team', direction: 'asc' },
{ columnId: 'salary', direction: 'desc' },
]),
byGrade: (api) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
byJoined: (api) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
clear: (api) => api.setSortModel([]),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Click a header to sort</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="teamThenSalary">Team, then salary</button>
<button type="button" id="byGrade">Highest grade first</button>
<button type="button" id="byJoined">Earliest hire first</button>
<button type="button" id="clear">Clear sort</button>
</div>
<div id="grid" style="height: 440px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = [
'Liam Carter',
'Emma Stone',
'Noah Brooks',
'Olivia Reed',
'Ethan Hall',
'Ava Morgan',
'Mason Gray',
'Mia Foster',
'Lucas Bell',
'Sophia Ward',
'Logan Price',
'Chloe Ross',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const GRADES = ['Junior', 'Associate', 'Senior', 'Lead', 'Manager', 'Director'];
const memos = [
'Joining a new project',
'',
'Back from parental leave',
'',
'Overseas trip planned',
'',
'Mentoring duty',
'',
];
// We want 'Grade' sorted Junior -> Director, not alphabetically. So the sort value (getValue)
// returns the rank number, and only the displayed text (formatValue) is turned into the grade name.
const options = {
columns: [
{ id: 'name', title: 'Name', width: 100 },
{ id: 'team', title: 'Team', width: 110 },
{
id: 'grade',
title: 'Grade (by rank)',
kind: 'number',
width: 130,
align: 'start',
getValue: (row) => GRADES.indexOf(row.grade),
formatValue: (value) => GRADES[Number(value)] ?? '',
},
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
{ id: 'joined', title: 'Joined', width: 120 },
// With sortable: false, clicking the header does not sort.
{ id: 'memo', title: 'Memo (not sortable)', width: 170, sortable: false },
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i],
team: teams[(i * 3 + 1) % 4],
grade: GRADES[(i * 5) % 6],
salary: 38000 + ((i * 530) % 4200) * 10,
joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
memo: memos[i % 8],
})),
rowKey: 'id',
};
function setup(api, log) {
const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// List the sort keys in priority order.
const off = api.on('sortChanged', ({ sortModel }) => log(sortModel.length === 0
? 'No sort (original order)'
: sortModel
.map((s, i) => `#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`)
.join(' → ')));
return () => off();
}
const actions = {
// Set the sort from code. The array order is the priority.
teamThenSalary: (api) => api.setSortModel([
{ columnId: 'team', direction: 'asc' },
{ columnId: 'salary', direction: 'desc' },
]),
byGrade: (api) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
byJoined: (api) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
clear: (api) => api.setSortModel([]),
};
options.ariaLabel = "Click a header to sort";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('teamThenSalary').addEventListener('click', () => actions.teamThenSalary(api));
document.getElementById('byGrade').addEventListener('click', () => actions.byGrade(api));
document.getElementById('byJoined').addEventListener('click', () => actions.byJoined(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.teamThenSalary(api)}
>Team, then salary</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.byGrade(api)}
>Highest grade first</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.byJoined(api)}
>Earliest hire first</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear sort</button>
</div>
<Grid style={{ height: 440 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
grade: string;
salary: number;
joined: string;
memo: string;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Brooks',
'Olivia Reed',
'Ethan Hall',
'Ava Morgan',
'Mason Gray',
'Mia Foster',
'Lucas Bell',
'Sophia Ward',
'Logan Price',
'Chloe Ross',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const GRADES = ['Junior', 'Associate', 'Senior', 'Lead', 'Manager', 'Director'];
const memos = [
'Joining a new project',
'',
'Back from parental leave',
'',
'Overseas trip planned',
'',
'Mentoring duty',
'',
];
// We want 'Grade' sorted Junior -> Director, not alphabetically. So the sort value (getValue)
// returns the rank number, and only the displayed text (formatValue) is turned into the grade name.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 100 },
{ id: 'team', title: 'Team', width: 110 },
{
id: 'grade',
title: 'Grade (by rank)',
kind: 'number',
width: 130,
align: 'start',
getValue: (row) => GRADES.indexOf(row.grade),
formatValue: (value) => GRADES[Number(value)] ?? '',
},
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
{ id: 'joined', title: 'Joined', width: 120 },
// With sortable: false, clicking the header does not sort.
{ id: 'memo', title: 'Memo (not sortable)', width: 170, sortable: false },
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i] as string,
team: teams[(i * 3 + 1) % 4] as string,
grade: GRADES[(i * 5) % 6] as string,
salary: 38000 + ((i * 530) % 4200) * 10,
joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
memo: memos[i % 8] as string,
})),
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// List the sort keys in priority order.
const off = api.on('sortChanged', ({ sortModel }) =>
log(
sortModel.length === 0
? 'No sort (original order)'
: sortModel
.map(
(s, i) =>
`#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`,
)
.join(' → '),
),
);
return () => off();
}
export const actions = {
// Set the sort from code. The array order is the priority.
teamThenSalary: (api: GridApi<Row>) =>
api.setSortModel([
{ columnId: 'team', direction: 'asc' },
{ columnId: 'salary', direction: 'desc' },
]),
byGrade: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
byJoined: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
clear: (api: GridApi<Row>) => 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 { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.teamThenSalary(api)"
>Team, then salary</button>
<button type="button" :disabled="!api" @click="api && actions.byGrade(api)">Highest grade first</button>
<button
type="button"
:disabled="!api"
@click="api && actions.byJoined(api)"
>Earliest hire first</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear sort</button>
</div>
<Grid style="height: 440px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
grade: string;
salary: number;
joined: string;
memo: string;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Brooks',
'Olivia Reed',
'Ethan Hall',
'Ava Morgan',
'Mason Gray',
'Mia Foster',
'Lucas Bell',
'Sophia Ward',
'Logan Price',
'Chloe Ross',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const GRADES = ['Junior', 'Associate', 'Senior', 'Lead', 'Manager', 'Director'];
const memos = [
'Joining a new project',
'',
'Back from parental leave',
'',
'Overseas trip planned',
'',
'Mentoring duty',
'',
];
// We want 'Grade' sorted Junior -> Director, not alphabetically. So the sort value (getValue)
// returns the rank number, and only the displayed text (formatValue) is turned into the grade name.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 100 },
{ id: 'team', title: 'Team', width: 110 },
{
id: 'grade',
title: 'Grade (by rank)',
kind: 'number',
width: 130,
align: 'start',
getValue: (row) => GRADES.indexOf(row.grade),
formatValue: (value) => GRADES[Number(value)] ?? '',
},
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
{ id: 'joined', title: 'Joined', width: 120 },
// With sortable: false, clicking the header does not sort.
{ id: 'memo', title: 'Memo (not sortable)', width: 170, sortable: false },
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i] as string,
team: teams[(i * 3 + 1) % 4] as string,
grade: GRADES[(i * 5) % 6] as string,
salary: 38000 + ((i * 530) % 4200) * 10,
joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
memo: memos[i % 8] as string,
})),
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// List the sort keys in priority order.
const off = api.on('sortChanged', ({ sortModel }) =>
log(
sortModel.length === 0
? 'No sort (original order)'
: sortModel
.map(
(s, i) =>
`#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`,
)
.join(' → '),
),
);
return () => off();
}
export const actions = {
// Set the sort from code. The array order is the priority.
teamThenSalary: (api: GridApi<Row>) =>
api.setSortModel([
{ columnId: 'team', direction: 'asc' },
{ columnId: 'salary', direction: 'desc' },
]),
byGrade: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
byJoined: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
clear: (api: GridApi<Row>) => api.setSortModel([]),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.teamThenSalary(api)"
>Team, then salary</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.byGrade(api)"
>Highest grade first</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.byJoined(api)"
>Earliest hire first</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear sort</button>
</div>
<mx-grid style="height: 440px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
team: string;
grade: string;
salary: number;
joined: string;
memo: string;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Brooks',
'Olivia Reed',
'Ethan Hall',
'Ava Morgan',
'Mason Gray',
'Mia Foster',
'Lucas Bell',
'Sophia Ward',
'Logan Price',
'Chloe Ross',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const GRADES = ['Junior', 'Associate', 'Senior', 'Lead', 'Manager', 'Director'];
const memos = [
'Joining a new project',
'',
'Back from parental leave',
'',
'Overseas trip planned',
'',
'Mentoring duty',
'',
];
// We want 'Grade' sorted Junior -> Director, not alphabetically. So the sort value (getValue)
// returns the rank number, and only the displayed text (formatValue) is turned into the grade name.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 100 },
{ id: 'team', title: 'Team', width: 110 },
{
id: 'grade',
title: 'Grade (by rank)',
kind: 'number',
width: 130,
align: 'start',
getValue: (row) => GRADES.indexOf(row.grade),
formatValue: (value) => GRADES[Number(value)] ?? '',
},
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
{ id: 'joined', title: 'Joined', width: 120 },
// With sortable: false, clicking the header does not sort.
{ id: 'memo', title: 'Memo (not sortable)', width: 170, sortable: false },
],
rows: Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: names[i] as string,
team: teams[(i * 3 + 1) % 4] as string,
grade: GRADES[(i * 5) % 6] as string,
salary: 38000 + ((i * 530) % 4200) * 10,
joined: `20${15 + ((i * 7) % 10)}-${String(1 + ((i * 5) % 12)).padStart(2, '0')}-${String(2 + ((i * 11) % 26)).padStart(2, '0')}`,
memo: memos[i % 8] as string,
})),
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const titleOf = (id: string) => api.getColumns().find((c) => c.id === id)?.title ?? id;
// List the sort keys in priority order.
const off = api.on('sortChanged', ({ sortModel }) =>
log(
sortModel.length === 0
? 'No sort (original order)'
: sortModel
.map(
(s, i) =>
`#${i + 1} ${titleOf(s.columnId)} ${s.direction === 'asc' ? '▲ ascending' : '▼ descending'}`,
)
.join(' → '),
),
);
return () => off();
}
export const actions = {
// Set the sort from code. The array order is the priority.
teamThenSalary: (api: GridApi<Row>) =>
api.setSortModel([
{ columnId: 'team', direction: 'asc' },
{ columnId: 'salary', direction: 'desc' },
]),
byGrade: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'grade', direction: 'desc' }]),
byJoined: (api: GridApi<Row>) => api.setSortModel([{ columnId: 'joined', direction: 'asc' }]),
clear: (api: GridApi<Row>) => api.setSortModel([]),
};