Chart.js 어댑터로 차트 만들기Build a chart with a Chart.js adapter
예제 안의 어댑터가 CDN에서 Chart.js 4를 불러와 chartAdapter로 이어 줘요. 불러오는 동안 온 갱신은 모아 두었다가 로드가 끝나면 그려요.The adapter in this example loads Chart.js 4 from a CDN and connects it as chartAdapter. Updates that arrive while loading are queued and drawn once the script is ready.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="fromSelection">선택으로 막대 차트</button>
<button type="button" id="allRows">전체 행</button>
<button type="button" id="lineChart">꺾은선</button>
<button type="button" id="clear">지우기</button>
</div>
<div id="grid" style="height: 320px"></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('fromSelection').addEventListener('click', () => actions.fromSelection(api));
document.getElementById('allRows').addEventListener('click', () => actions.allRows(api));
document.getElementById('lineChart').addEventListener('click', () => actions.lineChart(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const rows = [
{ id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
{ id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
{ id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
{ id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
{ id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
{ id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
{ id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
{ id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns = [
{ id: 'region', title: '지역', width: 110 },
{ id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: '메모', editable: true, width: 110 },
];
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart() {
return window.Chart;
}
function loadChartJs(onReady) {
if (globalChart() !== undefined) {
onReady();
return;
}
let script = document.querySelector('script[data-chartjs]');
if (script === null) {
script = document.createElement('script');
script.src = CDN;
script.dataset.chartjs = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter = {
create(ctx) {
const canvas = document.createElement('canvas');
ctx.container.append(canvas);
const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
const toData = (d) => ({
labels: d.categories,
datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
});
let latest = ctx.getData();
let instance = null;
let dead = false;
loadChartJs(() => {
const Ctor = globalChart();
if (dead || Ctor === undefined)
return;
instance = new Ctor(canvas, {
type: kind,
data: toData(latest),
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: ctx.type === 'bar' ? 'y' : 'x',
},
});
});
return {
update(data) {
latest = data;
if (instance === null)
return;
const next = toData(data);
instance.data.labels = next.labels;
instance.data.datasets = next.datasets;
instance.update();
},
destroy() {
dead = true;
instance?.destroy();
canvas.remove();
},
resize() {
instance?.resize();
},
};
},
};
export const options = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: '지역별 분기 매출',
chartAdapter: chartjsAdapter,
};
let host = null;
let chart = null;
function ensureHost() {
if (host !== null)
return host;
const first = document.getElementById('grid');
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null)
first.after(host);
else
document.body.append(host);
return host;
}
function cleanup() {
chart?.destroy();
chart = null;
}
export function setup(api, log) {
const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
log({
ko: `차트를 만들었어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
en: `Chart created: ${type}, ${categories} categories, ${series} series`,
});
});
const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
log({
ko: `차트를 갱신했어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
en: `Chart updated: ${type}, ${categories} categories, ${series} series`,
});
});
log({
ko: '지역과 1~3분기 칸을 끌어서 고른 뒤 버튼을 눌러요.',
en: 'Drag-select the region and Q1..Q3 cells, then press a button.',
});
return () => {
offCreated();
offUpdated();
cleanup();
host?.remove();
host = null;
};
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api, type) {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type });
}
export const actions = {
fromSelection: (api) => {
cleanup();
chart = fromSelection(api, 'column');
},
allRows: (api) => {
cleanup();
chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
},
lineChart: (api) => {
cleanup();
chart = fromSelection(api, 'line');
},
clear: () => {
cleanup();
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Chart.js 어댑터로 차트 만들기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="fromSelection">선택으로 막대 차트</button>
<button type="button" id="allRows">전체 행</button>
<button type="button" id="lineChart">꺾은선</button>
<button type="button" id="clear">지우기</button>
</div>
<div id="grid" style="height: 320px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
{ id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
{ id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
{ id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
{ id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
{ id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
{ id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
{ id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns = [
{ id: 'region', title: '지역', width: 110 },
{ id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: '메모', editable: true, width: 110 },
];
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart() {
return window.Chart;
}
function loadChartJs(onReady) {
if (globalChart() !== undefined) {
onReady();
return;
}
let script = document.querySelector('script[data-chartjs]');
if (script === null) {
script = document.createElement('script');
script.src = CDN;
script.dataset.chartjs = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter = {
create(ctx) {
const canvas = document.createElement('canvas');
ctx.container.append(canvas);
const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
const toData = (d) => ({
labels: d.categories,
datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
});
let latest = ctx.getData();
let instance = null;
let dead = false;
loadChartJs(() => {
const Ctor = globalChart();
if (dead || Ctor === undefined)
return;
instance = new Ctor(canvas, {
type: kind,
data: toData(latest),
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: ctx.type === 'bar' ? 'y' : 'x',
},
});
});
return {
update(data) {
latest = data;
if (instance === null)
return;
const next = toData(data);
instance.data.labels = next.labels;
instance.data.datasets = next.datasets;
instance.update();
},
destroy() {
dead = true;
instance?.destroy();
canvas.remove();
},
resize() {
instance?.resize();
},
};
},
};
const options = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: '지역별 분기 매출',
chartAdapter: chartjsAdapter,
};
let host = null;
let chart = null;
function ensureHost() {
if (host !== null)
return host;
const first = document.getElementById('grid');
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null)
first.after(host);
else
document.body.append(host);
return host;
}
function cleanup() {
chart?.destroy();
chart = null;
}
function setup(api, log) {
const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
log({
ko: `차트를 만들었어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
en: `Chart created: ${type}, ${categories} categories, ${series} series`,
});
});
const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
log({
ko: `차트를 갱신했어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
en: `Chart updated: ${type}, ${categories} categories, ${series} series`,
});
});
log({
ko: '지역과 1~3분기 칸을 끌어서 고른 뒤 버튼을 눌러요.',
en: 'Drag-select the region and Q1..Q3 cells, then press a button.',
});
return () => {
offCreated();
offUpdated();
cleanup();
host?.remove();
host = null;
};
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api, type) {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type });
}
const actions = {
fromSelection: (api) => {
cleanup();
chart = fromSelection(api, 'column');
},
allRows: (api) => {
cleanup();
chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
},
lineChart: (api) => {
cleanup();
chart = fromSelection(api, 'line');
},
clear: () => {
cleanup();
},
};
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('fromSelection').addEventListener('click', () => actions.fromSelection(api));
document.getElementById('allRows').addEventListener('click', () => actions.allRows(api));
document.getElementById('lineChart').addEventListener('click', () => actions.lineChart(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.fromSelection(api)}
>선택으로 막대 차트</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.allRows(api)}
>전체 행</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.lineChart(api)}
>꺾은선</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>지우기</button>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import type {
ChartAdapter,
ChartType,
ChartData,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
{ id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
{ id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
{ id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
{ id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
{ id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
{ id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
{ id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: '지역', width: 110 },
{ id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: '메모', editable: true, width: 110 },
];
type ChartJsInstance = {
data: { labels: string[]; datasets: unknown[] };
update(): void;
destroy(): void;
resize(): void;
};
type ChartJsCtor = new (el: HTMLCanvasElement, config: unknown) => ChartJsInstance;
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart(): ChartJsCtor | undefined {
return (window as unknown as { Chart?: ChartJsCtor }).Chart;
}
function loadChartJs(onReady: () => void): void {
if (globalChart() !== undefined) {
onReady();
return;
}
let script = document.querySelector<HTMLScriptElement>('script[data-chartjs]');
if (script === null) {
script = document.createElement('script');
script.src = CDN;
script.dataset.chartjs = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter: ChartAdapter = {
create(ctx) {
const canvas = document.createElement('canvas');
ctx.container.append(canvas);
const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
const toData = (d: ChartData) => ({
labels: d.categories,
datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
});
let latest = ctx.getData();
let instance: ChartJsInstance | null = null;
let dead = false;
loadChartJs(() => {
const Ctor = globalChart();
if (dead || Ctor === undefined) return;
instance = new Ctor(canvas, {
type: kind,
data: toData(latest),
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: ctx.type === 'bar' ? 'y' : 'x',
},
});
});
return {
update(data) {
latest = data;
if (instance === null) return;
const next = toData(data);
instance.data.labels = next.labels;
instance.data.datasets = next.datasets;
instance.update();
},
destroy() {
dead = true;
instance?.destroy();
canvas.remove();
},
resize() {
instance?.resize();
},
};
},
};
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: '지역별 분기 매출',
chartAdapter: chartjsAdapter,
};
let host: HTMLElement | null = null;
let chart: GridChart | null = null;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(host);
else document.body.append(host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
log({
ko: `차트를 만들었어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
en: `Chart created: ${type}, ${categories} categories, ${series} series`,
});
});
const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
log({
ko: `차트를 갱신했어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
en: `Chart updated: ${type}, ${categories} categories, ${series} series`,
});
});
log({
ko: '지역과 1~3분기 칸을 끌어서 고른 뒤 버튼을 눌러요.',
en: 'Drag-select the region and Q1..Q3 cells, then press a button.',
});
return () => {
offCreated();
offUpdated();
cleanup();
host?.remove();
host = null;
};
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type });
}
export const actions = {
fromSelection: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'column');
},
allRows: (api: GridApi<Row>) => {
cleanup();
chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
},
lineChart: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'line');
},
clear: () => {
cleanup();
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.fromSelection(api)"
>선택으로 막대 차트</button>
<button type="button" :disabled="!api" @click="api && actions.allRows(api)">전체 행</button>
<button
type="button"
:disabled="!api"
@click="api && actions.lineChart(api)"
>꺾은선</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">지우기</button>
</div>
<Grid style="height: 320px" :options="options" @ready="onReady" />
</template>import type {
ChartAdapter,
ChartType,
ChartData,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
{ id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
{ id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
{ id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
{ id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
{ id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
{ id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
{ id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: '지역', width: 110 },
{ id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: '메모', editable: true, width: 110 },
];
type ChartJsInstance = {
data: { labels: string[]; datasets: unknown[] };
update(): void;
destroy(): void;
resize(): void;
};
type ChartJsCtor = new (el: HTMLCanvasElement, config: unknown) => ChartJsInstance;
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart(): ChartJsCtor | undefined {
return (window as unknown as { Chart?: ChartJsCtor }).Chart;
}
function loadChartJs(onReady: () => void): void {
if (globalChart() !== undefined) {
onReady();
return;
}
let script = document.querySelector<HTMLScriptElement>('script[data-chartjs]');
if (script === null) {
script = document.createElement('script');
script.src = CDN;
script.dataset.chartjs = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter: ChartAdapter = {
create(ctx) {
const canvas = document.createElement('canvas');
ctx.container.append(canvas);
const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
const toData = (d: ChartData) => ({
labels: d.categories,
datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
});
let latest = ctx.getData();
let instance: ChartJsInstance | null = null;
let dead = false;
loadChartJs(() => {
const Ctor = globalChart();
if (dead || Ctor === undefined) return;
instance = new Ctor(canvas, {
type: kind,
data: toData(latest),
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: ctx.type === 'bar' ? 'y' : 'x',
},
});
});
return {
update(data) {
latest = data;
if (instance === null) return;
const next = toData(data);
instance.data.labels = next.labels;
instance.data.datasets = next.datasets;
instance.update();
},
destroy() {
dead = true;
instance?.destroy();
canvas.remove();
},
resize() {
instance?.resize();
},
};
},
};
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: '지역별 분기 매출',
chartAdapter: chartjsAdapter,
};
let host: HTMLElement | null = null;
let chart: GridChart | null = null;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(host);
else document.body.append(host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
log({
ko: `차트를 만들었어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
en: `Chart created: ${type}, ${categories} categories, ${series} series`,
});
});
const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
log({
ko: `차트를 갱신했어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
en: `Chart updated: ${type}, ${categories} categories, ${series} series`,
});
});
log({
ko: '지역과 1~3분기 칸을 끌어서 고른 뒤 버튼을 눌러요.',
en: 'Drag-select the region and Q1..Q3 cells, then press a button.',
});
return () => {
offCreated();
offUpdated();
cleanup();
host?.remove();
host = null;
};
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type });
}
export const actions = {
fromSelection: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'column');
},
allRows: (api: GridApi<Row>) => {
cleanup();
chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
},
lineChart: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'line');
},
clear: () => {
cleanup();
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.fromSelection(api)"
>선택으로 막대 차트</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.allRows(api)"
>전체 행</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.lineChart(api)"
>꺾은선</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>지우기</button>
</div>
<mx-grid style="height: 320px" [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 {
ChartAdapter,
ChartType,
ChartData,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
{ id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
{ id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
{ id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
{ id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
{ id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
{ id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
{ id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: '지역', width: 110 },
{ id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: '메모', editable: true, width: 110 },
];
type ChartJsInstance = {
data: { labels: string[]; datasets: unknown[] };
update(): void;
destroy(): void;
resize(): void;
};
type ChartJsCtor = new (el: HTMLCanvasElement, config: unknown) => ChartJsInstance;
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart(): ChartJsCtor | undefined {
return (window as unknown as { Chart?: ChartJsCtor }).Chart;
}
function loadChartJs(onReady: () => void): void {
if (globalChart() !== undefined) {
onReady();
return;
}
let script = document.querySelector<HTMLScriptElement>('script[data-chartjs]');
if (script === null) {
script = document.createElement('script');
script.src = CDN;
script.dataset.chartjs = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter: ChartAdapter = {
create(ctx) {
const canvas = document.createElement('canvas');
ctx.container.append(canvas);
const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
const toData = (d: ChartData) => ({
labels: d.categories,
datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
});
let latest = ctx.getData();
let instance: ChartJsInstance | null = null;
let dead = false;
loadChartJs(() => {
const Ctor = globalChart();
if (dead || Ctor === undefined) return;
instance = new Ctor(canvas, {
type: kind,
data: toData(latest),
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: ctx.type === 'bar' ? 'y' : 'x',
},
});
});
return {
update(data) {
latest = data;
if (instance === null) return;
const next = toData(data);
instance.data.labels = next.labels;
instance.data.datasets = next.datasets;
instance.update();
},
destroy() {
dead = true;
instance?.destroy();
canvas.remove();
},
resize() {
instance?.resize();
},
};
},
};
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: '지역별 분기 매출',
chartAdapter: chartjsAdapter,
};
let host: HTMLElement | null = null;
let chart: GridChart | null = null;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(host);
else document.body.append(host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
log({
ko: `차트를 만들었어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
en: `Chart created: ${type}, ${categories} categories, ${series} series`,
});
});
const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
log({
ko: `차트를 갱신했어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
en: `Chart updated: ${type}, ${categories} categories, ${series} series`,
});
});
log({
ko: '지역과 1~3분기 칸을 끌어서 고른 뒤 버튼을 눌러요.',
en: 'Drag-select the region and Q1..Q3 cells, then press a button.',
});
return () => {
offCreated();
offUpdated();
cleanup();
host?.remove();
host = null;
};
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type });
}
export const actions = {
fromSelection: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'column');
},
allRows: (api: GridApi<Row>) => {
cleanup();
chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
},
lineChart: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'line');
},
clear: () => {
cleanup();
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="fromSelection">Column chart from selection</button>
<button type="button" id="allRows">All rows</button>
<button type="button" id="lineChart">Line</button>
<button type="button" id="clear">Clear</button>
</div>
<div id="grid" style="height: 320px"></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('fromSelection').addEventListener('click', () => actions.fromSelection(api));
document.getElementById('allRows').addEventListener('click', () => actions.allRows(api));
document.getElementById('lineChart').addEventListener('click', () => actions.lineChart(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const rows = [
{ id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
{ id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
{ id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
{ id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
{ id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
{ id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
{ id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
{ id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns = [
{ id: 'region', title: 'Region', width: 110 },
{ id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: 'Note', editable: true, width: 110 },
];
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart() {
return window.Chart;
}
function loadChartJs(onReady) {
if (globalChart() !== undefined) {
onReady();
return;
}
let script = document.querySelector('script[data-chartjs]');
if (script === null) {
script = document.createElement('script');
script.src = CDN;
script.dataset.chartjs = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter = {
create(ctx) {
const canvas = document.createElement('canvas');
ctx.container.append(canvas);
const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
const toData = (d) => ({
labels: d.categories,
datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
});
let latest = ctx.getData();
let instance = null;
let dead = false;
loadChartJs(() => {
const Ctor = globalChart();
if (dead || Ctor === undefined)
return;
instance = new Ctor(canvas, {
type: kind,
data: toData(latest),
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: ctx.type === 'bar' ? 'y' : 'x',
},
});
});
return {
update(data) {
latest = data;
if (instance === null)
return;
const next = toData(data);
instance.data.labels = next.labels;
instance.data.datasets = next.datasets;
instance.update();
},
destroy() {
dead = true;
instance?.destroy();
canvas.remove();
},
resize() {
instance?.resize();
},
};
},
};
export const options = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: 'Regional sales by quarter',
chartAdapter: chartjsAdapter,
};
let host = null;
let chart = null;
function ensureHost() {
if (host !== null)
return host;
const first = document.getElementById('grid');
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null)
first.after(host);
else
document.body.append(host);
return host;
}
function cleanup() {
chart?.destroy();
chart = null;
}
export function setup(api, log) {
const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
log(`Chart created: ${type}, ${categories} categories, ${series} series`);
});
const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
log(`Chart updated: ${type}, ${categories} categories, ${series} series`);
});
log('Drag-select the region and Q1..Q3 cells, then press a button.');
return () => {
offCreated();
offUpdated();
cleanup();
host?.remove();
host = null;
};
}
// With nothing selected, select the first four rows (region to Q3) so the chart appears right away.
function fromSelection(api, type) {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type });
}
export const actions = {
fromSelection: (api) => {
cleanup();
chart = fromSelection(api, 'column');
},
allRows: (api) => {
cleanup();
chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
},
lineChart: (api) => {
cleanup();
chart = fromSelection(api, 'line');
},
clear: () => {
cleanup();
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Build a chart with a Chart.js adapter</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="fromSelection">Column chart from selection</button>
<button type="button" id="allRows">All rows</button>
<button type="button" id="lineChart">Line</button>
<button type="button" id="clear">Clear</button>
</div>
<div id="grid" style="height: 320px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
{ id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
{ id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
{ id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
{ id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
{ id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
{ id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
{ id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns = [
{ id: 'region', title: 'Region', width: 110 },
{ id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: 'Note', editable: true, width: 110 },
];
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart() {
return window.Chart;
}
function loadChartJs(onReady) {
if (globalChart() !== undefined) {
onReady();
return;
}
let script = document.querySelector('script[data-chartjs]');
if (script === null) {
script = document.createElement('script');
script.src = CDN;
script.dataset.chartjs = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter = {
create(ctx) {
const canvas = document.createElement('canvas');
ctx.container.append(canvas);
const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
const toData = (d) => ({
labels: d.categories,
datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
});
let latest = ctx.getData();
let instance = null;
let dead = false;
loadChartJs(() => {
const Ctor = globalChart();
if (dead || Ctor === undefined)
return;
instance = new Ctor(canvas, {
type: kind,
data: toData(latest),
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: ctx.type === 'bar' ? 'y' : 'x',
},
});
});
return {
update(data) {
latest = data;
if (instance === null)
return;
const next = toData(data);
instance.data.labels = next.labels;
instance.data.datasets = next.datasets;
instance.update();
},
destroy() {
dead = true;
instance?.destroy();
canvas.remove();
},
resize() {
instance?.resize();
},
};
},
};
const options = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: 'Regional sales by quarter',
chartAdapter: chartjsAdapter,
};
let host = null;
let chart = null;
function ensureHost() {
if (host !== null)
return host;
const first = document.getElementById('grid');
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null)
first.after(host);
else
document.body.append(host);
return host;
}
function cleanup() {
chart?.destroy();
chart = null;
}
function setup(api, log) {
const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
log(`Chart created: ${type}, ${categories} categories, ${series} series`);
});
const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
log(`Chart updated: ${type}, ${categories} categories, ${series} series`);
});
log('Drag-select the region and Q1..Q3 cells, then press a button.');
return () => {
offCreated();
offUpdated();
cleanup();
host?.remove();
host = null;
};
}
// With nothing selected, select the first four rows (region to Q3) so the chart appears right away.
function fromSelection(api, type) {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type });
}
const actions = {
fromSelection: (api) => {
cleanup();
chart = fromSelection(api, 'column');
},
allRows: (api) => {
cleanup();
chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
},
lineChart: (api) => {
cleanup();
chart = fromSelection(api, 'line');
},
clear: () => {
cleanup();
},
};
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('fromSelection').addEventListener('click', () => actions.fromSelection(api));
document.getElementById('allRows').addEventListener('click', () => actions.allRows(api));
document.getElementById('lineChart').addEventListener('click', () => actions.lineChart(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.fromSelection(api)}
>Column chart from selection</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.allRows(api)}
>All rows</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.lineChart(api)}
>Line</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear</button>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import type {
ChartAdapter,
ChartType,
ChartData,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
{ id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
{ id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
{ id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
{ id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
{ id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
{ id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
{ id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: 'Region', width: 110 },
{ id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: 'Note', editable: true, width: 110 },
];
type ChartJsInstance = {
data: { labels: string[]; datasets: unknown[] };
update(): void;
destroy(): void;
resize(): void;
};
type ChartJsCtor = new (el: HTMLCanvasElement, config: unknown) => ChartJsInstance;
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart(): ChartJsCtor | undefined {
return (window as unknown as { Chart?: ChartJsCtor }).Chart;
}
function loadChartJs(onReady: () => void): void {
if (globalChart() !== undefined) {
onReady();
return;
}
let script = document.querySelector<HTMLScriptElement>('script[data-chartjs]');
if (script === null) {
script = document.createElement('script');
script.src = CDN;
script.dataset.chartjs = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter: ChartAdapter = {
create(ctx) {
const canvas = document.createElement('canvas');
ctx.container.append(canvas);
const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
const toData = (d: ChartData) => ({
labels: d.categories,
datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
});
let latest = ctx.getData();
let instance: ChartJsInstance | null = null;
let dead = false;
loadChartJs(() => {
const Ctor = globalChart();
if (dead || Ctor === undefined) return;
instance = new Ctor(canvas, {
type: kind,
data: toData(latest),
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: ctx.type === 'bar' ? 'y' : 'x',
},
});
});
return {
update(data) {
latest = data;
if (instance === null) return;
const next = toData(data);
instance.data.labels = next.labels;
instance.data.datasets = next.datasets;
instance.update();
},
destroy() {
dead = true;
instance?.destroy();
canvas.remove();
},
resize() {
instance?.resize();
},
};
},
};
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: 'Regional sales by quarter',
chartAdapter: chartjsAdapter,
};
let host: HTMLElement | null = null;
let chart: GridChart | null = null;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(host);
else document.body.append(host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
log(`Chart created: ${type}, ${categories} categories, ${series} series`);
});
const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
log(`Chart updated: ${type}, ${categories} categories, ${series} series`);
});
log('Drag-select the region and Q1..Q3 cells, then press a button.');
return () => {
offCreated();
offUpdated();
cleanup();
host?.remove();
host = null;
};
}
// With nothing selected, select the first four rows (region to Q3) so the chart appears right away.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type });
}
export const actions = {
fromSelection: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'column');
},
allRows: (api: GridApi<Row>) => {
cleanup();
chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
},
lineChart: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'line');
},
clear: () => {
cleanup();
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.fromSelection(api)"
>Column chart from selection</button>
<button type="button" :disabled="!api" @click="api && actions.allRows(api)">All rows</button>
<button
type="button"
:disabled="!api"
@click="api && actions.lineChart(api)"
>Line</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear</button>
</div>
<Grid style="height: 320px" :options="options" @ready="onReady" />
</template>import type {
ChartAdapter,
ChartType,
ChartData,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
{ id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
{ id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
{ id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
{ id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
{ id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
{ id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
{ id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: 'Region', width: 110 },
{ id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: 'Note', editable: true, width: 110 },
];
type ChartJsInstance = {
data: { labels: string[]; datasets: unknown[] };
update(): void;
destroy(): void;
resize(): void;
};
type ChartJsCtor = new (el: HTMLCanvasElement, config: unknown) => ChartJsInstance;
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart(): ChartJsCtor | undefined {
return (window as unknown as { Chart?: ChartJsCtor }).Chart;
}
function loadChartJs(onReady: () => void): void {
if (globalChart() !== undefined) {
onReady();
return;
}
let script = document.querySelector<HTMLScriptElement>('script[data-chartjs]');
if (script === null) {
script = document.createElement('script');
script.src = CDN;
script.dataset.chartjs = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter: ChartAdapter = {
create(ctx) {
const canvas = document.createElement('canvas');
ctx.container.append(canvas);
const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
const toData = (d: ChartData) => ({
labels: d.categories,
datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
});
let latest = ctx.getData();
let instance: ChartJsInstance | null = null;
let dead = false;
loadChartJs(() => {
const Ctor = globalChart();
if (dead || Ctor === undefined) return;
instance = new Ctor(canvas, {
type: kind,
data: toData(latest),
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: ctx.type === 'bar' ? 'y' : 'x',
},
});
});
return {
update(data) {
latest = data;
if (instance === null) return;
const next = toData(data);
instance.data.labels = next.labels;
instance.data.datasets = next.datasets;
instance.update();
},
destroy() {
dead = true;
instance?.destroy();
canvas.remove();
},
resize() {
instance?.resize();
},
};
},
};
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: 'Regional sales by quarter',
chartAdapter: chartjsAdapter,
};
let host: HTMLElement | null = null;
let chart: GridChart | null = null;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(host);
else document.body.append(host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
log(`Chart created: ${type}, ${categories} categories, ${series} series`);
});
const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
log(`Chart updated: ${type}, ${categories} categories, ${series} series`);
});
log('Drag-select the region and Q1..Q3 cells, then press a button.');
return () => {
offCreated();
offUpdated();
cleanup();
host?.remove();
host = null;
};
}
// With nothing selected, select the first four rows (region to Q3) so the chart appears right away.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type });
}
export const actions = {
fromSelection: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'column');
},
allRows: (api: GridApi<Row>) => {
cleanup();
chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
},
lineChart: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'line');
},
clear: () => {
cleanup();
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.fromSelection(api)"
>Column chart from selection</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.allRows(api)"
>All rows</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.lineChart(api)"
>Line</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear</button>
</div>
<mx-grid style="height: 320px" [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 {
ChartAdapter,
ChartType,
ChartData,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
{ id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
{ id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
{ id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
{ id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
{ id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
{ id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
{ id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: 'Region', width: 110 },
{ id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: 'Note', editable: true, width: 110 },
];
type ChartJsInstance = {
data: { labels: string[]; datasets: unknown[] };
update(): void;
destroy(): void;
resize(): void;
};
type ChartJsCtor = new (el: HTMLCanvasElement, config: unknown) => ChartJsInstance;
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart(): ChartJsCtor | undefined {
return (window as unknown as { Chart?: ChartJsCtor }).Chart;
}
function loadChartJs(onReady: () => void): void {
if (globalChart() !== undefined) {
onReady();
return;
}
let script = document.querySelector<HTMLScriptElement>('script[data-chartjs]');
if (script === null) {
script = document.createElement('script');
script.src = CDN;
script.dataset.chartjs = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter: ChartAdapter = {
create(ctx) {
const canvas = document.createElement('canvas');
ctx.container.append(canvas);
const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
const toData = (d: ChartData) => ({
labels: d.categories,
datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
});
let latest = ctx.getData();
let instance: ChartJsInstance | null = null;
let dead = false;
loadChartJs(() => {
const Ctor = globalChart();
if (dead || Ctor === undefined) return;
instance = new Ctor(canvas, {
type: kind,
data: toData(latest),
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: ctx.type === 'bar' ? 'y' : 'x',
},
});
});
return {
update(data) {
latest = data;
if (instance === null) return;
const next = toData(data);
instance.data.labels = next.labels;
instance.data.datasets = next.datasets;
instance.update();
},
destroy() {
dead = true;
instance?.destroy();
canvas.remove();
},
resize() {
instance?.resize();
},
};
},
};
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: 'Regional sales by quarter',
chartAdapter: chartjsAdapter,
};
let host: HTMLElement | null = null;
let chart: GridChart | null = null;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(host);
else document.body.append(host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
log(`Chart created: ${type}, ${categories} categories, ${series} series`);
});
const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
log(`Chart updated: ${type}, ${categories} categories, ${series} series`);
});
log('Drag-select the region and Q1..Q3 cells, then press a button.');
return () => {
offCreated();
offUpdated();
cleanup();
host?.remove();
host = null;
};
}
// With nothing selected, select the first four rows (region to Q3) so the chart appears right away.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type });
}
export const actions = {
fromSelection: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'column');
},
allRows: (api: GridApi<Row>) => {
cleanup();
chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
},
lineChart: (api: GridApi<Row>) => {
cleanup();
chart = fromSelection(api, 'line');
},
clear: () => {
cleanup();
},
};