그룹을 합계 순으로 정렬하기Sort groups by their total
합계가 큰 팀을 위로 올리고, 이름순으로 바꾸고, 그룹 안의 순서만 바꿔 봐요.Move the team with the largest total to the top, sort by name, or reorder only inside the groups.
코드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="sort">
<option value="none" selected>정렬 없음</option>
<option value="biggest">팀 합계 큰 순</option>
<option value="smallest">팀 합계 작은 순</option>
<option value="name">팀 이름 순</option>
<option value="inner">팀 이름 순, 그룹 안은 매출 큰 순</option>
</select>
<button type="button" id="expandAll">모두 펼치기</button>
<button type="button" id="collapseAll">모두 접기</button>
</div>
<div id="grid" style="height: 330px"></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('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));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 totals = new Map();
for (const row of rows)
totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
export const options = {
columns: [
{ id: 'team', title: '팀', width: 110 },
{ id: 'member', title: '담당자', width: 110 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
{
id: 'teamTotal',
title: '팀 합계',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => totals.get(row.team) ?? 0,
},
],
rows,
rowKey: 'id',
grouping: { by: ['team'], expandDepth: 0 },
};
const titles = {
team: '팀',
member: '담당자',
sales: '매출',
teamTotal: '팀 합계',
};
const models = {
biggest: [
{ columnId: 'teamTotal', direction: 'desc' },
{ columnId: 'sales', direction: 'desc' },
],
smallest: [
{ columnId: 'teamTotal', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
name: [{ columnId: 'team', direction: 'asc' }],
inner: [
{ columnId: 'team', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
none: [],
};
export function setup(api, log) {
return api.on('sortChanged', ({ sortModel }) => log({
ko: sortModel
.map((item) => `${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? '오름차순' : '내림차순'}`)
.join(', ') || '정렬을 풀었어요.',
en: sortModel
.map((item) => `${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`)
.join(', ') || 'Sort cleared.',
}));
}
export const actions = {
sort: (api, value) => api.setSortModel(models[value ?? 'none'] ?? []),
expandAll: (api) => api.expandAll(),
collapseAll: (api) => api.collapseAll(),
};<!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="sort">
<option value="none" selected>정렬 없음</option>
<option value="biggest">팀 합계 큰 순</option>
<option value="smallest">팀 합계 작은 순</option>
<option value="name">팀 이름 순</option>
<option value="inner">팀 이름 순, 그룹 안은 매출 큰 순</option>
</select>
<button type="button" id="expandAll">모두 펼치기</button>
<button type="button" id="collapseAll">모두 접기</button>
</div>
<div id="grid" style="height: 330px"></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 totals = new Map();
for (const row of rows)
totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
const options = {
columns: [
{ id: 'team', title: '팀', width: 110 },
{ id: 'member', title: '담당자', width: 110 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
{
id: 'teamTotal',
title: '팀 합계',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => totals.get(row.team) ?? 0,
},
],
rows,
rowKey: 'id',
grouping: { by: ['team'], expandDepth: 0 },
};
const titles = {
team: '팀',
member: '담당자',
sales: '매출',
teamTotal: '팀 합계',
};
const models = {
biggest: [
{ columnId: 'teamTotal', direction: 'desc' },
{ columnId: 'sales', direction: 'desc' },
],
smallest: [
{ columnId: 'teamTotal', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
name: [{ columnId: 'team', direction: 'asc' }],
inner: [
{ columnId: 'team', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
none: [],
};
function setup(api, log) {
return api.on('sortChanged', ({ sortModel }) => log({
ko: sortModel
.map((item) => `${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? '오름차순' : '내림차순'}`)
.join(', ') || '정렬을 풀었어요.',
en: sortModel
.map((item) => `${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`)
.join(', ') || 'Sort cleared.',
}));
}
const actions = {
sort: (api, value) => api.setSortModel(models[value ?? 'none'] ?? []),
expandAll: (api) => api.expandAll(),
collapseAll: (api) => api.collapseAll(),
};
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('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(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">
<select
aria-label="정렬"
disabled={!api}
onChange={(event) => api && actions.sort(api, event.target.value)}
>
<option value="none">정렬 없음</option>
<option value="biggest">팀 합계 큰 순</option>
<option value="smallest">팀 합계 작은 순</option>
<option value="name">팀 이름 순</option>
<option value="inner">팀 이름 순, 그룹 안은 매출 큰 순</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.expandAll(api)}
>모두 펼치기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.collapseAll(api)}
>모두 접기</button>
</div>
<Grid style={{ height: 330 }} 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),
}));
// 정렬은 먼저 줄을 정렬한 다음 그룹으로 모아요. 그래서 매출로 정렬하면 각 그룹 안의 순서가 바뀌어요.
// 그룹 줄은 줄 순서에 따라 나타나기 때문에, 합계가 큰 그룹을 위로 올리려면 "팀 합계" 도우미 컬럼을 두고
// 그 컬럼으로 먼저 정렬해요.
const totals = new Map<string, number>();
for (const row of rows) totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: '팀', width: 110 },
{ id: 'member', title: '담당자', width: 110 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
{
id: 'teamTotal',
title: '팀 합계',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => totals.get(row.team) ?? 0,
},
],
rows,
rowKey: 'id',
grouping: { by: ['team'], expandDepth: 0 },
};
const titles: Record<string, string> = {
team: '팀',
member: '담당자',
sales: '매출',
teamTotal: '팀 합계',
};
const models: Record<string, { columnId: string; direction: 'asc' | 'desc' }[]> = {
biggest: [
{ columnId: 'teamTotal', direction: 'desc' },
{ columnId: 'sales', direction: 'desc' },
],
smallest: [
{ columnId: 'teamTotal', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
name: [{ columnId: 'team', direction: 'asc' }],
inner: [
{ columnId: 'team', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
none: [],
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('sortChanged', ({ sortModel }) =>
log({
ko:
sortModel
.map(
(item) =>
`${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? '오름차순' : '내림차순'}`,
)
.join(', ') || '정렬을 풀었어요.',
en:
sortModel
.map(
(item) =>
`${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`,
)
.join(', ') || 'Sort cleared.',
}),
);
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => api.setSortModel(models[value ?? 'none'] ?? []),
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};버튼을 누르면 이 예제의 코드가 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.sort(api, ($event.target as HTMLSelectElement).value)"
>
<option value="none" selected>정렬 없음</option>
<option value="biggest">팀 합계 큰 순</option>
<option value="smallest">팀 합계 작은 순</option>
<option value="name">팀 이름 순</option>
<option value="inner">팀 이름 순, 그룹 안은 매출 큰 순</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.expandAll(api)"
>모두 펼치기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.collapseAll(api)"
>모두 접기</button>
</div>
<Grid style="height: 330px" :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),
}));
// 정렬은 먼저 줄을 정렬한 다음 그룹으로 모아요. 그래서 매출로 정렬하면 각 그룹 안의 순서가 바뀌어요.
// 그룹 줄은 줄 순서에 따라 나타나기 때문에, 합계가 큰 그룹을 위로 올리려면 "팀 합계" 도우미 컬럼을 두고
// 그 컬럼으로 먼저 정렬해요.
const totals = new Map<string, number>();
for (const row of rows) totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: '팀', width: 110 },
{ id: 'member', title: '담당자', width: 110 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
{
id: 'teamTotal',
title: '팀 합계',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => totals.get(row.team) ?? 0,
},
],
rows,
rowKey: 'id',
grouping: { by: ['team'], expandDepth: 0 },
};
const titles: Record<string, string> = {
team: '팀',
member: '담당자',
sales: '매출',
teamTotal: '팀 합계',
};
const models: Record<string, { columnId: string; direction: 'asc' | 'desc' }[]> = {
biggest: [
{ columnId: 'teamTotal', direction: 'desc' },
{ columnId: 'sales', direction: 'desc' },
],
smallest: [
{ columnId: 'teamTotal', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
name: [{ columnId: 'team', direction: 'asc' }],
inner: [
{ columnId: 'team', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
none: [],
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('sortChanged', ({ sortModel }) =>
log({
ko:
sortModel
.map(
(item) =>
`${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? '오름차순' : '내림차순'}`,
)
.join(', ') || '정렬을 풀었어요.',
en:
sortModel
.map(
(item) =>
`${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`,
)
.join(', ') || 'Sort cleared.',
}),
);
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => api.setSortModel(models[value ?? 'none'] ?? []),
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};버튼을 누르면 이 예제의 코드가 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.sort(api, $any($event.target).value)"
>
<option value="none" selected>정렬 없음</option>
<option value="biggest">팀 합계 큰 순</option>
<option value="smallest">팀 합계 작은 순</option>
<option value="name">팀 이름 순</option>
<option value="inner">팀 이름 순, 그룹 안은 매출 큰 순</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.expandAll(api)"
>모두 펼치기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.collapseAll(api)"
>모두 접기</button>
</div>
<mx-grid style="height: 330px" [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),
}));
// 정렬은 먼저 줄을 정렬한 다음 그룹으로 모아요. 그래서 매출로 정렬하면 각 그룹 안의 순서가 바뀌어요.
// 그룹 줄은 줄 순서에 따라 나타나기 때문에, 합계가 큰 그룹을 위로 올리려면 "팀 합계" 도우미 컬럼을 두고
// 그 컬럼으로 먼저 정렬해요.
const totals = new Map<string, number>();
for (const row of rows) totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: '팀', width: 110 },
{ id: 'member', title: '담당자', width: 110 },
{
id: 'sales',
title: '매출(만원)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
{
id: 'teamTotal',
title: '팀 합계',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => totals.get(row.team) ?? 0,
},
],
rows,
rowKey: 'id',
grouping: { by: ['team'], expandDepth: 0 },
};
const titles: Record<string, string> = {
team: '팀',
member: '담당자',
sales: '매출',
teamTotal: '팀 합계',
};
const models: Record<string, { columnId: string; direction: 'asc' | 'desc' }[]> = {
biggest: [
{ columnId: 'teamTotal', direction: 'desc' },
{ columnId: 'sales', direction: 'desc' },
],
smallest: [
{ columnId: 'teamTotal', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
name: [{ columnId: 'team', direction: 'asc' }],
inner: [
{ columnId: 'team', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
none: [],
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('sortChanged', ({ sortModel }) =>
log({
ko:
sortModel
.map(
(item) =>
`${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? '오름차순' : '내림차순'}`,
)
.join(', ') || '정렬을 풀었어요.',
en:
sortModel
.map(
(item) =>
`${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`,
)
.join(', ') || 'Sort cleared.',
}),
);
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => api.setSortModel(models[value ?? 'none'] ?? []),
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};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="Sort" id="sort">
<option value="none" selected>No sort</option>
<option value="biggest">Team total, largest first</option>
<option value="smallest">Team total, smallest first</option>
<option value="name">Team name</option>
<option value="inner">Team name; sales desc inside groups</option>
</select>
<button type="button" id="expandAll">Expand all</button>
<button type="button" id="collapseAll">Collapse all</button>
</div>
<div id="grid" style="height: 330px"></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('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));const teams = ['Alpha', 'Beta', 'Gamma', 'Delta'];
const members = ['Emma Stone', 'Liam Carter', 'Mia Johnson', 'Ethan Brown', 'Zoe Miller'];
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,
}));
// Sorting orders the rows first and then collects them into groups. So sorting by sales changes the order inside each group.
// Group rows appear according to row order, so to move the groups with the biggest totals to the top,
// add a "Team total" helper column and sort by it first.
const totals = new Map();
for (const row of rows)
totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
export const options = {
columns: [
{ id: 'team', title: 'Team', width: 110 },
{ id: 'member', title: 'Owner', width: 120 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
{
id: 'teamTotal',
title: 'Team total',
kind: 'number',
width: 130,
align: 'end',
getValue: (row) => totals.get(row.team) ?? 0,
},
],
rows,
rowKey: 'id',
grouping: { by: ['team'], expandDepth: 0 },
};
const titles = {
team: 'Team',
member: 'Owner',
sales: 'Sales',
teamTotal: 'Team total',
};
const models = {
biggest: [
{ columnId: 'teamTotal', direction: 'desc' },
{ columnId: 'sales', direction: 'desc' },
],
smallest: [
{ columnId: 'teamTotal', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
name: [{ columnId: 'team', direction: 'asc' }],
inner: [
{ columnId: 'team', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
none: [],
};
export function setup(api, log) {
return api.on('sortChanged', ({ sortModel }) => log(sortModel
.map((item) => `${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`)
.join(', ') || 'Sort cleared.'));
}
export const actions = {
sort: (api, value) => api.setSortModel(models[value ?? 'none'] ?? []),
expandAll: (api) => api.expandAll(),
collapseAll: (api) => api.collapseAll(),
};<!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</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Sort" id="sort">
<option value="none" selected>No sort</option>
<option value="biggest">Team total, largest first</option>
<option value="smallest">Team total, smallest first</option>
<option value="name">Team name</option>
<option value="inner">Team name; sales desc inside groups</option>
</select>
<button type="button" id="expandAll">Expand all</button>
<button type="button" id="collapseAll">Collapse all</button>
</div>
<div id="grid" style="height: 330px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const teams = ['Alpha', 'Beta', 'Gamma', 'Delta'];
const members = ['Emma Stone', 'Liam Carter', 'Mia Johnson', 'Ethan Brown', 'Zoe Miller'];
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,
}));
// Sorting orders the rows first and then collects them into groups. So sorting by sales changes the order inside each group.
// Group rows appear according to row order, so to move the groups with the biggest totals to the top,
// add a "Team total" helper column and sort by it first.
const totals = new Map();
for (const row of rows)
totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
const options = {
columns: [
{ id: 'team', title: 'Team', width: 110 },
{ id: 'member', title: 'Owner', width: 120 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
{
id: 'teamTotal',
title: 'Team total',
kind: 'number',
width: 130,
align: 'end',
getValue: (row) => totals.get(row.team) ?? 0,
},
],
rows,
rowKey: 'id',
grouping: { by: ['team'], expandDepth: 0 },
};
const titles = {
team: 'Team',
member: 'Owner',
sales: 'Sales',
teamTotal: 'Team total',
};
const models = {
biggest: [
{ columnId: 'teamTotal', direction: 'desc' },
{ columnId: 'sales', direction: 'desc' },
],
smallest: [
{ columnId: 'teamTotal', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
name: [{ columnId: 'team', direction: 'asc' }],
inner: [
{ columnId: 'team', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
none: [],
};
function setup(api, log) {
return api.on('sortChanged', ({ sortModel }) => log(sortModel
.map((item) => `${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`)
.join(', ') || 'Sort cleared.'));
}
const actions = {
sort: (api, value) => api.setSortModel(models[value ?? 'none'] ?? []),
expandAll: (api) => api.expandAll(),
collapseAll: (api) => api.collapseAll(),
};
options.ariaLabel = "Sort groups by their total";
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('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(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">
<select
aria-label="Sort"
disabled={!api}
onChange={(event) => api && actions.sort(api, event.target.value)}
>
<option value="none">No sort</option>
<option value="biggest">Team total, largest first</option>
<option value="smallest">Team total, smallest first</option>
<option value="name">Team name</option>
<option value="inner">Team name; sales desc inside groups</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.expandAll(api)}
>Expand all</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.collapseAll(api)}
>Collapse all</button>
</div>
<Grid style={{ height: 330 }} 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 = ['Alpha', 'Beta', 'Gamma', 'Delta'];
const members = ['Emma Stone', 'Liam Carter', 'Mia Johnson', 'Ethan Brown', 'Zoe Miller'];
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,
}));
// Sorting orders the rows first and then collects them into groups. So sorting by sales changes the order inside each group.
// Group rows appear according to row order, so to move the groups with the biggest totals to the top,
// add a "Team total" helper column and sort by it first.
const totals = new Map<string, number>();
for (const row of rows) totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: 'Team', width: 110 },
{ id: 'member', title: 'Owner', width: 120 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
{
id: 'teamTotal',
title: 'Team total',
kind: 'number',
width: 130,
align: 'end',
getValue: (row) => totals.get(row.team) ?? 0,
},
],
rows,
rowKey: 'id',
grouping: { by: ['team'], expandDepth: 0 },
};
const titles: Record<string, string> = {
team: 'Team',
member: 'Owner',
sales: 'Sales',
teamTotal: 'Team total',
};
const models: Record<string, { columnId: string; direction: 'asc' | 'desc' }[]> = {
biggest: [
{ columnId: 'teamTotal', direction: 'desc' },
{ columnId: 'sales', direction: 'desc' },
],
smallest: [
{ columnId: 'teamTotal', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
name: [{ columnId: 'team', direction: 'asc' }],
inner: [
{ columnId: 'team', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
none: [],
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('sortChanged', ({ sortModel }) =>
log(
sortModel
.map(
(item) =>
`${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`,
)
.join(', ') || 'Sort cleared.',
),
);
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => api.setSortModel(models[value ?? 'none'] ?? []),
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};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="Sort"
:disabled="!api"
@change="api && actions.sort(api, ($event.target as HTMLSelectElement).value)"
>
<option value="none" selected>No sort</option>
<option value="biggest">Team total, largest first</option>
<option value="smallest">Team total, smallest first</option>
<option value="name">Team name</option>
<option value="inner">Team name; sales desc inside groups</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.expandAll(api)"
>Expand all</button>
<button
type="button"
:disabled="!api"
@click="api && actions.collapseAll(api)"
>Collapse all</button>
</div>
<Grid style="height: 330px" :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 = ['Alpha', 'Beta', 'Gamma', 'Delta'];
const members = ['Emma Stone', 'Liam Carter', 'Mia Johnson', 'Ethan Brown', 'Zoe Miller'];
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,
}));
// Sorting orders the rows first and then collects them into groups. So sorting by sales changes the order inside each group.
// Group rows appear according to row order, so to move the groups with the biggest totals to the top,
// add a "Team total" helper column and sort by it first.
const totals = new Map<string, number>();
for (const row of rows) totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: 'Team', width: 110 },
{ id: 'member', title: 'Owner', width: 120 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
{
id: 'teamTotal',
title: 'Team total',
kind: 'number',
width: 130,
align: 'end',
getValue: (row) => totals.get(row.team) ?? 0,
},
],
rows,
rowKey: 'id',
grouping: { by: ['team'], expandDepth: 0 },
};
const titles: Record<string, string> = {
team: 'Team',
member: 'Owner',
sales: 'Sales',
teamTotal: 'Team total',
};
const models: Record<string, { columnId: string; direction: 'asc' | 'desc' }[]> = {
biggest: [
{ columnId: 'teamTotal', direction: 'desc' },
{ columnId: 'sales', direction: 'desc' },
],
smallest: [
{ columnId: 'teamTotal', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
name: [{ columnId: 'team', direction: 'asc' }],
inner: [
{ columnId: 'team', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
none: [],
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('sortChanged', ({ sortModel }) =>
log(
sortModel
.map(
(item) =>
`${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`,
)
.join(', ') || 'Sort cleared.',
),
);
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => api.setSortModel(models[value ?? 'none'] ?? []),
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};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="Sort"
[disabled]="!api"
(change)="api && actions.sort(api, $any($event.target).value)"
>
<option value="none" selected>No sort</option>
<option value="biggest">Team total, largest first</option>
<option value="smallest">Team total, smallest first</option>
<option value="name">Team name</option>
<option value="inner">Team name; sales desc inside groups</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.expandAll(api)"
>Expand all</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.collapseAll(api)"
>Collapse all</button>
</div>
<mx-grid style="height: 330px" [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 = ['Alpha', 'Beta', 'Gamma', 'Delta'];
const members = ['Emma Stone', 'Liam Carter', 'Mia Johnson', 'Ethan Brown', 'Zoe Miller'];
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,
}));
// Sorting orders the rows first and then collects them into groups. So sorting by sales changes the order inside each group.
// Group rows appear according to row order, so to move the groups with the biggest totals to the top,
// add a "Team total" helper column and sort by it first.
const totals = new Map<string, number>();
for (const row of rows) totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
export const options: GridOptions<Row> = {
columns: [
{ id: 'team', title: 'Team', width: 110 },
{ id: 'member', title: 'Owner', width: 120 },
{
id: 'sales',
title: 'Sales ($)',
kind: 'number',
width: 110,
align: 'end',
aggregate: 'sum',
},
{
id: 'teamTotal',
title: 'Team total',
kind: 'number',
width: 130,
align: 'end',
getValue: (row) => totals.get(row.team) ?? 0,
},
],
rows,
rowKey: 'id',
grouping: { by: ['team'], expandDepth: 0 },
};
const titles: Record<string, string> = {
team: 'Team',
member: 'Owner',
sales: 'Sales',
teamTotal: 'Team total',
};
const models: Record<string, { columnId: string; direction: 'asc' | 'desc' }[]> = {
biggest: [
{ columnId: 'teamTotal', direction: 'desc' },
{ columnId: 'sales', direction: 'desc' },
],
smallest: [
{ columnId: 'teamTotal', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
name: [{ columnId: 'team', direction: 'asc' }],
inner: [
{ columnId: 'team', direction: 'asc' },
{ columnId: 'sales', direction: 'desc' },
],
none: [],
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('sortChanged', ({ sortModel }) =>
log(
sortModel
.map(
(item) =>
`${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`,
)
.join(', ') || 'Sort cleared.',
),
);
}
export const actions = {
sort: (api: GridApi<Row>, value?: string) => api.setSortModel(models[value ?? 'none'] ?? []),
expandAll: (api: GridApi<Row>) => api.expandAll(),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};