그룹을 합계 순으로 바로 정렬하기Sort groups by their total directly
grouping.sortByTotal에 컬럼을 적으면 같은 부모 안의 그룹이 그 컬럼의 그룹 합계 순서로 놓여요. 도우미 컬럼이 필요 없어요.Set grouping.sortByTotal to a column and sibling groups are ordered by that column's group total. No helper column needed.
코드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">
<select aria-label="그룹 정렬" id="order">
<option value="desc" selected>합계 큰 순</option>
<option value="asc">합계 작은 순</option>
<option value="none">정렬 안 함</option>
</select>
</div>
<div id="grid" style="height: 360px"></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('order').addEventListener('change', (event) => actions.order(api, event.target.value));const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const members = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const rows = Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
team: teams[i % 4],
member: members[Math.floor(i / 4)],
sales: 100 + ((i * 53) % 170),
}));
const grouping = (order) => ({
by: ['team'],
expandDepth: 0,
// 같은 부모 안의 그룹을 sales 합계 순으로 놓아요. 없으면 줄이 처음 나타난 순서예요.
...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
export const options = {
columns: [
{ id: 'team', title: '팀', width: 100 },
{ id: 'member', title: '담당자', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
],
rows,
rowKey: 'id',
grouping: grouping('desc'),
};
let say = () => { };
// 사용자가 '그룹 정렬' 선택으로 고른 값. 머리글 정렬을 풀면 이 값으로 돌아가요.
let chosen = 'desc';
const WORDS_EN = {
desc: 'Sorted by total, largest first',
asc: 'Sorted by total, smallest first',
none: 'Not sorted. Rows are in the order they first appeared',
};
const WORDS = {
desc: '합계 큰 순으로 정렬했어요',
asc: '합계 작은 순으로 정렬했어요',
none: '정렬하지 않아요. 줄이 처음 나타난 순서예요',
};
function showChoice(order) {
const select = document.getElementById('order');
if (select instanceof HTMLSelectElement && select.value !== order)
select.value = order;
}
export function setup(api, log) {
say = log;
log({ ko: WORDS.desc, en: WORDS_EN.desc });
// 매출 머리글을 눌러 정렬하면 그룹 순서의 방향이 그 방향을 따라가요. 선택 칸도 실제 순서에 맞춰 바꿔요.
const off = api.on('sortChanged', ({ sortModel }) => {
const item = sortModel.find((s) => s.columnId === 'sales');
if (chosen === 'none' || !item)
return showChoice(chosen);
showChoice(item.direction);
log({
ko: `매출 머리글 정렬을 따라 ${item.direction === 'asc' ? '합계 작은 순' : '합계 큰 순'}이 됐어요`,
en: `Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`,
});
});
return () => off();
}
export const actions = {
order: (api, value) => {
chosen = (value ?? 'desc');
api.setOptions({ grouping: grouping(chosen) });
say({ ko: WORDS[chosen], en: WORDS_EN[chosen] });
},
};<!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">
<select aria-label="그룹 정렬" id="order">
<option value="desc" selected>합계 큰 순</option>
<option value="asc">합계 작은 순</option>
<option value="none">정렬 안 함</option>
</select>
</div>
<div id="grid" style="height: 360px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const members = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const rows = Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
team: teams[i % 4],
member: members[Math.floor(i / 4)],
sales: 100 + ((i * 53) % 170),
}));
const grouping = (order) => ({
by: ['team'],
expandDepth: 0,
// 같은 부모 안의 그룹을 sales 합계 순으로 놓아요. 없으면 줄이 처음 나타난 순서예요.
...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
const options = {
columns: [
{ id: 'team', title: '팀', width: 100 },
{ id: 'member', title: '담당자', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
],
rows,
rowKey: 'id',
grouping: grouping('desc'),
};
let say = () => { };
// 사용자가 '그룹 정렬' 선택으로 고른 값. 머리글 정렬을 풀면 이 값으로 돌아가요.
let chosen = 'desc';
const WORDS_EN = {
desc: 'Sorted by total, largest first',
asc: 'Sorted by total, smallest first',
none: 'Not sorted. Rows are in the order they first appeared',
};
const WORDS = {
desc: '합계 큰 순으로 정렬했어요',
asc: '합계 작은 순으로 정렬했어요',
none: '정렬하지 않아요. 줄이 처음 나타난 순서예요',
};
function showChoice(order) {
const select = document.getElementById('order');
if (select instanceof HTMLSelectElement && select.value !== order)
select.value = order;
}
function setup(api, log) {
say = log;
log({ ko: WORDS.desc, en: WORDS_EN.desc });
// 매출 머리글을 눌러 정렬하면 그룹 순서의 방향이 그 방향을 따라가요. 선택 칸도 실제 순서에 맞춰 바꿔요.
const off = api.on('sortChanged', ({ sortModel }) => {
const item = sortModel.find((s) => s.columnId === 'sales');
if (chosen === 'none' || !item)
return showChoice(chosen);
showChoice(item.direction);
log({
ko: `매출 머리글 정렬을 따라 ${item.direction === 'asc' ? '합계 작은 순' : '합계 큰 순'}이 됐어요`,
en: `Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`,
});
});
return () => off();
}
const actions = {
order: (api, value) => {
chosen = (value ?? 'desc');
api.setOptions({ grouping: grouping(chosen) });
say({ ko: WORDS[chosen], en: WORDS_EN[chosen] });
},
};
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('order').addEventListener('change', (event) => actions.order(api, event.target.value));
</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">
<select
aria-label="그룹 정렬"
disabled={!api}
onChange={(event) => api && actions.order(api, event.target.value)}
>
<option value="desc">합계 큰 순</option>
<option value="asc">합계 작은 순</option>
<option value="none">정렬 안 함</option>
</select>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
team: string;
member: string;
sales: number;
}
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const members = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const rows: Row[] = Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
team: teams[i % 4] as string,
member: members[Math.floor(i / 4)] as string,
sales: 100 + ((i * 53) % 170),
}));
type Order = 'asc' | 'desc' | 'none';
const grouping = (order: Order): NonNullable<GridOptions<Row>['grouping']> => ({
by: ['team'],
expandDepth: 0,
// 같은 부모 안의 그룹을 sales 합계 순으로 놓아요. 없으면 줄이 처음 나타난 순서예요.
...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: '팀', width: 100 },
{ id: 'member', title: '담당자', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
],
rows,
rowKey: 'id',
grouping: grouping('desc'),
};
let say: (message: LogText) => void = () => {};
// 사용자가 '그룹 정렬' 선택으로 고른 값. 머리글 정렬을 풀면 이 값으로 돌아가요.
let chosen: Order = 'desc';
const WORDS_EN: Record<Order, string> = {
desc: 'Sorted by total, largest first',
asc: 'Sorted by total, smallest first',
none: 'Not sorted. Rows are in the order they first appeared',
};
const WORDS: Record<Order, string> = {
desc: '합계 큰 순으로 정렬했어요',
asc: '합계 작은 순으로 정렬했어요',
none: '정렬하지 않아요. 줄이 처음 나타난 순서예요',
};
function showChoice(order: Order): void {
const select = document.getElementById('order');
if (select instanceof HTMLSelectElement && select.value !== order) select.value = order;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({ ko: WORDS.desc, en: WORDS_EN.desc });
// 매출 머리글을 눌러 정렬하면 그룹 순서의 방향이 그 방향을 따라가요. 선택 칸도 실제 순서에 맞춰 바꿔요.
const off = api.on('sortChanged', ({ sortModel }) => {
const item = sortModel.find((s) => s.columnId === 'sales');
if (chosen === 'none' || !item) return showChoice(chosen);
showChoice(item.direction);
log({
ko: `매출 머리글 정렬을 따라 ${item.direction === 'asc' ? '합계 작은 순' : '합계 큰 순'}이 됐어요`,
en: `Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`,
});
});
return () => off();
}
export const actions = {
order: (api: GridApi<Row>, value?: string) => {
chosen = (value ?? 'desc') as Order;
api.setOptions({ grouping: grouping(chosen) });
say({ ko: WORDS[chosen], en: WORDS_EN[chosen] });
},
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="그룹 정렬"
:disabled="!api"
@change="api && actions.order(api, ($event.target as HTMLSelectElement).value)"
>
<option value="desc" selected>합계 큰 순</option>
<option value="asc">합계 작은 순</option>
<option value="none">정렬 안 함</option>
</select>
</div>
<Grid style="height: 360px" :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;
team: string;
member: string;
sales: number;
}
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const members = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const rows: Row[] = Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
team: teams[i % 4] as string,
member: members[Math.floor(i / 4)] as string,
sales: 100 + ((i * 53) % 170),
}));
type Order = 'asc' | 'desc' | 'none';
const grouping = (order: Order): NonNullable<GridOptions<Row>['grouping']> => ({
by: ['team'],
expandDepth: 0,
// 같은 부모 안의 그룹을 sales 합계 순으로 놓아요. 없으면 줄이 처음 나타난 순서예요.
...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: '팀', width: 100 },
{ id: 'member', title: '담당자', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
],
rows,
rowKey: 'id',
grouping: grouping('desc'),
};
let say: (message: LogText) => void = () => {};
// 사용자가 '그룹 정렬' 선택으로 고른 값. 머리글 정렬을 풀면 이 값으로 돌아가요.
let chosen: Order = 'desc';
const WORDS_EN: Record<Order, string> = {
desc: 'Sorted by total, largest first',
asc: 'Sorted by total, smallest first',
none: 'Not sorted. Rows are in the order they first appeared',
};
const WORDS: Record<Order, string> = {
desc: '합계 큰 순으로 정렬했어요',
asc: '합계 작은 순으로 정렬했어요',
none: '정렬하지 않아요. 줄이 처음 나타난 순서예요',
};
function showChoice(order: Order): void {
const select = document.getElementById('order');
if (select instanceof HTMLSelectElement && select.value !== order) select.value = order;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({ ko: WORDS.desc, en: WORDS_EN.desc });
// 매출 머리글을 눌러 정렬하면 그룹 순서의 방향이 그 방향을 따라가요. 선택 칸도 실제 순서에 맞춰 바꿔요.
const off = api.on('sortChanged', ({ sortModel }) => {
const item = sortModel.find((s) => s.columnId === 'sales');
if (chosen === 'none' || !item) return showChoice(chosen);
showChoice(item.direction);
log({
ko: `매출 머리글 정렬을 따라 ${item.direction === 'asc' ? '합계 작은 순' : '합계 큰 순'}이 됐어요`,
en: `Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`,
});
});
return () => off();
}
export const actions = {
order: (api: GridApi<Row>, value?: string) => {
chosen = (value ?? 'desc') as Order;
api.setOptions({ grouping: grouping(chosen) });
say({ ko: WORDS[chosen], en: WORDS_EN[chosen] });
},
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="그룹 정렬"
[disabled]="!api"
(change)="api && actions.order(api, $any($event.target).value)"
>
<option value="desc" selected>합계 큰 순</option>
<option value="asc">합계 작은 순</option>
<option value="none">정렬 안 함</option>
</select>
</div>
<mx-grid style="height: 360px" [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;
team: string;
member: string;
sales: number;
}
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const members = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const rows: Row[] = Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
team: teams[i % 4] as string,
member: members[Math.floor(i / 4)] as string,
sales: 100 + ((i * 53) % 170),
}));
type Order = 'asc' | 'desc' | 'none';
const grouping = (order: Order): NonNullable<GridOptions<Row>['grouping']> => ({
by: ['team'],
expandDepth: 0,
// 같은 부모 안의 그룹을 sales 합계 순으로 놓아요. 없으면 줄이 처음 나타난 순서예요.
...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: '팀', width: 100 },
{ id: 'member', title: '담당자', width: 90 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
],
rows,
rowKey: 'id',
grouping: grouping('desc'),
};
let say: (message: LogText) => void = () => {};
// 사용자가 '그룹 정렬' 선택으로 고른 값. 머리글 정렬을 풀면 이 값으로 돌아가요.
let chosen: Order = 'desc';
const WORDS_EN: Record<Order, string> = {
desc: 'Sorted by total, largest first',
asc: 'Sorted by total, smallest first',
none: 'Not sorted. Rows are in the order they first appeared',
};
const WORDS: Record<Order, string> = {
desc: '합계 큰 순으로 정렬했어요',
asc: '합계 작은 순으로 정렬했어요',
none: '정렬하지 않아요. 줄이 처음 나타난 순서예요',
};
function showChoice(order: Order): void {
const select = document.getElementById('order');
if (select instanceof HTMLSelectElement && select.value !== order) select.value = order;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({ ko: WORDS.desc, en: WORDS_EN.desc });
// 매출 머리글을 눌러 정렬하면 그룹 순서의 방향이 그 방향을 따라가요. 선택 칸도 실제 순서에 맞춰 바꿔요.
const off = api.on('sortChanged', ({ sortModel }) => {
const item = sortModel.find((s) => s.columnId === 'sales');
if (chosen === 'none' || !item) return showChoice(chosen);
showChoice(item.direction);
log({
ko: `매출 머리글 정렬을 따라 ${item.direction === 'asc' ? '합계 작은 순' : '합계 큰 순'}이 됐어요`,
en: `Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`,
});
});
return () => off();
}
export const actions = {
order: (api: GridApi<Row>, value?: string) => {
chosen = (value ?? 'desc') as Order;
api.setOptions({ grouping: grouping(chosen) });
say({ ko: WORDS[chosen], en: WORDS_EN[chosen] });
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<select aria-label="Group order" id="order">
<option value="desc" selected>Largest first</option>
<option value="asc">Smallest first</option>
<option value="none">Off</option>
</select>
</div>
<div id="grid" style="height: 360px"></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('order').addEventListener('change', (event) => actions.order(api, event.target.value));const teams = ['Dev', 'Design', 'Sales', 'HR'];
const members = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Park', 'Mia Johnson'];
const rows = Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
team: teams[i % 4],
member: members[Math.floor(i / 4)],
sales: 1000 + ((i * 53) % 170) * 10,
}));
const grouping = (order) => ({
by: ['team'],
expandDepth: 0,
// Place the groups inside the same parent in order of their sales total. Without it, rows keep the order they first appeared.
...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
export const options = {
columns: [
{ id: 'team', title: 'Team', width: 100 },
{ id: 'member', title: 'Owner', width: 120 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
],
rows,
rowKey: 'id',
grouping: grouping('desc'),
};
let say = () => { };
// The value the user picked in the "group order" select. Clearing the header sort returns to this value.
let chosen = 'desc';
const WORDS = {
desc: 'Sorted by total, largest first',
asc: 'Sorted by total, smallest first',
none: 'Not sorted. Rows are in the order they first appeared',
};
function showChoice(order) {
const select = document.getElementById('order');
if (select instanceof HTMLSelectElement && select.value !== order)
select.value = order;
}
export function setup(api, log) {
say = log;
log(WORDS.desc);
// Sorting by the Sales header makes the group order follow that direction. The select is updated to match the real order.
const off = api.on('sortChanged', ({ sortModel }) => {
const item = sortModel.find((s) => s.columnId === 'sales');
if (chosen === 'none' || !item)
return showChoice(chosen);
showChoice(item.direction);
log(`Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`);
});
return () => off();
}
export const actions = {
order: (api, value) => {
chosen = (value ?? 'desc');
api.setOptions({ grouping: grouping(chosen) });
say(WORDS[chosen]);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Sort groups by their total directly</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Group order" id="order">
<option value="desc" selected>Largest first</option>
<option value="asc">Smallest first</option>
<option value="none">Off</option>
</select>
</div>
<div id="grid" style="height: 360px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const members = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Park', 'Mia Johnson'];
const rows = Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
team: teams[i % 4],
member: members[Math.floor(i / 4)],
sales: 1000 + ((i * 53) % 170) * 10,
}));
const grouping = (order) => ({
by: ['team'],
expandDepth: 0,
// Place the groups inside the same parent in order of their sales total. Without it, rows keep the order they first appeared.
...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
const options = {
columns: [
{ id: 'team', title: 'Team', width: 100 },
{ id: 'member', title: 'Owner', width: 120 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
],
rows,
rowKey: 'id',
grouping: grouping('desc'),
};
let say = () => { };
// The value the user picked in the "group order" select. Clearing the header sort returns to this value.
let chosen = 'desc';
const WORDS = {
desc: 'Sorted by total, largest first',
asc: 'Sorted by total, smallest first',
none: 'Not sorted. Rows are in the order they first appeared',
};
function showChoice(order) {
const select = document.getElementById('order');
if (select instanceof HTMLSelectElement && select.value !== order)
select.value = order;
}
function setup(api, log) {
say = log;
log(WORDS.desc);
// Sorting by the Sales header makes the group order follow that direction. The select is updated to match the real order.
const off = api.on('sortChanged', ({ sortModel }) => {
const item = sortModel.find((s) => s.columnId === 'sales');
if (chosen === 'none' || !item)
return showChoice(chosen);
showChoice(item.direction);
log(`Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`);
});
return () => off();
}
const actions = {
order: (api, value) => {
chosen = (value ?? 'desc');
api.setOptions({ grouping: grouping(chosen) });
say(WORDS[chosen]);
},
};
options.ariaLabel = "Sort groups by their total directly";
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('order').addEventListener('change', (event) => actions.order(api, event.target.value));
</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">
<select
aria-label="Group order"
disabled={!api}
onChange={(event) => api && actions.order(api, event.target.value)}
>
<option value="desc">Largest first</option>
<option value="asc">Smallest first</option>
<option value="none">Off</option>
</select>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
team: string;
member: string;
sales: number;
}
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const members = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Park', 'Mia Johnson'];
const rows: Row[] = Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
team: teams[i % 4] as string,
member: members[Math.floor(i / 4)] as string,
sales: 1000 + ((i * 53) % 170) * 10,
}));
type Order = 'asc' | 'desc' | 'none';
const grouping = (order: Order): NonNullable<GridOptions<Row>['grouping']> => ({
by: ['team'],
expandDepth: 0,
// Place the groups inside the same parent in order of their sales total. Without it, rows keep the order they first appeared.
...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: 'Team', width: 100 },
{ id: 'member', title: 'Owner', width: 120 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
],
rows,
rowKey: 'id',
grouping: grouping('desc'),
};
let say: (message: LogText) => void = () => {};
// The value the user picked in the "group order" select. Clearing the header sort returns to this value.
let chosen: Order = 'desc';
const WORDS: Record<Order, string> = {
desc: 'Sorted by total, largest first',
asc: 'Sorted by total, smallest first',
none: 'Not sorted. Rows are in the order they first appeared',
};
function showChoice(order: Order): void {
const select = document.getElementById('order');
if (select instanceof HTMLSelectElement && select.value !== order) select.value = order;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(WORDS.desc);
// Sorting by the Sales header makes the group order follow that direction. The select is updated to match the real order.
const off = api.on('sortChanged', ({ sortModel }) => {
const item = sortModel.find((s) => s.columnId === 'sales');
if (chosen === 'none' || !item) return showChoice(chosen);
showChoice(item.direction);
log(
`Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`,
);
});
return () => off();
}
export const actions = {
order: (api: GridApi<Row>, value?: string) => {
chosen = (value ?? 'desc') as Order;
api.setOptions({ grouping: grouping(chosen) });
say(WORDS[chosen]);
},
};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">
<select
aria-label="Group order"
:disabled="!api"
@change="api && actions.order(api, ($event.target as HTMLSelectElement).value)"
>
<option value="desc" selected>Largest first</option>
<option value="asc">Smallest first</option>
<option value="none">Off</option>
</select>
</div>
<Grid style="height: 360px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
team: string;
member: string;
sales: number;
}
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const members = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Park', 'Mia Johnson'];
const rows: Row[] = Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
team: teams[i % 4] as string,
member: members[Math.floor(i / 4)] as string,
sales: 1000 + ((i * 53) % 170) * 10,
}));
type Order = 'asc' | 'desc' | 'none';
const grouping = (order: Order): NonNullable<GridOptions<Row>['grouping']> => ({
by: ['team'],
expandDepth: 0,
// Place the groups inside the same parent in order of their sales total. Without it, rows keep the order they first appeared.
...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: 'Team', width: 100 },
{ id: 'member', title: 'Owner', width: 120 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
],
rows,
rowKey: 'id',
grouping: grouping('desc'),
};
let say: (message: LogText) => void = () => {};
// The value the user picked in the "group order" select. Clearing the header sort returns to this value.
let chosen: Order = 'desc';
const WORDS: Record<Order, string> = {
desc: 'Sorted by total, largest first',
asc: 'Sorted by total, smallest first',
none: 'Not sorted. Rows are in the order they first appeared',
};
function showChoice(order: Order): void {
const select = document.getElementById('order');
if (select instanceof HTMLSelectElement && select.value !== order) select.value = order;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(WORDS.desc);
// Sorting by the Sales header makes the group order follow that direction. The select is updated to match the real order.
const off = api.on('sortChanged', ({ sortModel }) => {
const item = sortModel.find((s) => s.columnId === 'sales');
if (chosen === 'none' || !item) return showChoice(chosen);
showChoice(item.direction);
log(
`Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`,
);
});
return () => off();
}
export const actions = {
order: (api: GridApi<Row>, value?: string) => {
chosen = (value ?? 'desc') as Order;
api.setOptions({ grouping: grouping(chosen) });
say(WORDS[chosen]);
},
};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">
<select
aria-label="Group order"
[disabled]="!api"
(change)="api && actions.order(api, $any($event.target).value)"
>
<option value="desc" selected>Largest first</option>
<option value="asc">Smallest first</option>
<option value="none">Off</option>
</select>
</div>
<mx-grid style="height: 360px" [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;
export interface Row {
id: number;
team: string;
member: string;
sales: number;
}
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const members = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Park', 'Mia Johnson'];
const rows: Row[] = Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
team: teams[i % 4] as string,
member: members[Math.floor(i / 4)] as string,
sales: 1000 + ((i * 53) % 170) * 10,
}));
type Order = 'asc' | 'desc' | 'none';
const grouping = (order: Order): NonNullable<GridOptions<Row>['grouping']> => ({
by: ['team'],
expandDepth: 0,
// Place the groups inside the same parent in order of their sales total. Without it, rows keep the order they first appeared.
...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: 'Team', width: 100 },
{ id: 'member', title: 'Owner', width: 120 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
],
rows,
rowKey: 'id',
grouping: grouping('desc'),
};
let say: (message: LogText) => void = () => {};
// The value the user picked in the "group order" select. Clearing the header sort returns to this value.
let chosen: Order = 'desc';
const WORDS: Record<Order, string> = {
desc: 'Sorted by total, largest first',
asc: 'Sorted by total, smallest first',
none: 'Not sorted. Rows are in the order they first appeared',
};
function showChoice(order: Order): void {
const select = document.getElementById('order');
if (select instanceof HTMLSelectElement && select.value !== order) select.value = order;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(WORDS.desc);
// Sorting by the Sales header makes the group order follow that direction. The select is updated to match the real order.
const off = api.on('sortChanged', ({ sortModel }) => {
const item = sortModel.find((s) => s.columnId === 'sales');
if (chosen === 'none' || !item) return showChoice(chosen);
showChoice(item.direction);
log(
`Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`,
);
});
return () => off();
}
export const actions = {
order: (api: GridApi<Row>, value?: string) => {
chosen = (value ?? 'desc') as Order;
api.setOptions({ grouping: grouping(chosen) });
say(WORDS[chosen]);
},
};