그룹 안에서 비율·순위로 보기Show numbers as shares and ranks inside groups
컬럼 showAs로 숫자를 그룹 합계 대비 %, 전체 합계 대비 %, 그룹 안 순위로 보여 줘요. 표시만 바뀌고 값·정렬·편집은 그대로예요. 내보내기는 exportShowAs를 켜야 보이는 값을 써요.A column's showAs shows a number as a percentage of its group, a percentage of the grand total or a rank inside the group. Only the display changes; the value, sorting and editing stay. Exports use the displayed value only with exportShowAs.
코드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)
이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<select aria-label="보기 방식" id="showAs">
<option value="value">값 그대로</option>
<option value="percentOfGroup" selected>그룹 합계 대비</option>
<option value="percentOfTotal">전체 합계 대비</option>
<option value="rankInGroup">그룹 안 순위</option>
</select>
<select aria-label="내보낼 때" id="exportShown">
<option value="no" selected>원래 값</option>
<option value="yes">보이는 값</option>
</select>
<button type="button" id="csv">CSV</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('showAs').addEventListener('change', (event) => actions.showAs(api, event.target.value));
document.getElementById('exportShown').addEventListener('change', (event) => actions.exportShown(api, event.target.value));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));import { withExport } from '@maxgrid/export';
const regions = ['서울', '부산', '대구'];
const products = ['무선 이어폰', '노트북', '스마트워치', '태블릿', '보조배터리', '스피커'];
const rows = Array.from({ length: 18 }, (_, i) => ({
id: i + 1,
region: regions[Math.floor(i / 6)],
product: products[i % 6],
amount: 120 + ((i * 53) % 400),
}));
// showAs는 그룹 안에서 숫자 컬럼이 보이는 방식만 바꿔요(값·정렬·편집 값은 그대로). 퍼센트는 소수 1자리예요.
export const options = {
columns: [
{ id: 'product', title: '상품', width: 160 },
{ id: 'region', title: '지역', width: 100 },
{
id: 'amount',
title: '금액 ($)',
kind: 'number',
width: 140,
align: 'end',
aggregate: 'sum',
showAs: 'percentOfGroup',
exportShowAs: false,
},
],
rows,
rowKey: 'id',
grouping: { by: ['region'], expandDepth: 'all' },
summary: true,
};
export function setup(_api, log) {
log({
ko: '"보기 방식"을 바꿔 금액이 그룹 안 비율·전체 비율·순위로 보이게 해 보세요. 값은 그대로예요.',
en: 'Change "Show as" to see the amount as a share of its group, of the total, or as a rank. The value itself does not change.',
});
return () => undefined;
}
export const actions = {
showAs: (api, value) => api.updateColumn('amount', {
showAs: (value ?? 'value'),
}),
exportShown: (api, value) => api.updateColumn('amount', { exportShowAs: value === 'yes' }),
csv: (api) => void withExport(api).downloadCsv('group-show-as.csv', { hierarchy: true, bom: true }),
}; 이 HTML은 추가 번들(위 script 태그)도 함께 불러오고 전역 변수로 써요. 별도 설치는 필요 없어요.
<!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="showAs">
<option value="value">값 그대로</option>
<option value="percentOfGroup" selected>그룹 합계 대비</option>
<option value="percentOfTotal">전체 합계 대비</option>
<option value="rankInGroup">그룹 안 순위</option>
</select>
<select aria-label="내보낼 때" id="exportShown">
<option value="no" selected>원래 값</option>
<option value="yes">보이는 값</option>
</select>
<button type="button" id="csv">CSV</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 src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script>
const { withExport } = MaxGridExport;
const regions = ['서울', '부산', '대구'];
const products = ['무선 이어폰', '노트북', '스마트워치', '태블릿', '보조배터리', '스피커'];
const rows = Array.from({ length: 18 }, (_, i) => ({
id: i + 1,
region: regions[Math.floor(i / 6)],
product: products[i % 6],
amount: 120 + ((i * 53) % 400),
}));
// showAs는 그룹 안에서 숫자 컬럼이 보이는 방식만 바꿔요(값·정렬·편집 값은 그대로). 퍼센트는 소수 1자리예요.
const options = {
columns: [
{ id: 'product', title: '상품', width: 160 },
{ id: 'region', title: '지역', width: 100 },
{
id: 'amount',
title: '금액 ($)',
kind: 'number',
width: 140,
align: 'end',
aggregate: 'sum',
showAs: 'percentOfGroup',
exportShowAs: false,
},
],
rows,
rowKey: 'id',
grouping: { by: ['region'], expandDepth: 'all' },
summary: true,
};
function setup(_api, log) {
log({
ko: '"보기 방식"을 바꿔 금액이 그룹 안 비율·전체 비율·순위로 보이게 해 보세요. 값은 그대로예요.',
en: 'Change "Show as" to see the amount as a share of its group, of the total, or as a rank. The value itself does not change.',
});
return () => undefined;
}
const actions = {
showAs: (api, value) => api.updateColumn('amount', {
showAs: (value ?? 'value'),
}),
exportShown: (api, value) => api.updateColumn('amount', { exportShowAs: value === 'yes' }),
csv: (api) => void withExport(api).downloadCsv('group-show-as.csv', { hierarchy: true, bom: true }),
};
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('showAs').addEventListener('change', (event) => actions.showAs(api, event.target.value));
document.getElementById('exportShown').addEventListener('change', (event) => actions.exportShown(api, event.target.value));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
</script>
</body>
</html> 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/react @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 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.showAs(api, event.target.value)}
>
<option value="value">값 그대로</option>
<option value="percentOfGroup">그룹 합계 대비</option>
<option value="percentOfTotal">전체 합계 대비</option>
<option value="rankInGroup">그룹 안 순위</option>
</select>
<select defaultValue="percentOfGroup"
aria-label="내보낼 때"
disabled={!api}
onChange={(event) => api && actions.exportShown(api, event.target.value)}
>
<option value="no">원래 값</option>
<option value="yes">보이는 값</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.csv(api)}
>CSV</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
product: string;
amount: number;
}
const regions = ['서울', '부산', '대구'];
const products = ['무선 이어폰', '노트북', '스마트워치', '태블릿', '보조배터리', '스피커'];
const rows: Row[] = Array.from({ length: 18 }, (_, i) => ({
id: i + 1,
region: regions[Math.floor(i / 6)] as string,
product: products[i % 6] as string,
amount: 120 + ((i * 53) % 400),
}));
// showAs는 그룹 안에서 숫자 컬럼이 보이는 방식만 바꿔요(값·정렬·편집 값은 그대로). 퍼센트는 소수 1자리예요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'product', title: '상품', width: 160 },
{ id: 'region', title: '지역', width: 100 },
{
id: 'amount',
title: '금액 ($)',
kind: 'number',
width: 140,
align: 'end',
aggregate: 'sum',
showAs: 'percentOfGroup',
exportShowAs: false,
},
],
rows,
rowKey: 'id',
grouping: { by: ['region'], expandDepth: 'all' },
summary: true,
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '"보기 방식"을 바꿔 금액이 그룹 안 비율·전체 비율·순위로 보이게 해 보세요. 값은 그대로예요.',
en: 'Change "Show as" to see the amount as a share of its group, of the total, or as a rank. The value itself does not change.',
});
return () => undefined;
}
export const actions = {
showAs: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', {
showAs: (value ?? 'value') as 'value' | 'percentOfGroup' | 'percentOfTotal' | 'rankInGroup',
}),
exportShown: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', { exportShowAs: value === 'yes' }),
csv: (api: GridApi<Row>) =>
void withExport(api).downloadCsv('group-show-as.csv', { hierarchy: true, bom: true }),
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/vue @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 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.showAs(api, ($event.target as HTMLSelectElement).value)"
>
<option value="value">값 그대로</option>
<option value="percentOfGroup" selected>그룹 합계 대비</option>
<option value="percentOfTotal">전체 합계 대비</option>
<option value="rankInGroup">그룹 안 순위</option>
</select>
<select
aria-label="내보낼 때"
:disabled="!api"
@change="api && actions.exportShown(api, ($event.target as HTMLSelectElement).value)"
>
<option value="no" selected>원래 값</option>
<option value="yes">보이는 값</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.csv(api)">CSV</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
product: string;
amount: number;
}
const regions = ['서울', '부산', '대구'];
const products = ['무선 이어폰', '노트북', '스마트워치', '태블릿', '보조배터리', '스피커'];
const rows: Row[] = Array.from({ length: 18 }, (_, i) => ({
id: i + 1,
region: regions[Math.floor(i / 6)] as string,
product: products[i % 6] as string,
amount: 120 + ((i * 53) % 400),
}));
// showAs는 그룹 안에서 숫자 컬럼이 보이는 방식만 바꿔요(값·정렬·편집 값은 그대로). 퍼센트는 소수 1자리예요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'product', title: '상품', width: 160 },
{ id: 'region', title: '지역', width: 100 },
{
id: 'amount',
title: '금액 ($)',
kind: 'number',
width: 140,
align: 'end',
aggregate: 'sum',
showAs: 'percentOfGroup',
exportShowAs: false,
},
],
rows,
rowKey: 'id',
grouping: { by: ['region'], expandDepth: 'all' },
summary: true,
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '"보기 방식"을 바꿔 금액이 그룹 안 비율·전체 비율·순위로 보이게 해 보세요. 값은 그대로예요.',
en: 'Change "Show as" to see the amount as a share of its group, of the total, or as a rank. The value itself does not change.',
});
return () => undefined;
}
export const actions = {
showAs: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', {
showAs: (value ?? 'value') as 'value' | 'percentOfGroup' | 'percentOfTotal' | 'rankInGroup',
}),
exportShown: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', { exportShowAs: value === 'yes' }),
csv: (api: GridApi<Row>) =>
void withExport(api).downloadCsv('group-show-as.csv', { hierarchy: true, bom: true }),
}; 이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i @maxgrid/angular @maxgrid/export로 설치하세요.
버튼을 누르면 이 예제의 코드가 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.showAs(api, $any($event.target).value)"
>
<option value="value">값 그대로</option>
<option value="percentOfGroup" selected>그룹 합계 대비</option>
<option value="percentOfTotal">전체 합계 대비</option>
<option value="rankInGroup">그룹 안 순위</option>
</select>
<select
aria-label="내보낼 때"
[disabled]="!api"
(change)="api && actions.exportShown(api, $any($event.target).value)"
>
<option value="no" selected>원래 값</option>
<option value="yes">보이는 값</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.csv(api)"
>CSV</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 { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
product: string;
amount: number;
}
const regions = ['서울', '부산', '대구'];
const products = ['무선 이어폰', '노트북', '스마트워치', '태블릿', '보조배터리', '스피커'];
const rows: Row[] = Array.from({ length: 18 }, (_, i) => ({
id: i + 1,
region: regions[Math.floor(i / 6)] as string,
product: products[i % 6] as string,
amount: 120 + ((i * 53) % 400),
}));
// showAs는 그룹 안에서 숫자 컬럼이 보이는 방식만 바꿔요(값·정렬·편집 값은 그대로). 퍼센트는 소수 1자리예요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'product', title: '상품', width: 160 },
{ id: 'region', title: '지역', width: 100 },
{
id: 'amount',
title: '금액 ($)',
kind: 'number',
width: 140,
align: 'end',
aggregate: 'sum',
showAs: 'percentOfGroup',
exportShowAs: false,
},
],
rows,
rowKey: 'id',
grouping: { by: ['region'], expandDepth: 'all' },
summary: true,
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '"보기 방식"을 바꿔 금액이 그룹 안 비율·전체 비율·순위로 보이게 해 보세요. 값은 그대로예요.',
en: 'Change "Show as" to see the amount as a share of its group, of the total, or as a rank. The value itself does not change.',
});
return () => undefined;
}
export const actions = {
showAs: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', {
showAs: (value ?? 'value') as 'value' | 'percentOfGroup' | 'percentOfTotal' | 'rankInGroup',
}),
exportShown: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', { exportShowAs: value === 'yes' }),
csv: (api: GridApi<Row>) =>
void withExport(api).downloadCsv('group-show-as.csv', { hierarchy: true, bom: true }),
}; This example needs an extra package. To run it locally, install with npm i maxgrid @maxgrid/export.
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="Show as" id="showAs">
<option value="value">Value</option>
<option value="percentOfGroup" selected>Share of group</option>
<option value="percentOfTotal">Share of total</option>
<option value="rankInGroup">Rank in group</option>
</select>
<select aria-label="On export" id="exportShown">
<option value="no" selected>Real value</option>
<option value="yes">Displayed value</option>
</select>
<button type="button" id="csv">CSV</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('showAs').addEventListener('change', (event) => actions.showAs(api, event.target.value));
document.getElementById('exportShown').addEventListener('change', (event) => actions.exportShown(api, event.target.value));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));import { withExport } from '@maxgrid/export';
const regions = ['New York', 'Boston', 'Austin'];
const products = ['Earbuds', 'Laptop', 'Smartwatch', 'Tablet', 'Power bank', 'Speaker'];
const rows = Array.from({ length: 18 }, (_, i) => ({
id: i + 1,
region: regions[Math.floor(i / 6)],
product: products[i % 6],
amount: 120 + ((i * 53) % 400),
}));
// showAs only changes how a number column looks inside groups (the value, sorting and the edited value stay the same). Percentages show one decimal.
export const options = {
columns: [
{ id: 'product', title: 'Product', width: 160 },
{ id: 'region', title: 'Region', width: 100 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 140,
align: 'end',
aggregate: 'sum',
showAs: 'percentOfGroup',
exportShowAs: false,
},
],
rows,
rowKey: 'id',
grouping: { by: ['region'], expandDepth: 'all' },
summary: true,
};
export function setup(_api, log) {
log('Change "Show as" to see the amount as a share of its group, of the total, or as a rank. The value itself does not change.');
return () => undefined;
}
export const actions = {
showAs: (api, value) => api.updateColumn('amount', {
showAs: (value ?? 'value'),
}),
exportShown: (api, value) => api.updateColumn('amount', { exportShowAs: value === 'yes' }),
csv: (api) => void withExport(api).downloadCsv('group-show-as.csv', { hierarchy: true, bom: true }),
};This HTML also loads an extra bundle (the extra script tag above) and uses it as a global. No install is needed.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Show numbers as shares and ranks inside groups</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Show as" id="showAs">
<option value="value">Value</option>
<option value="percentOfGroup" selected>Share of group</option>
<option value="percentOfTotal">Share of total</option>
<option value="rankInGroup">Rank in group</option>
</select>
<select aria-label="On export" id="exportShown">
<option value="no" selected>Real value</option>
<option value="yes">Displayed value</option>
</select>
<button type="button" id="csv">CSV</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 src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.export.min.js"></script>
<script>
const { withExport } = MaxGridExport;
const regions = ['New York', 'Boston', 'Austin'];
const products = ['Earbuds', 'Laptop', 'Smartwatch', 'Tablet', 'Power bank', 'Speaker'];
const rows = Array.from({ length: 18 }, (_, i) => ({
id: i + 1,
region: regions[Math.floor(i / 6)],
product: products[i % 6],
amount: 120 + ((i * 53) % 400),
}));
// showAs only changes how a number column looks inside groups (the value, sorting and the edited value stay the same). Percentages show one decimal.
const options = {
columns: [
{ id: 'product', title: 'Product', width: 160 },
{ id: 'region', title: 'Region', width: 100 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 140,
align: 'end',
aggregate: 'sum',
showAs: 'percentOfGroup',
exportShowAs: false,
},
],
rows,
rowKey: 'id',
grouping: { by: ['region'], expandDepth: 'all' },
summary: true,
};
function setup(_api, log) {
log('Change "Show as" to see the amount as a share of its group, of the total, or as a rank. The value itself does not change.');
return () => undefined;
}
const actions = {
showAs: (api, value) => api.updateColumn('amount', {
showAs: (value ?? 'value'),
}),
exportShown: (api, value) => api.updateColumn('amount', { exportShowAs: value === 'yes' }),
csv: (api) => void withExport(api).downloadCsv('group-show-as.csv', { hierarchy: true, bom: true }),
};
options.ariaLabel = "Show numbers as shares and ranks inside groups";
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('showAs').addEventListener('change', (event) => actions.showAs(api, event.target.value));
document.getElementById('exportShown').addEventListener('change', (event) => actions.exportShown(api, event.target.value));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
</script>
</body>
</html> This example needs an extra package. To run it locally, install with npm i @maxgrid/react @maxgrid/export.
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="Show as"
disabled={!api}
onChange={(event) => api && actions.showAs(api, event.target.value)}
>
<option value="value">Value</option>
<option value="percentOfGroup">Share of group</option>
<option value="percentOfTotal">Share of total</option>
<option value="rankInGroup">Rank in group</option>
</select>
<select defaultValue="percentOfGroup"
aria-label="On export"
disabled={!api}
onChange={(event) => api && actions.exportShown(api, event.target.value)}
>
<option value="no">Real value</option>
<option value="yes">Displayed value</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.csv(api)}
>CSV</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
region: string;
product: string;
amount: number;
}
const regions = ['New York', 'Boston', 'Austin'];
const products = ['Earbuds', 'Laptop', 'Smartwatch', 'Tablet', 'Power bank', 'Speaker'];
const rows: Row[] = Array.from({ length: 18 }, (_, i) => ({
id: i + 1,
region: regions[Math.floor(i / 6)] as string,
product: products[i % 6] as string,
amount: 120 + ((i * 53) % 400),
}));
// showAs only changes how a number column looks inside groups (the value, sorting and the edited value stay the same). Percentages show one decimal.
export const options: GridOptions<Row> = {
columns: [
{ id: 'product', title: 'Product', width: 160 },
{ id: 'region', title: 'Region', width: 100 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 140,
align: 'end',
aggregate: 'sum',
showAs: 'percentOfGroup',
exportShowAs: false,
},
],
rows,
rowKey: 'id',
grouping: { by: ['region'], expandDepth: 'all' },
summary: true,
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Change "Show as" to see the amount as a share of its group, of the total, or as a rank. The value itself does not change.',
);
return () => undefined;
}
export const actions = {
showAs: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', {
showAs: (value ?? 'value') as 'value' | 'percentOfGroup' | 'percentOfTotal' | 'rankInGroup',
}),
exportShown: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', { exportShowAs: value === 'yes' }),
csv: (api: GridApi<Row>) =>
void withExport(api).downloadCsv('group-show-as.csv', { hierarchy: true, bom: true }),
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/vue @maxgrid/export.
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="Show as"
:disabled="!api"
@change="api && actions.showAs(api, ($event.target as HTMLSelectElement).value)"
>
<option value="value">Value</option>
<option value="percentOfGroup" selected>Share of group</option>
<option value="percentOfTotal">Share of total</option>
<option value="rankInGroup">Rank in group</option>
</select>
<select
aria-label="On export"
:disabled="!api"
@change="api && actions.exportShown(api, ($event.target as HTMLSelectElement).value)"
>
<option value="no" selected>Real value</option>
<option value="yes">Displayed value</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.csv(api)">CSV</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
region: string;
product: string;
amount: number;
}
const regions = ['New York', 'Boston', 'Austin'];
const products = ['Earbuds', 'Laptop', 'Smartwatch', 'Tablet', 'Power bank', 'Speaker'];
const rows: Row[] = Array.from({ length: 18 }, (_, i) => ({
id: i + 1,
region: regions[Math.floor(i / 6)] as string,
product: products[i % 6] as string,
amount: 120 + ((i * 53) % 400),
}));
// showAs only changes how a number column looks inside groups (the value, sorting and the edited value stay the same). Percentages show one decimal.
export const options: GridOptions<Row> = {
columns: [
{ id: 'product', title: 'Product', width: 160 },
{ id: 'region', title: 'Region', width: 100 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 140,
align: 'end',
aggregate: 'sum',
showAs: 'percentOfGroup',
exportShowAs: false,
},
],
rows,
rowKey: 'id',
grouping: { by: ['region'], expandDepth: 'all' },
summary: true,
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Change "Show as" to see the amount as a share of its group, of the total, or as a rank. The value itself does not change.',
);
return () => undefined;
}
export const actions = {
showAs: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', {
showAs: (value ?? 'value') as 'value' | 'percentOfGroup' | 'percentOfTotal' | 'rankInGroup',
}),
exportShown: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', { exportShowAs: value === 'yes' }),
csv: (api: GridApi<Row>) =>
void withExport(api).downloadCsv('group-show-as.csv', { hierarchy: true, bom: true }),
}; This example needs an extra package. To run it locally, install with npm i @maxgrid/angular @maxgrid/export.
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="Show as"
[disabled]="!api"
(change)="api && actions.showAs(api, $any($event.target).value)"
>
<option value="value">Value</option>
<option value="percentOfGroup" selected>Share of group</option>
<option value="percentOfTotal">Share of total</option>
<option value="rankInGroup">Rank in group</option>
</select>
<select
aria-label="On export"
[disabled]="!api"
(change)="api && actions.exportShown(api, $any($event.target).value)"
>
<option value="no" selected>Real value</option>
<option value="yes">Displayed value</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.csv(api)"
>CSV</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 { withExport } from '@maxgrid/export';
import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
region: string;
product: string;
amount: number;
}
const regions = ['New York', 'Boston', 'Austin'];
const products = ['Earbuds', 'Laptop', 'Smartwatch', 'Tablet', 'Power bank', 'Speaker'];
const rows: Row[] = Array.from({ length: 18 }, (_, i) => ({
id: i + 1,
region: regions[Math.floor(i / 6)] as string,
product: products[i % 6] as string,
amount: 120 + ((i * 53) % 400),
}));
// showAs only changes how a number column looks inside groups (the value, sorting and the edited value stay the same). Percentages show one decimal.
export const options: GridOptions<Row> = {
columns: [
{ id: 'product', title: 'Product', width: 160 },
{ id: 'region', title: 'Region', width: 100 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 140,
align: 'end',
aggregate: 'sum',
showAs: 'percentOfGroup',
exportShowAs: false,
},
],
rows,
rowKey: 'id',
grouping: { by: ['region'], expandDepth: 'all' },
summary: true,
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Change "Show as" to see the amount as a share of its group, of the total, or as a rank. The value itself does not change.',
);
return () => undefined;
}
export const actions = {
showAs: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', {
showAs: (value ?? 'value') as 'value' | 'percentOfGroup' | 'percentOfTotal' | 'rankInGroup',
}),
exportShown: (api: GridApi<Row>, value?: string) =>
api.updateColumn('amount', { exportShowAs: value === 'yes' }),
csv: (api: GridApi<Row>) =>
void withExport(api).downloadCsv('group-show-as.csv', { hierarchy: true, bom: true }),
};