고른 칸의 합계와 평균을 바로 보기Instant sum and average of the cells you pick
칸을 끌어서 고르거나 행 번호를 누르면, 고른 칸의 개수·합계·평균·최댓값이 바로 계산돼요. 숫자가 아닌 칸은 알아서 빼고, 나만의 수식도 칸을 읽어서 직접 만들 수 있어요.Drag over cells or click a row number to get the count, sum, average and max of your selection at once. Text cells are skipped, and you can build your own formula from the selected cells.
코드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="formula">
<option value="basic" selected>합계·평균 (기본)</option>
<option value="full">합계·평균·최소·최대</option>
<option value="custom">내 수식: 5,000만 원 넘는 칸</option>
</select>
<button type="button" id="pickBlock">블록 고르기</button>
<button type="button" id="pickRow">대구 행 통째로</button>
<button type="button" id="pickColumn">3월 열 통째로</button>
<button type="button" id="clear">선택 지우기</button>
</div>
<div id="grid" style="height: 340px"></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('formula').addEventListener('change', (event) => actions.formula(api, event.target.value));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickRow').addEventListener('click', () => actions.pickRow(api));
document.getElementById('pickColumn').addEventListener('click', () => actions.pickColumn(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const regions = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'];
// 지역별 월 매출(만 원). 칸을 고르면 그 칸들의 합계·평균·개수를 계산해서 알려 줘요.
// 숫자가 아닌 칸('비고')은 개수에는 들어가지만 합계에는 더하지 않아요.
export const options = {
columns: [
{ id: 'region', title: '지역', width: 100 },
...MONTHS.map((id, i) => ({
id,
title: `${i + 1}월`,
kind: 'number',
width: 96,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
})),
{ id: 'note', title: '비고', width: 140 },
],
rows: regions.map((region, i) => ({
id: i + 1,
region,
m1: 3700 + ((i * 910) % 6000),
m2: 1700 + ((i * 1230) % 8000),
m3: 1100 + ((i * 570) % 5000),
m4: 2900 + ((i * 2130) % 9000),
m5: 2400 + ((i * 780) % 6500),
m6: 3100 + ((i * 1470) % 7000),
note: i % 3 === 0 ? '목표 초과' : '',
})),
rowKey: 'id',
// 왼쪽 행 번호를 누르면 그 행 전체가 선택돼요(Shift는 행 범위, Ctrl은 더하기).
showRowNumbers: true,
cellSelection: 'multiple',
};
const won = (n) => n === null ? '-' : `${Math.round(n).toLocaleString('ko-KR')}만원`;
let formula = 'basic';
let say = () => { };
// 고른 칸을 읽어 한 줄 요약을 만들어요. getCellStats()가 기본 계산을 해 주고,
// 나만의 수식은 getSelectedCells()로 칸을 하나씩 읽어서 직접 계산해요.
function summarize(api) {
const cells = api.getSelectedCells();
if (cells.length === 0)
return L('고른 칸이 없어요. 칸을 끌거나 왼쪽 행 번호를 눌러 보세요', 'No cells selected. Drag across cells or click a row number on the left');
const s = api.getCellStats();
const base = L(`${s.count}칸 선택 (숫자 ${s.numberCount}칸)`, `${s.count} cells selected (${s.numberCount} numeric)`);
if (formula === 'full') {
return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)} · ${L('최소', 'Min')} ${won(s.min)} · ${L('최대', 'Max')} ${won(s.max)}`;
}
if (formula === 'custom') {
// 내 수식: 선택한 칸 중에서 5,000만 원을 넘긴 칸이 몇 개이고, 전체 숫자 칸의 몇 %인지.
const over = cells.filter((c) => {
const v = api.getRowByKey(c.rowKey)?.[c.columnId];
return typeof v === 'number' && v > 5000;
}).length;
const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
return `${base} · ${L(`5,000만 원 넘는 칸 ${over}개`, `${over} cells over 50 million KRW`)} (${pct}%)`;
}
return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)}`;
}
export function setup(api, log) {
say = log;
log({
ko: '칸을 끌어 보세요. 고른 칸의 개수·합계·평균이 여기에 나와요.',
en: 'Drag across cells. The count, sum and average of the selection appear here.',
});
const off = api.on('cellSelectionChanged', () => log(summarize(api)));
return () => off();
}
export const actions = {
// 계산 방식을 바꾸면 지금 고른 칸으로 다시 계산해서 보여 줘요.
formula: (api, value) => {
formula = value ?? 'basic';
say(summarize(api));
},
// 코드로 고르기: 서울~울산 지역의 2월~4월 칸 묶음
pickBlock: (api) => api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
// 행 번호를 누른 것과 같아요: 3번째 행(대구)의 모든 칸.
pickRow: (api) => api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
// 3월 열 전체
pickColumn: (api) => api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
clear: (api) => api.clearCellSelection(),
};<!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="formula">
<option value="basic" selected>합계·평균 (기본)</option>
<option value="full">합계·평균·최소·최대</option>
<option value="custom">내 수식: 5,000만 원 넘는 칸</option>
</select>
<button type="button" id="pickBlock">블록 고르기</button>
<button type="button" id="pickRow">대구 행 통째로</button>
<button type="button" id="pickColumn">3월 열 통째로</button>
<button type="button" id="clear">선택 지우기</button>
</div>
<div id="grid" style="height: 340px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const regions = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'];
// 지역별 월 매출(만 원). 칸을 고르면 그 칸들의 합계·평균·개수를 계산해서 알려 줘요.
// 숫자가 아닌 칸('비고')은 개수에는 들어가지만 합계에는 더하지 않아요.
const options = {
columns: [
{ id: 'region', title: '지역', width: 100 },
...MONTHS.map((id, i) => ({
id,
title: `${i + 1}월`,
kind: 'number',
width: 96,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
})),
{ id: 'note', title: '비고', width: 140 },
],
rows: regions.map((region, i) => ({
id: i + 1,
region,
m1: 3700 + ((i * 910) % 6000),
m2: 1700 + ((i * 1230) % 8000),
m3: 1100 + ((i * 570) % 5000),
m4: 2900 + ((i * 2130) % 9000),
m5: 2400 + ((i * 780) % 6500),
m6: 3100 + ((i * 1470) % 7000),
note: i % 3 === 0 ? '목표 초과' : '',
})),
rowKey: 'id',
// 왼쪽 행 번호를 누르면 그 행 전체가 선택돼요(Shift는 행 범위, Ctrl은 더하기).
showRowNumbers: true,
cellSelection: 'multiple',
};
const won = (n) => n === null ? '-' : `${Math.round(n).toLocaleString('ko-KR')}만원`;
let formula = 'basic';
let say = () => { };
// 고른 칸을 읽어 한 줄 요약을 만들어요. getCellStats()가 기본 계산을 해 주고,
// 나만의 수식은 getSelectedCells()로 칸을 하나씩 읽어서 직접 계산해요.
function summarize(api) {
const cells = api.getSelectedCells();
if (cells.length === 0)
return L('고른 칸이 없어요. 칸을 끌거나 왼쪽 행 번호를 눌러 보세요', 'No cells selected. Drag across cells or click a row number on the left');
const s = api.getCellStats();
const base = L(`${s.count}칸 선택 (숫자 ${s.numberCount}칸)`, `${s.count} cells selected (${s.numberCount} numeric)`);
if (formula === 'full') {
return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)} · ${L('최소', 'Min')} ${won(s.min)} · ${L('최대', 'Max')} ${won(s.max)}`;
}
if (formula === 'custom') {
// 내 수식: 선택한 칸 중에서 5,000만 원을 넘긴 칸이 몇 개이고, 전체 숫자 칸의 몇 %인지.
const over = cells.filter((c) => {
const v = api.getRowByKey(c.rowKey)?.[c.columnId];
return typeof v === 'number' && v > 5000;
}).length;
const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
return `${base} · ${L(`5,000만 원 넘는 칸 ${over}개`, `${over} cells over 50 million KRW`)} (${pct}%)`;
}
return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)}`;
}
function setup(api, log) {
say = log;
log({
ko: '칸을 끌어 보세요. 고른 칸의 개수·합계·평균이 여기에 나와요.',
en: 'Drag across cells. The count, sum and average of the selection appear here.',
});
const off = api.on('cellSelectionChanged', () => log(summarize(api)));
return () => off();
}
const actions = {
// 계산 방식을 바꾸면 지금 고른 칸으로 다시 계산해서 보여 줘요.
formula: (api, value) => {
formula = value ?? 'basic';
say(summarize(api));
},
// 코드로 고르기: 서울~울산 지역의 2월~4월 칸 묶음
pickBlock: (api) => api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
// 행 번호를 누른 것과 같아요: 3번째 행(대구)의 모든 칸.
pickRow: (api) => api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
// 3월 열 전체
pickColumn: (api) => api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
clear: (api) => api.clearCellSelection(),
};
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('formula').addEventListener('change', (event) => actions.formula(api, event.target.value));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickRow').addEventListener('click', () => actions.pickRow(api));
document.getElementById('pickColumn').addEventListener('click', () => actions.pickColumn(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="계산 방식"
disabled={!api}
onChange={(event) => api && actions.formula(api, event.target.value)}
>
<option value="basic">합계·평균 (기본)</option>
<option value="full">합계·평균·최소·최대</option>
<option value="custom">내 수식: 5,000만 원 넘는 칸</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pickBlock(api)}
>블록 고르기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pickRow(api)}
>대구 행 통째로</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pickColumn(api)}
>3월 열 통째로</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>선택 지우기</button>
</div>
<Grid style={{ height: 340 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
m1: number;
m2: number;
m3: number;
m4: number;
m5: number;
m6: number;
note: string;
}
const regions = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'] as const;
// 지역별 월 매출(만 원). 칸을 고르면 그 칸들의 합계·평균·개수를 계산해서 알려 줘요.
// 숫자가 아닌 칸('비고')은 개수에는 들어가지만 합계에는 더하지 않아요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: '지역', width: 100 },
...MONTHS.map((id, i) => ({
id,
title: `${i + 1}월`,
kind: 'number' as const,
width: 96,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR'),
})),
{ id: 'note', title: '비고', width: 140 },
],
rows: regions.map((region, i) => ({
id: i + 1,
region,
m1: 3700 + ((i * 910) % 6000),
m2: 1700 + ((i * 1230) % 8000),
m3: 1100 + ((i * 570) % 5000),
m4: 2900 + ((i * 2130) % 9000),
m5: 2400 + ((i * 780) % 6500),
m6: 3100 + ((i * 1470) % 7000),
note: i % 3 === 0 ? '목표 초과' : '',
})),
rowKey: 'id',
// 왼쪽 행 번호를 누르면 그 행 전체가 선택돼요(Shift는 행 범위, Ctrl은 더하기).
showRowNumbers: true,
cellSelection: 'multiple',
};
const won = (n: number | null): string =>
n === null ? '-' : `${Math.round(n).toLocaleString('ko-KR')}만원`;
let formula = 'basic';
let say: (message: LogText) => void = () => {};
// 고른 칸을 읽어 한 줄 요약을 만들어요. getCellStats()가 기본 계산을 해 주고,
// 나만의 수식은 getSelectedCells()로 칸을 하나씩 읽어서 직접 계산해요.
function summarize(api: GridApi<Row>): string {
const cells = api.getSelectedCells();
if (cells.length === 0)
return L(
'고른 칸이 없어요. 칸을 끌거나 왼쪽 행 번호를 눌러 보세요',
'No cells selected. Drag across cells or click a row number on the left',
);
const s = api.getCellStats();
const base = L(
`${s.count}칸 선택 (숫자 ${s.numberCount}칸)`,
`${s.count} cells selected (${s.numberCount} numeric)`,
);
if (formula === 'full') {
return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)} · ${L('최소', 'Min')} ${won(s.min)} · ${L('최대', 'Max')} ${won(s.max)}`;
}
if (formula === 'custom') {
// 내 수식: 선택한 칸 중에서 5,000만 원을 넘긴 칸이 몇 개이고, 전체 숫자 칸의 몇 %인지.
const over = cells.filter((c) => {
const v = (api.getRowByKey(c.rowKey) as Row | undefined)?.[c.columnId as keyof Row];
return typeof v === 'number' && v > 5000;
}).length;
const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
return `${base} · ${L(`5,000만 원 넘는 칸 ${over}개`, `${over} cells over 50 million KRW`)} (${pct}%)`;
}
return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 끌어 보세요. 고른 칸의 개수·합계·평균이 여기에 나와요.',
en: 'Drag across cells. The count, sum and average of the selection appear here.',
});
const off = api.on('cellSelectionChanged', () => log(summarize(api)));
return () => off();
}
export const actions = {
// 계산 방식을 바꾸면 지금 고른 칸으로 다시 계산해서 보여 줘요.
formula: (api: GridApi<Row>, value?: string) => {
formula = value ?? 'basic';
say(summarize(api));
},
// 코드로 고르기: 서울~울산 지역의 2월~4월 칸 묶음
pickBlock: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
// 행 번호를 누른 것과 같아요: 3번째 행(대구)의 모든 칸.
pickRow: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
// 3월 열 전체
pickColumn: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
clear: (api: GridApi<Row>) => api.clearCellSelection(),
};버튼을 누르면 이 예제의 코드가 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.formula(api, ($event.target as HTMLSelectElement).value)"
>
<option value="basic" selected>합계·평균 (기본)</option>
<option value="full">합계·평균·최소·최대</option>
<option value="custom">내 수식: 5,000만 원 넘는 칸</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.pickBlock(api)"
>블록 고르기</button>
<button type="button" :disabled="!api" @click="api && actions.pickRow(api)">대구 행 통째로</button>
<button
type="button"
:disabled="!api"
@click="api && actions.pickColumn(api)"
>3월 열 통째로</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">선택 지우기</button>
</div>
<Grid style="height: 340px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
m1: number;
m2: number;
m3: number;
m4: number;
m5: number;
m6: number;
note: string;
}
const regions = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'] as const;
// 지역별 월 매출(만 원). 칸을 고르면 그 칸들의 합계·평균·개수를 계산해서 알려 줘요.
// 숫자가 아닌 칸('비고')은 개수에는 들어가지만 합계에는 더하지 않아요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: '지역', width: 100 },
...MONTHS.map((id, i) => ({
id,
title: `${i + 1}월`,
kind: 'number' as const,
width: 96,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR'),
})),
{ id: 'note', title: '비고', width: 140 },
],
rows: regions.map((region, i) => ({
id: i + 1,
region,
m1: 3700 + ((i * 910) % 6000),
m2: 1700 + ((i * 1230) % 8000),
m3: 1100 + ((i * 570) % 5000),
m4: 2900 + ((i * 2130) % 9000),
m5: 2400 + ((i * 780) % 6500),
m6: 3100 + ((i * 1470) % 7000),
note: i % 3 === 0 ? '목표 초과' : '',
})),
rowKey: 'id',
// 왼쪽 행 번호를 누르면 그 행 전체가 선택돼요(Shift는 행 범위, Ctrl은 더하기).
showRowNumbers: true,
cellSelection: 'multiple',
};
const won = (n: number | null): string =>
n === null ? '-' : `${Math.round(n).toLocaleString('ko-KR')}만원`;
let formula = 'basic';
let say: (message: LogText) => void = () => {};
// 고른 칸을 읽어 한 줄 요약을 만들어요. getCellStats()가 기본 계산을 해 주고,
// 나만의 수식은 getSelectedCells()로 칸을 하나씩 읽어서 직접 계산해요.
function summarize(api: GridApi<Row>): string {
const cells = api.getSelectedCells();
if (cells.length === 0)
return L(
'고른 칸이 없어요. 칸을 끌거나 왼쪽 행 번호를 눌러 보세요',
'No cells selected. Drag across cells or click a row number on the left',
);
const s = api.getCellStats();
const base = L(
`${s.count}칸 선택 (숫자 ${s.numberCount}칸)`,
`${s.count} cells selected (${s.numberCount} numeric)`,
);
if (formula === 'full') {
return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)} · ${L('최소', 'Min')} ${won(s.min)} · ${L('최대', 'Max')} ${won(s.max)}`;
}
if (formula === 'custom') {
// 내 수식: 선택한 칸 중에서 5,000만 원을 넘긴 칸이 몇 개이고, 전체 숫자 칸의 몇 %인지.
const over = cells.filter((c) => {
const v = (api.getRowByKey(c.rowKey) as Row | undefined)?.[c.columnId as keyof Row];
return typeof v === 'number' && v > 5000;
}).length;
const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
return `${base} · ${L(`5,000만 원 넘는 칸 ${over}개`, `${over} cells over 50 million KRW`)} (${pct}%)`;
}
return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 끌어 보세요. 고른 칸의 개수·합계·평균이 여기에 나와요.',
en: 'Drag across cells. The count, sum and average of the selection appear here.',
});
const off = api.on('cellSelectionChanged', () => log(summarize(api)));
return () => off();
}
export const actions = {
// 계산 방식을 바꾸면 지금 고른 칸으로 다시 계산해서 보여 줘요.
formula: (api: GridApi<Row>, value?: string) => {
formula = value ?? 'basic';
say(summarize(api));
},
// 코드로 고르기: 서울~울산 지역의 2월~4월 칸 묶음
pickBlock: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
// 행 번호를 누른 것과 같아요: 3번째 행(대구)의 모든 칸.
pickRow: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
// 3월 열 전체
pickColumn: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
clear: (api: GridApi<Row>) => api.clearCellSelection(),
};버튼을 누르면 이 예제의 코드가 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.formula(api, $any($event.target).value)"
>
<option value="basic" selected>합계·평균 (기본)</option>
<option value="full">합계·평균·최소·최대</option>
<option value="custom">내 수식: 5,000만 원 넘는 칸</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pickBlock(api)"
>블록 고르기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pickRow(api)"
>대구 행 통째로</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pickColumn(api)"
>3월 열 통째로</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>선택 지우기</button>
</div>
<mx-grid style="height: 340px" [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';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
m1: number;
m2: number;
m3: number;
m4: number;
m5: number;
m6: number;
note: string;
}
const regions = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'] as const;
// 지역별 월 매출(만 원). 칸을 고르면 그 칸들의 합계·평균·개수를 계산해서 알려 줘요.
// 숫자가 아닌 칸('비고')은 개수에는 들어가지만 합계에는 더하지 않아요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: '지역', width: 100 },
...MONTHS.map((id, i) => ({
id,
title: `${i + 1}월`,
kind: 'number' as const,
width: 96,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR'),
})),
{ id: 'note', title: '비고', width: 140 },
],
rows: regions.map((region, i) => ({
id: i + 1,
region,
m1: 3700 + ((i * 910) % 6000),
m2: 1700 + ((i * 1230) % 8000),
m3: 1100 + ((i * 570) % 5000),
m4: 2900 + ((i * 2130) % 9000),
m5: 2400 + ((i * 780) % 6500),
m6: 3100 + ((i * 1470) % 7000),
note: i % 3 === 0 ? '목표 초과' : '',
})),
rowKey: 'id',
// 왼쪽 행 번호를 누르면 그 행 전체가 선택돼요(Shift는 행 범위, Ctrl은 더하기).
showRowNumbers: true,
cellSelection: 'multiple',
};
const won = (n: number | null): string =>
n === null ? '-' : `${Math.round(n).toLocaleString('ko-KR')}만원`;
let formula = 'basic';
let say: (message: LogText) => void = () => {};
// 고른 칸을 읽어 한 줄 요약을 만들어요. getCellStats()가 기본 계산을 해 주고,
// 나만의 수식은 getSelectedCells()로 칸을 하나씩 읽어서 직접 계산해요.
function summarize(api: GridApi<Row>): string {
const cells = api.getSelectedCells();
if (cells.length === 0)
return L(
'고른 칸이 없어요. 칸을 끌거나 왼쪽 행 번호를 눌러 보세요',
'No cells selected. Drag across cells or click a row number on the left',
);
const s = api.getCellStats();
const base = L(
`${s.count}칸 선택 (숫자 ${s.numberCount}칸)`,
`${s.count} cells selected (${s.numberCount} numeric)`,
);
if (formula === 'full') {
return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)} · ${L('최소', 'Min')} ${won(s.min)} · ${L('최대', 'Max')} ${won(s.max)}`;
}
if (formula === 'custom') {
// 내 수식: 선택한 칸 중에서 5,000만 원을 넘긴 칸이 몇 개이고, 전체 숫자 칸의 몇 %인지.
const over = cells.filter((c) => {
const v = (api.getRowByKey(c.rowKey) as Row | undefined)?.[c.columnId as keyof Row];
return typeof v === 'number' && v > 5000;
}).length;
const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
return `${base} · ${L(`5,000만 원 넘는 칸 ${over}개`, `${over} cells over 50 million KRW`)} (${pct}%)`;
}
return `${base} · ${L('합계', 'Sum')} ${won(s.sum)} · ${L('평균', 'Average')} ${won(s.average)}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 끌어 보세요. 고른 칸의 개수·합계·평균이 여기에 나와요.',
en: 'Drag across cells. The count, sum and average of the selection appear here.',
});
const off = api.on('cellSelectionChanged', () => log(summarize(api)));
return () => off();
}
export const actions = {
// 계산 방식을 바꾸면 지금 고른 칸으로 다시 계산해서 보여 줘요.
formula: (api: GridApi<Row>, value?: string) => {
formula = value ?? 'basic';
say(summarize(api));
},
// 코드로 고르기: 서울~울산 지역의 2월~4월 칸 묶음
pickBlock: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
// 행 번호를 누른 것과 같아요: 3번째 행(대구)의 모든 칸.
pickRow: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
// 3월 열 전체
pickColumn: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
clear: (api: GridApi<Row>) => api.clearCellSelection(),
};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="Formula" id="formula">
<option value="basic" selected>Sum and average</option>
<option value="full">Sum, average, min, max</option>
<option value="custom">Custom: cells over 5,000</option>
</select>
<button type="button" id="pickBlock">Pick a block</button>
<button type="button" id="pickRow">Whole Daegu row</button>
<button type="button" id="pickColumn">Whole March column</button>
<button type="button" id="clear">Clear selection</button>
</div>
<div id="grid" style="height: 340px"></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('formula').addEventListener('change', (event) => actions.formula(api, event.target.value));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickRow').addEventListener('click', () => actions.pickRow(api));
document.getElementById('pickColumn').addEventListener('click', () => actions.pickColumn(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const regions = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'];
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
// Monthly sales per region (in $). Select cells and the sum, average and count of those cells are reported.
// Non-numeric cells ('Note') count toward the cell count but are not added to the sum.
export const options = {
columns: [
{ id: 'region', title: 'Region', width: 100 },
...MONTHS.map((id, i) => ({
id,
title: MONTH_NAMES[i],
kind: 'number',
width: 96,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
})),
{ id: 'note', title: 'Note', width: 140 },
],
rows: regions.map((region, i) => ({
id: i + 1,
region,
m1: 3700 + ((i * 910) % 6000),
m2: 1700 + ((i * 1230) % 8000),
m3: 1100 + ((i * 570) % 5000),
m4: 2900 + ((i * 2130) % 9000),
m5: 2400 + ((i * 780) % 6500),
m6: 3100 + ((i * 1470) % 7000),
note: i % 3 === 0 ? 'Target exceeded' : '',
})),
rowKey: 'id',
// Clicking a row number on the left selects that whole row (Shift for a row range, Ctrl to add).
showRowNumbers: true,
cellSelection: 'multiple',
};
const usd = (n) => n === null ? '-' : `$${Math.round(n).toLocaleString('en-US')}`;
let formula = 'basic';
let say = () => { };
// Reads the selected cells and builds a one-line summary. getCellStats() does the basic math,
// and a custom formula reads cells one by one with getSelectedCells().
function summarize(api) {
const cells = api.getSelectedCells();
if (cells.length === 0)
return 'No cells selected. Drag across cells or click a row number on the left';
const s = api.getCellStats();
const base = `${s.count} cells selected (${s.numberCount} numeric)`;
if (formula === 'full') {
return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)} · Min ${usd(s.min)} · Max ${usd(s.max)}`;
}
if (formula === 'custom') {
// Custom formula: how many selected cells exceed $5,000, and what % of all numeric cells that is.
const over = cells.filter((c) => {
const v = api.getRowByKey(c.rowKey)?.[c.columnId];
return typeof v === 'number' && v > 5000;
}).length;
const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
return `${base} · ${over} cells over $5,000 (${pct}%)`;
}
return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)}`;
}
export function setup(api, log) {
say = log;
log('Drag across cells. The count, sum and average of the selection appear here.');
const off = api.on('cellSelectionChanged', () => log(summarize(api)));
return () => off();
}
export const actions = {
// Changing the formula recalculates with the cells selected right now.
formula: (api, value) => {
formula = value ?? 'basic';
say(summarize(api));
},
// Select in code: Feb to Apr cells for the first four regions (Seoul to Incheon)
pickBlock: (api) => api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
// Same as clicking a row number: every cell of row 3 (Daegu).
pickRow: (api) => api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
// The whole March column
pickColumn: (api) => api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
clear: (api) => api.clearCellSelection(),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Instant sum and average of the cells you pick</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Formula" id="formula">
<option value="basic" selected>Sum and average</option>
<option value="full">Sum, average, min, max</option>
<option value="custom">Custom: cells over 5,000</option>
</select>
<button type="button" id="pickBlock">Pick a block</button>
<button type="button" id="pickRow">Whole Daegu row</button>
<button type="button" id="pickColumn">Whole March column</button>
<button type="button" id="clear">Clear selection</button>
</div>
<div id="grid" style="height: 340px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const regions = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'];
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
// Monthly sales per region (in $). Select cells and the sum, average and count of those cells are reported.
// Non-numeric cells ('Note') count toward the cell count but are not added to the sum.
const options = {
columns: [
{ id: 'region', title: 'Region', width: 100 },
...MONTHS.map((id, i) => ({
id,
title: MONTH_NAMES[i],
kind: 'number',
width: 96,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
})),
{ id: 'note', title: 'Note', width: 140 },
],
rows: regions.map((region, i) => ({
id: i + 1,
region,
m1: 3700 + ((i * 910) % 6000),
m2: 1700 + ((i * 1230) % 8000),
m3: 1100 + ((i * 570) % 5000),
m4: 2900 + ((i * 2130) % 9000),
m5: 2400 + ((i * 780) % 6500),
m6: 3100 + ((i * 1470) % 7000),
note: i % 3 === 0 ? 'Target exceeded' : '',
})),
rowKey: 'id',
// Clicking a row number on the left selects that whole row (Shift for a row range, Ctrl to add).
showRowNumbers: true,
cellSelection: 'multiple',
};
const usd = (n) => n === null ? '-' : `$${Math.round(n).toLocaleString('en-US')}`;
let formula = 'basic';
let say = () => { };
// Reads the selected cells and builds a one-line summary. getCellStats() does the basic math,
// and a custom formula reads cells one by one with getSelectedCells().
function summarize(api) {
const cells = api.getSelectedCells();
if (cells.length === 0)
return 'No cells selected. Drag across cells or click a row number on the left';
const s = api.getCellStats();
const base = `${s.count} cells selected (${s.numberCount} numeric)`;
if (formula === 'full') {
return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)} · Min ${usd(s.min)} · Max ${usd(s.max)}`;
}
if (formula === 'custom') {
// Custom formula: how many selected cells exceed $5,000, and what % of all numeric cells that is.
const over = cells.filter((c) => {
const v = api.getRowByKey(c.rowKey)?.[c.columnId];
return typeof v === 'number' && v > 5000;
}).length;
const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
return `${base} · ${over} cells over $5,000 (${pct}%)`;
}
return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)}`;
}
function setup(api, log) {
say = log;
log('Drag across cells. The count, sum and average of the selection appear here.');
const off = api.on('cellSelectionChanged', () => log(summarize(api)));
return () => off();
}
const actions = {
// Changing the formula recalculates with the cells selected right now.
formula: (api, value) => {
formula = value ?? 'basic';
say(summarize(api));
},
// Select in code: Feb to Apr cells for the first four regions (Seoul to Incheon)
pickBlock: (api) => api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
// Same as clicking a row number: every cell of row 3 (Daegu).
pickRow: (api) => api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
// The whole March column
pickColumn: (api) => api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
clear: (api) => api.clearCellSelection(),
};
options.ariaLabel = "Instant sum and average of the cells you pick";
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('formula').addEventListener('change', (event) => actions.formula(api, event.target.value));
document.getElementById('pickBlock').addEventListener('click', () => actions.pickBlock(api));
document.getElementById('pickRow').addEventListener('click', () => actions.pickRow(api));
document.getElementById('pickColumn').addEventListener('click', () => actions.pickColumn(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="Formula"
disabled={!api}
onChange={(event) => api && actions.formula(api, event.target.value)}
>
<option value="basic">Sum and average</option>
<option value="full">Sum, average, min, max</option>
<option value="custom">Custom: cells over 5,000</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pickBlock(api)}
>Pick a block</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pickRow(api)}
>Whole Daegu row</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pickColumn(api)}
>Whole March column</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear selection</button>
</div>
<Grid style={{ height: 340 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
m1: number;
m2: number;
m3: number;
m4: number;
m5: number;
m6: number;
note: string;
}
const regions = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'] as const;
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
// Monthly sales per region (in $). Select cells and the sum, average and count of those cells are reported.
// Non-numeric cells ('Note') count toward the cell count but are not added to the sum.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: 'Region', width: 100 },
...MONTHS.map((id, i) => ({
id,
title: MONTH_NAMES[i] as string,
kind: 'number' as const,
width: 96,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('en-US'),
})),
{ id: 'note', title: 'Note', width: 140 },
],
rows: regions.map((region, i) => ({
id: i + 1,
region,
m1: 3700 + ((i * 910) % 6000),
m2: 1700 + ((i * 1230) % 8000),
m3: 1100 + ((i * 570) % 5000),
m4: 2900 + ((i * 2130) % 9000),
m5: 2400 + ((i * 780) % 6500),
m6: 3100 + ((i * 1470) % 7000),
note: i % 3 === 0 ? 'Target exceeded' : '',
})),
rowKey: 'id',
// Clicking a row number on the left selects that whole row (Shift for a row range, Ctrl to add).
showRowNumbers: true,
cellSelection: 'multiple',
};
const usd = (n: number | null): string =>
n === null ? '-' : `$${Math.round(n).toLocaleString('en-US')}`;
let formula = 'basic';
let say: (message: LogText) => void = () => {};
// Reads the selected cells and builds a one-line summary. getCellStats() does the basic math,
// and a custom formula reads cells one by one with getSelectedCells().
function summarize(api: GridApi<Row>): string {
const cells = api.getSelectedCells();
if (cells.length === 0)
return 'No cells selected. Drag across cells or click a row number on the left';
const s = api.getCellStats();
const base = `${s.count} cells selected (${s.numberCount} numeric)`;
if (formula === 'full') {
return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)} · Min ${usd(s.min)} · Max ${usd(s.max)}`;
}
if (formula === 'custom') {
// Custom formula: how many selected cells exceed $5,000, and what % of all numeric cells that is.
const over = cells.filter((c) => {
const v = (api.getRowByKey(c.rowKey) as Row | undefined)?.[c.columnId as keyof Row];
return typeof v === 'number' && v > 5000;
}).length;
const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
return `${base} · ${over} cells over $5,000 (${pct}%)`;
}
return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Drag across cells. The count, sum and average of the selection appear here.');
const off = api.on('cellSelectionChanged', () => log(summarize(api)));
return () => off();
}
export const actions = {
// Changing the formula recalculates with the cells selected right now.
formula: (api: GridApi<Row>, value?: string) => {
formula = value ?? 'basic';
say(summarize(api));
},
// Select in code: Feb to Apr cells for the first four regions (Seoul to Incheon)
pickBlock: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
// Same as clicking a row number: every cell of row 3 (Daegu).
pickRow: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
// The whole March column
pickColumn: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
clear: (api: GridApi<Row>) => api.clearCellSelection(),
};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="Formula"
:disabled="!api"
@change="api && actions.formula(api, ($event.target as HTMLSelectElement).value)"
>
<option value="basic" selected>Sum and average</option>
<option value="full">Sum, average, min, max</option>
<option value="custom">Custom: cells over 5,000</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.pickBlock(api)"
>Pick a block</button>
<button type="button" :disabled="!api" @click="api && actions.pickRow(api)">Whole Daegu row</button>
<button
type="button"
:disabled="!api"
@click="api && actions.pickColumn(api)"
>Whole March column</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear selection</button>
</div>
<Grid style="height: 340px" :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;
region: string;
m1: number;
m2: number;
m3: number;
m4: number;
m5: number;
m6: number;
note: string;
}
const regions = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'] as const;
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
// Monthly sales per region (in $). Select cells and the sum, average and count of those cells are reported.
// Non-numeric cells ('Note') count toward the cell count but are not added to the sum.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: 'Region', width: 100 },
...MONTHS.map((id, i) => ({
id,
title: MONTH_NAMES[i] as string,
kind: 'number' as const,
width: 96,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('en-US'),
})),
{ id: 'note', title: 'Note', width: 140 },
],
rows: regions.map((region, i) => ({
id: i + 1,
region,
m1: 3700 + ((i * 910) % 6000),
m2: 1700 + ((i * 1230) % 8000),
m3: 1100 + ((i * 570) % 5000),
m4: 2900 + ((i * 2130) % 9000),
m5: 2400 + ((i * 780) % 6500),
m6: 3100 + ((i * 1470) % 7000),
note: i % 3 === 0 ? 'Target exceeded' : '',
})),
rowKey: 'id',
// Clicking a row number on the left selects that whole row (Shift for a row range, Ctrl to add).
showRowNumbers: true,
cellSelection: 'multiple',
};
const usd = (n: number | null): string =>
n === null ? '-' : `$${Math.round(n).toLocaleString('en-US')}`;
let formula = 'basic';
let say: (message: LogText) => void = () => {};
// Reads the selected cells and builds a one-line summary. getCellStats() does the basic math,
// and a custom formula reads cells one by one with getSelectedCells().
function summarize(api: GridApi<Row>): string {
const cells = api.getSelectedCells();
if (cells.length === 0)
return 'No cells selected. Drag across cells or click a row number on the left';
const s = api.getCellStats();
const base = `${s.count} cells selected (${s.numberCount} numeric)`;
if (formula === 'full') {
return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)} · Min ${usd(s.min)} · Max ${usd(s.max)}`;
}
if (formula === 'custom') {
// Custom formula: how many selected cells exceed $5,000, and what % of all numeric cells that is.
const over = cells.filter((c) => {
const v = (api.getRowByKey(c.rowKey) as Row | undefined)?.[c.columnId as keyof Row];
return typeof v === 'number' && v > 5000;
}).length;
const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
return `${base} · ${over} cells over $5,000 (${pct}%)`;
}
return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Drag across cells. The count, sum and average of the selection appear here.');
const off = api.on('cellSelectionChanged', () => log(summarize(api)));
return () => off();
}
export const actions = {
// Changing the formula recalculates with the cells selected right now.
formula: (api: GridApi<Row>, value?: string) => {
formula = value ?? 'basic';
say(summarize(api));
},
// Select in code: Feb to Apr cells for the first four regions (Seoul to Incheon)
pickBlock: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
// Same as clicking a row number: every cell of row 3 (Daegu).
pickRow: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
// The whole March column
pickColumn: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
clear: (api: GridApi<Row>) => api.clearCellSelection(),
};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="Formula"
[disabled]="!api"
(change)="api && actions.formula(api, $any($event.target).value)"
>
<option value="basic" selected>Sum and average</option>
<option value="full">Sum, average, min, max</option>
<option value="custom">Custom: cells over 5,000</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pickBlock(api)"
>Pick a block</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pickRow(api)"
>Whole Daegu row</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pickColumn(api)"
>Whole March column</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear selection</button>
</div>
<mx-grid style="height: 340px" [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;
region: string;
m1: number;
m2: number;
m3: number;
m4: number;
m5: number;
m6: number;
note: string;
}
const regions = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const MONTHS = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6'] as const;
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
// Monthly sales per region (in $). Select cells and the sum, average and count of those cells are reported.
// Non-numeric cells ('Note') count toward the cell count but are not added to the sum.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: 'Region', width: 100 },
...MONTHS.map((id, i) => ({
id,
title: MONTH_NAMES[i] as string,
kind: 'number' as const,
width: 96,
align: 'end' as const,
formatValue: (value: unknown) => Number(value).toLocaleString('en-US'),
})),
{ id: 'note', title: 'Note', width: 140 },
],
rows: regions.map((region, i) => ({
id: i + 1,
region,
m1: 3700 + ((i * 910) % 6000),
m2: 1700 + ((i * 1230) % 8000),
m3: 1100 + ((i * 570) % 5000),
m4: 2900 + ((i * 2130) % 9000),
m5: 2400 + ((i * 780) % 6500),
m6: 3100 + ((i * 1470) % 7000),
note: i % 3 === 0 ? 'Target exceeded' : '',
})),
rowKey: 'id',
// Clicking a row number on the left selects that whole row (Shift for a row range, Ctrl to add).
showRowNumbers: true,
cellSelection: 'multiple',
};
const usd = (n: number | null): string =>
n === null ? '-' : `$${Math.round(n).toLocaleString('en-US')}`;
let formula = 'basic';
let say: (message: LogText) => void = () => {};
// Reads the selected cells and builds a one-line summary. getCellStats() does the basic math,
// and a custom formula reads cells one by one with getSelectedCells().
function summarize(api: GridApi<Row>): string {
const cells = api.getSelectedCells();
if (cells.length === 0)
return 'No cells selected. Drag across cells or click a row number on the left';
const s = api.getCellStats();
const base = `${s.count} cells selected (${s.numberCount} numeric)`;
if (formula === 'full') {
return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)} · Min ${usd(s.min)} · Max ${usd(s.max)}`;
}
if (formula === 'custom') {
// Custom formula: how many selected cells exceed $5,000, and what % of all numeric cells that is.
const over = cells.filter((c) => {
const v = (api.getRowByKey(c.rowKey) as Row | undefined)?.[c.columnId as keyof Row];
return typeof v === 'number' && v > 5000;
}).length;
const pct = s.numberCount === 0 ? 0 : Math.round((over / s.numberCount) * 100);
return `${base} · ${over} cells over $5,000 (${pct}%)`;
}
return `${base} · Sum ${usd(s.sum)} · Average ${usd(s.average)}`;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Drag across cells. The count, sum and average of the selection appear here.');
const off = api.on('cellSelectionChanged', () => log(summarize(api)));
return () => off();
}
export const actions = {
// Changing the formula recalculates with the cells selected right now.
formula: (api: GridApi<Row>, value?: string) => {
formula = value ?? 'basic';
say(summarize(api));
},
// Select in code: Feb to Apr cells for the first four regions (Seoul to Incheon)
pickBlock: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm2' }, { rowKey: 4, columnId: 'm4' }),
// Same as clicking a row number: every cell of row 3 (Daegu).
pickRow: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 3, columnId: 'region' }, { rowKey: 3, columnId: 'note' }),
// The whole March column
pickColumn: (api: GridApi<Row>) =>
api.selectCells({ rowKey: 1, columnId: 'm3' }, { rowKey: 8, columnId: 'm3' }),
clear: (api: GridApi<Row>) => api.clearCellSelection(),
};