필요한 명령만 담은 나만의 컬럼 메뉴Your own column menu with only the commands you want
기본 ⋮ 메뉴 대신 필요한 명령(고정, 맨 앞으로, 더 넓게, 숨기기)만 담은 메뉴를 직접 만들어요. 메뉴는 내 화면이라 컬럼을 바꾸는 기능만 불러 쓰면 돼요. 기본 메뉴의 언어를 바꾸는 법도 함께 보여 줘요.Build your own menu with only the commands you need (pin, move first, widen, hide) instead of the default ⋮ menu. The menu is your own UI and just calls the column functions. It also shows how to change the default menu's language.
코드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="target">
<option value="name" selected>이름</option>
<option value="team">팀</option>
<option value="city">근무지</option>
<option value="salary">연봉</option>
</select>
<button type="button" id="pinStart">왼쪽에 고정</button>
<button type="button" id="pinEnd">오른쪽에 고정</button>
<button type="button" id="unpin">고정 풀기</button>
<button type="button" id="first">맨 앞으로</button>
<button type="button" id="wider">40px 더 넓게</button>
<button type="button" id="hide">숨기기</button>
<button type="button" id="showAll">숨긴 컬럼 모두 보이기</button>
<select aria-label="기본 메뉴 언어" id="language">
<option value="ko" selected>한국어 (기본)</option>
<option value="en">English</option>
</select>
</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('target').addEventListener('change', (event) => actions.target(api, event.target.value));
document.getElementById('pinStart').addEventListener('click', () => actions.pinStart(api));
document.getElementById('pinEnd').addEventListener('click', () => actions.pinEnd(api));
document.getElementById('unpin').addEventListener('click', () => actions.unpin(api));
document.getElementById('first').addEventListener('click', () => actions.first(api));
document.getElementById('wider').addEventListener('click', () => actions.wider(api));
document.getElementById('hide').addEventListener('click', () => actions.hide(api));
document.getElementById('showAll').addEventListener('click', () => actions.showAll(api));
document.getElementById('language').addEventListener('change', (event) => actions.language(api, event.target.value));const names = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const cities = ['서울', '부산', '대구', '제주'];
// 기본 메뉴(columnMenu)가 꼭 맞지 않을 때는 메뉴를 직접 만들어요. 메뉴는 내 화면이고, 선택한 항목이 컬럼 API를 부르면 돼요.
// 여기서는 컬럼과 명령을 고르는 두 칸으로 흉내 내요. 메뉴 문구를 바꾸는 법도 함께 보여 줘요(locale, messages).
export const options = {
columnMenu: true,
columns: [
{ id: 'id', title: '번호', width: 70, align: 'end' },
{ id: 'name', title: '이름', width: 130 },
{ id: 'team', title: '팀', width: 120 },
{ id: 'city', title: '근무지', width: 110 },
{ id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5],
team: teams[(i * 3) % 4],
city: cities[i % 4],
salary: 3800 + ((i * 530) % 4200),
})),
rowKey: 'id',
};
let column = 'name';
let say = () => { };
export function setup(api, log) {
column = 'name';
say = log;
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
let timer;
const offs = [
// 컬럼 하나를 옮기면 사이에 낀 컬럼의 이동도 연달아 오니까, 잠깐 모았다가 새 순서를 한 줄로 알려 줘요.
api.on('columnMoved', () => {
clearTimeout(timer);
timer = setTimeout(() => log({
ko: `새 순서: ${api.getColumnOrder().map(title).join(' · ')}`,
en: `New order: ${api.getColumnOrder().map(title).join(' · ')}`,
}), 80);
}),
api.on('columnResized', (e) => log({
ko: `${title(e.columnId)} 컬럼 폭을 ${Math.round(e.width)}px로 바꿨어요`,
en: `${title(e.columnId)} column width set to ${Math.round(e.width)}px`,
})),
api.on('columnPinned', (e) => log({
ko: `${title(e.columnId)} 컬럼을 ${e.pinned === 'start' ? '왼쪽에 고정했어요' : e.pinned === 'end' ? '오른쪽에 고정했어요' : '고정 해제했어요'}`,
en: `${title(e.columnId)} column ${e.pinned === 'start' ? 'pinned to the left' : e.pinned === 'end' ? 'pinned to the right' : 'unpinned'}`,
})),
api.on('columnVisibilityChanged', (e) => log({
ko: `${title(e.columnId)} 컬럼을 ${e.hidden ? '숨겼어요' : '다시 보여 줬어요'}`,
en: `${title(e.columnId)} column ${e.hidden ? 'hidden' : 'shown again'}`,
})),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
const run = (api, command) => {
if (command === 'pin-start')
api.pinColumn(column, 'start');
else if (command === 'pin-end')
api.pinColumn(column, 'end');
else if (command === 'unpin')
api.pinColumn(column, null);
else if (command === 'first')
api.moveColumn(column, 0);
else if (command === 'wider') {
const width = api.getColumnState().find((s) => s.id === column)?.width ?? 120;
api.resizeColumn(column, width + 40);
}
else if (command === 'hide') {
// 마지막 한 컬럼은 숨기지 않아요.
if (api.getColumnState().filter((s) => !s.hidden).length > 1)
api.setColumnVisible(column, false);
else
say({ ko: '마지막 컬럼은 숨길 수 없어요', en: 'The last column cannot be hidden' });
}
};
export const actions = {
target: (_api, value) => {
column = value ?? 'name';
},
pinStart: (api) => run(api, 'pin-start'),
pinEnd: (api) => run(api, 'pin-end'),
unpin: (api) => run(api, 'unpin'),
first: (api) => run(api, 'first'),
wider: (api) => run(api, 'wider'),
hide: (api) => run(api, 'hide'),
showAll: (api) => api.getColumns().forEach((c) => api.setColumnVisible(c.id, true)),
// 기본 메뉴의 문구는 영어로, 또는 원하는 말로 바꿀 수 있어요.
language: (api, value) => {
api.setOptions({ locale: value === 'en' ? 'en' : 'ko' });
},
};<!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="target">
<option value="name" selected>이름</option>
<option value="team">팀</option>
<option value="city">근무지</option>
<option value="salary">연봉</option>
</select>
<button type="button" id="pinStart">왼쪽에 고정</button>
<button type="button" id="pinEnd">오른쪽에 고정</button>
<button type="button" id="unpin">고정 풀기</button>
<button type="button" id="first">맨 앞으로</button>
<button type="button" id="wider">40px 더 넓게</button>
<button type="button" id="hide">숨기기</button>
<button type="button" id="showAll">숨긴 컬럼 모두 보이기</button>
<select aria-label="기본 메뉴 언어" id="language">
<option value="ko" selected>한국어 (기본)</option>
<option value="en">English</option>
</select>
</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 names = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const cities = ['서울', '부산', '대구', '제주'];
// 기본 메뉴(columnMenu)가 꼭 맞지 않을 때는 메뉴를 직접 만들어요. 메뉴는 내 화면이고, 선택한 항목이 컬럼 API를 부르면 돼요.
// 여기서는 컬럼과 명령을 고르는 두 칸으로 흉내 내요. 메뉴 문구를 바꾸는 법도 함께 보여 줘요(locale, messages).
const options = {
columnMenu: true,
columns: [
{ id: 'id', title: '번호', width: 70, align: 'end' },
{ id: 'name', title: '이름', width: 130 },
{ id: 'team', title: '팀', width: 120 },
{ id: 'city', title: '근무지', width: 110 },
{ id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5],
team: teams[(i * 3) % 4],
city: cities[i % 4],
salary: 3800 + ((i * 530) % 4200),
})),
rowKey: 'id',
};
let column = 'name';
let say = () => { };
function setup(api, log) {
column = 'name';
say = log;
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
let timer;
const offs = [
// 컬럼 하나를 옮기면 사이에 낀 컬럼의 이동도 연달아 오니까, 잠깐 모았다가 새 순서를 한 줄로 알려 줘요.
api.on('columnMoved', () => {
clearTimeout(timer);
timer = setTimeout(() => log({
ko: `새 순서: ${api.getColumnOrder().map(title).join(' · ')}`,
en: `New order: ${api.getColumnOrder().map(title).join(' · ')}`,
}), 80);
}),
api.on('columnResized', (e) => log({
ko: `${title(e.columnId)} 컬럼 폭을 ${Math.round(e.width)}px로 바꿨어요`,
en: `${title(e.columnId)} column width set to ${Math.round(e.width)}px`,
})),
api.on('columnPinned', (e) => log({
ko: `${title(e.columnId)} 컬럼을 ${e.pinned === 'start' ? '왼쪽에 고정했어요' : e.pinned === 'end' ? '오른쪽에 고정했어요' : '고정 해제했어요'}`,
en: `${title(e.columnId)} column ${e.pinned === 'start' ? 'pinned to the left' : e.pinned === 'end' ? 'pinned to the right' : 'unpinned'}`,
})),
api.on('columnVisibilityChanged', (e) => log({
ko: `${title(e.columnId)} 컬럼을 ${e.hidden ? '숨겼어요' : '다시 보여 줬어요'}`,
en: `${title(e.columnId)} column ${e.hidden ? 'hidden' : 'shown again'}`,
})),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
const run = (api, command) => {
if (command === 'pin-start')
api.pinColumn(column, 'start');
else if (command === 'pin-end')
api.pinColumn(column, 'end');
else if (command === 'unpin')
api.pinColumn(column, null);
else if (command === 'first')
api.moveColumn(column, 0);
else if (command === 'wider') {
const width = api.getColumnState().find((s) => s.id === column)?.width ?? 120;
api.resizeColumn(column, width + 40);
}
else if (command === 'hide') {
// 마지막 한 컬럼은 숨기지 않아요.
if (api.getColumnState().filter((s) => !s.hidden).length > 1)
api.setColumnVisible(column, false);
else
say({ ko: '마지막 컬럼은 숨길 수 없어요', en: 'The last column cannot be hidden' });
}
};
const actions = {
target: (_api, value) => {
column = value ?? 'name';
},
pinStart: (api) => run(api, 'pin-start'),
pinEnd: (api) => run(api, 'pin-end'),
unpin: (api) => run(api, 'unpin'),
first: (api) => run(api, 'first'),
wider: (api) => run(api, 'wider'),
hide: (api) => run(api, 'hide'),
showAll: (api) => api.getColumns().forEach((c) => api.setColumnVisible(c.id, true)),
// 기본 메뉴의 문구는 영어로, 또는 원하는 말로 바꿀 수 있어요.
language: (api, value) => {
api.setOptions({ locale: value === 'en' ? 'en' : 'ko' });
},
};
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('target').addEventListener('change', (event) => actions.target(api, event.target.value));
document.getElementById('pinStart').addEventListener('click', () => actions.pinStart(api));
document.getElementById('pinEnd').addEventListener('click', () => actions.pinEnd(api));
document.getElementById('unpin').addEventListener('click', () => actions.unpin(api));
document.getElementById('first').addEventListener('click', () => actions.first(api));
document.getElementById('wider').addEventListener('click', () => actions.wider(api));
document.getElementById('hide').addEventListener('click', () => actions.hide(api));
document.getElementById('showAll').addEventListener('click', () => actions.showAll(api));
document.getElementById('language').addEventListener('change', (event) => actions.language(api, event.target.value));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="컬럼"
disabled={!api}
onChange={(event) => api && actions.target(api, event.target.value)}
>
<option value="name">이름</option>
<option value="team">팀</option>
<option value="city">근무지</option>
<option value="salary">연봉</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pinStart(api)}
>왼쪽에 고정</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pinEnd(api)}
>오른쪽에 고정</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.unpin(api)}
>고정 풀기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.first(api)}
>맨 앞으로</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.wider(api)}
>40px 더 넓게</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.hide(api)}
>숨기기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.showAll(api)}
>숨긴 컬럼 모두 보이기</button>
<select defaultValue="name"
aria-label="기본 메뉴 언어"
disabled={!api}
onChange={(event) => api && actions.language(api, event.target.value)}
>
<option value="ko">한국어 (기본)</option>
<option value="en">English</option>
</select>
</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;
name: string;
team: string;
city: string;
salary: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const cities = ['서울', '부산', '대구', '제주'];
// 기본 메뉴(columnMenu)가 꼭 맞지 않을 때는 메뉴를 직접 만들어요. 메뉴는 내 화면이고, 선택한 항목이 컬럼 API를 부르면 돼요.
// 여기서는 컬럼과 명령을 고르는 두 칸으로 흉내 내요. 메뉴 문구를 바꾸는 법도 함께 보여 줘요(locale, messages).
export const options: GridOptions<Row> = {
columnMenu: true,
columns: [
{ id: 'id', title: '번호', width: 70, align: 'end' },
{ id: 'name', title: '이름', width: 130 },
{ id: 'team', title: '팀', width: 120 },
{ id: 'city', title: '근무지', width: 110 },
{ id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
city: cities[i % 4] as string,
salary: 3800 + ((i * 530) % 4200),
})),
rowKey: 'id',
};
let column = 'name';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
column = 'name';
say = log;
const title = (id: string): string => api.getColumns().find((c) => c.id === id)?.title ?? id;
let timer: ReturnType<typeof setTimeout> | undefined;
const offs = [
// 컬럼 하나를 옮기면 사이에 낀 컬럼의 이동도 연달아 오니까, 잠깐 모았다가 새 순서를 한 줄로 알려 줘요.
api.on('columnMoved', () => {
clearTimeout(timer);
timer = setTimeout(
() =>
log({
ko: `새 순서: ${api.getColumnOrder().map(title).join(' · ')}`,
en: `New order: ${api.getColumnOrder().map(title).join(' · ')}`,
}),
80,
);
}),
api.on('columnResized', (e) =>
log({
ko: `${title(e.columnId)} 컬럼 폭을 ${Math.round(e.width)}px로 바꿨어요`,
en: `${title(e.columnId)} column width set to ${Math.round(e.width)}px`,
}),
),
api.on('columnPinned', (e) =>
log({
ko: `${title(e.columnId)} 컬럼을 ${e.pinned === 'start' ? '왼쪽에 고정했어요' : e.pinned === 'end' ? '오른쪽에 고정했어요' : '고정 해제했어요'}`,
en: `${title(e.columnId)} column ${e.pinned === 'start' ? 'pinned to the left' : e.pinned === 'end' ? 'pinned to the right' : 'unpinned'}`,
}),
),
api.on('columnVisibilityChanged', (e) =>
log({
ko: `${title(e.columnId)} 컬럼을 ${e.hidden ? '숨겼어요' : '다시 보여 줬어요'}`,
en: `${title(e.columnId)} column ${e.hidden ? 'hidden' : 'shown again'}`,
}),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
const run = (api: GridApi<Row>, command: string): void => {
if (command === 'pin-start') api.pinColumn(column, 'start');
else if (command === 'pin-end') api.pinColumn(column, 'end');
else if (command === 'unpin') api.pinColumn(column, null);
else if (command === 'first') api.moveColumn(column, 0);
else if (command === 'wider') {
const width = api.getColumnState().find((s) => s.id === column)?.width ?? 120;
api.resizeColumn(column, width + 40);
} else if (command === 'hide') {
// 마지막 한 컬럼은 숨기지 않아요.
if (api.getColumnState().filter((s) => !s.hidden).length > 1)
api.setColumnVisible(column, false);
else say({ ko: '마지막 컬럼은 숨길 수 없어요', en: 'The last column cannot be hidden' });
}
};
export const actions = {
target: (_api: GridApi<Row>, value?: string) => {
column = value ?? 'name';
},
pinStart: (api: GridApi<Row>) => run(api, 'pin-start'),
pinEnd: (api: GridApi<Row>) => run(api, 'pin-end'),
unpin: (api: GridApi<Row>) => run(api, 'unpin'),
first: (api: GridApi<Row>) => run(api, 'first'),
wider: (api: GridApi<Row>) => run(api, 'wider'),
hide: (api: GridApi<Row>) => run(api, 'hide'),
showAll: (api: GridApi<Row>) => api.getColumns().forEach((c) => api.setColumnVisible(c.id, true)),
// 기본 메뉴의 문구는 영어로, 또는 원하는 말로 바꿀 수 있어요.
language: (api: GridApi<Row>, value?: string) => {
api.setOptions({ locale: value === 'en' ? 'en' : 'ko' });
},
};버튼을 누르면 이 예제의 코드가 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.target(api, ($event.target as HTMLSelectElement).value)"
>
<option value="name" selected>이름</option>
<option value="team">팀</option>
<option value="city">근무지</option>
<option value="salary">연봉</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.pinStart(api)"
>왼쪽에 고정</button>
<button type="button" :disabled="!api" @click="api && actions.pinEnd(api)">오른쪽에 고정</button>
<button type="button" :disabled="!api" @click="api && actions.unpin(api)">고정 풀기</button>
<button type="button" :disabled="!api" @click="api && actions.first(api)">맨 앞으로</button>
<button type="button" :disabled="!api" @click="api && actions.wider(api)">40px 더 넓게</button>
<button type="button" :disabled="!api" @click="api && actions.hide(api)">숨기기</button>
<button type="button" :disabled="!api" @click="api && actions.showAll(api)">숨긴 컬럼 모두 보이기</button>
<select
aria-label="기본 메뉴 언어"
:disabled="!api"
@change="api && actions.language(api, ($event.target as HTMLSelectElement).value)"
>
<option value="ko" selected>한국어 (기본)</option>
<option value="en">English</option>
</select>
</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;
name: string;
team: string;
city: string;
salary: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const cities = ['서울', '부산', '대구', '제주'];
// 기본 메뉴(columnMenu)가 꼭 맞지 않을 때는 메뉴를 직접 만들어요. 메뉴는 내 화면이고, 선택한 항목이 컬럼 API를 부르면 돼요.
// 여기서는 컬럼과 명령을 고르는 두 칸으로 흉내 내요. 메뉴 문구를 바꾸는 법도 함께 보여 줘요(locale, messages).
export const options: GridOptions<Row> = {
columnMenu: true,
columns: [
{ id: 'id', title: '번호', width: 70, align: 'end' },
{ id: 'name', title: '이름', width: 130 },
{ id: 'team', title: '팀', width: 120 },
{ id: 'city', title: '근무지', width: 110 },
{ id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
city: cities[i % 4] as string,
salary: 3800 + ((i * 530) % 4200),
})),
rowKey: 'id',
};
let column = 'name';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
column = 'name';
say = log;
const title = (id: string): string => api.getColumns().find((c) => c.id === id)?.title ?? id;
let timer: ReturnType<typeof setTimeout> | undefined;
const offs = [
// 컬럼 하나를 옮기면 사이에 낀 컬럼의 이동도 연달아 오니까, 잠깐 모았다가 새 순서를 한 줄로 알려 줘요.
api.on('columnMoved', () => {
clearTimeout(timer);
timer = setTimeout(
() =>
log({
ko: `새 순서: ${api.getColumnOrder().map(title).join(' · ')}`,
en: `New order: ${api.getColumnOrder().map(title).join(' · ')}`,
}),
80,
);
}),
api.on('columnResized', (e) =>
log({
ko: `${title(e.columnId)} 컬럼 폭을 ${Math.round(e.width)}px로 바꿨어요`,
en: `${title(e.columnId)} column width set to ${Math.round(e.width)}px`,
}),
),
api.on('columnPinned', (e) =>
log({
ko: `${title(e.columnId)} 컬럼을 ${e.pinned === 'start' ? '왼쪽에 고정했어요' : e.pinned === 'end' ? '오른쪽에 고정했어요' : '고정 해제했어요'}`,
en: `${title(e.columnId)} column ${e.pinned === 'start' ? 'pinned to the left' : e.pinned === 'end' ? 'pinned to the right' : 'unpinned'}`,
}),
),
api.on('columnVisibilityChanged', (e) =>
log({
ko: `${title(e.columnId)} 컬럼을 ${e.hidden ? '숨겼어요' : '다시 보여 줬어요'}`,
en: `${title(e.columnId)} column ${e.hidden ? 'hidden' : 'shown again'}`,
}),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
const run = (api: GridApi<Row>, command: string): void => {
if (command === 'pin-start') api.pinColumn(column, 'start');
else if (command === 'pin-end') api.pinColumn(column, 'end');
else if (command === 'unpin') api.pinColumn(column, null);
else if (command === 'first') api.moveColumn(column, 0);
else if (command === 'wider') {
const width = api.getColumnState().find((s) => s.id === column)?.width ?? 120;
api.resizeColumn(column, width + 40);
} else if (command === 'hide') {
// 마지막 한 컬럼은 숨기지 않아요.
if (api.getColumnState().filter((s) => !s.hidden).length > 1)
api.setColumnVisible(column, false);
else say({ ko: '마지막 컬럼은 숨길 수 없어요', en: 'The last column cannot be hidden' });
}
};
export const actions = {
target: (_api: GridApi<Row>, value?: string) => {
column = value ?? 'name';
},
pinStart: (api: GridApi<Row>) => run(api, 'pin-start'),
pinEnd: (api: GridApi<Row>) => run(api, 'pin-end'),
unpin: (api: GridApi<Row>) => run(api, 'unpin'),
first: (api: GridApi<Row>) => run(api, 'first'),
wider: (api: GridApi<Row>) => run(api, 'wider'),
hide: (api: GridApi<Row>) => run(api, 'hide'),
showAll: (api: GridApi<Row>) => api.getColumns().forEach((c) => api.setColumnVisible(c.id, true)),
// 기본 메뉴의 문구는 영어로, 또는 원하는 말로 바꿀 수 있어요.
language: (api: GridApi<Row>, value?: string) => {
api.setOptions({ locale: value === 'en' ? 'en' : 'ko' });
},
};버튼을 누르면 이 예제의 코드가 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.target(api, $any($event.target).value)"
>
<option value="name" selected>이름</option>
<option value="team">팀</option>
<option value="city">근무지</option>
<option value="salary">연봉</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pinStart(api)"
>왼쪽에 고정</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pinEnd(api)"
>오른쪽에 고정</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.unpin(api)"
>고정 풀기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.first(api)"
>맨 앞으로</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.wider(api)"
>40px 더 넓게</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.hide(api)"
>숨기기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.showAll(api)"
>숨긴 컬럼 모두 보이기</button>
<select
aria-label="기본 메뉴 언어"
[disabled]="!api"
(change)="api && actions.language(api, $any($event.target).value)"
>
<option value="ko" selected>한국어 (기본)</option>
<option value="en">English</option>
</select>
</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;
name: string;
team: string;
city: string;
salary: number;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const cities = ['서울', '부산', '대구', '제주'];
// 기본 메뉴(columnMenu)가 꼭 맞지 않을 때는 메뉴를 직접 만들어요. 메뉴는 내 화면이고, 선택한 항목이 컬럼 API를 부르면 돼요.
// 여기서는 컬럼과 명령을 고르는 두 칸으로 흉내 내요. 메뉴 문구를 바꾸는 법도 함께 보여 줘요(locale, messages).
export const options: GridOptions<Row> = {
columnMenu: true,
columns: [
{ id: 'id', title: '번호', width: 70, align: 'end' },
{ id: 'name', title: '이름', width: 130 },
{ id: 'team', title: '팀', width: 120 },
{ id: 'city', title: '근무지', width: 110 },
{ id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
city: cities[i % 4] as string,
salary: 3800 + ((i * 530) % 4200),
})),
rowKey: 'id',
};
let column = 'name';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
column = 'name';
say = log;
const title = (id: string): string => api.getColumns().find((c) => c.id === id)?.title ?? id;
let timer: ReturnType<typeof setTimeout> | undefined;
const offs = [
// 컬럼 하나를 옮기면 사이에 낀 컬럼의 이동도 연달아 오니까, 잠깐 모았다가 새 순서를 한 줄로 알려 줘요.
api.on('columnMoved', () => {
clearTimeout(timer);
timer = setTimeout(
() =>
log({
ko: `새 순서: ${api.getColumnOrder().map(title).join(' · ')}`,
en: `New order: ${api.getColumnOrder().map(title).join(' · ')}`,
}),
80,
);
}),
api.on('columnResized', (e) =>
log({
ko: `${title(e.columnId)} 컬럼 폭을 ${Math.round(e.width)}px로 바꿨어요`,
en: `${title(e.columnId)} column width set to ${Math.round(e.width)}px`,
}),
),
api.on('columnPinned', (e) =>
log({
ko: `${title(e.columnId)} 컬럼을 ${e.pinned === 'start' ? '왼쪽에 고정했어요' : e.pinned === 'end' ? '오른쪽에 고정했어요' : '고정 해제했어요'}`,
en: `${title(e.columnId)} column ${e.pinned === 'start' ? 'pinned to the left' : e.pinned === 'end' ? 'pinned to the right' : 'unpinned'}`,
}),
),
api.on('columnVisibilityChanged', (e) =>
log({
ko: `${title(e.columnId)} 컬럼을 ${e.hidden ? '숨겼어요' : '다시 보여 줬어요'}`,
en: `${title(e.columnId)} column ${e.hidden ? 'hidden' : 'shown again'}`,
}),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
const run = (api: GridApi<Row>, command: string): void => {
if (command === 'pin-start') api.pinColumn(column, 'start');
else if (command === 'pin-end') api.pinColumn(column, 'end');
else if (command === 'unpin') api.pinColumn(column, null);
else if (command === 'first') api.moveColumn(column, 0);
else if (command === 'wider') {
const width = api.getColumnState().find((s) => s.id === column)?.width ?? 120;
api.resizeColumn(column, width + 40);
} else if (command === 'hide') {
// 마지막 한 컬럼은 숨기지 않아요.
if (api.getColumnState().filter((s) => !s.hidden).length > 1)
api.setColumnVisible(column, false);
else say({ ko: '마지막 컬럼은 숨길 수 없어요', en: 'The last column cannot be hidden' });
}
};
export const actions = {
target: (_api: GridApi<Row>, value?: string) => {
column = value ?? 'name';
},
pinStart: (api: GridApi<Row>) => run(api, 'pin-start'),
pinEnd: (api: GridApi<Row>) => run(api, 'pin-end'),
unpin: (api: GridApi<Row>) => run(api, 'unpin'),
first: (api: GridApi<Row>) => run(api, 'first'),
wider: (api: GridApi<Row>) => run(api, 'wider'),
hide: (api: GridApi<Row>) => run(api, 'hide'),
showAll: (api: GridApi<Row>) => api.getColumns().forEach((c) => api.setColumnVisible(c.id, true)),
// 기본 메뉴의 문구는 영어로, 또는 원하는 말로 바꿀 수 있어요.
language: (api: GridApi<Row>, value?: string) => {
api.setOptions({ locale: value === 'en' ? 'en' : 'ko' });
},
};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="Column" id="target">
<option value="name" selected>Name</option>
<option value="team">Team</option>
<option value="city">City</option>
<option value="salary">Salary</option>
</select>
<button type="button" id="pinStart">Pin left</button>
<button type="button" id="pinEnd">Pin right</button>
<button type="button" id="unpin">Unpin</button>
<button type="button" id="first">Move first</button>
<button type="button" id="wider">40px wider</button>
<button type="button" id="hide">Hide</button>
<button type="button" id="showAll">Show all columns</button>
<select aria-label="Built-in menu language" id="language">
<option value="ko" selected>Korean (default)</option>
<option value="en">English</option>
</select>
</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('target').addEventListener('change', (event) => actions.target(api, event.target.value));
document.getElementById('pinStart').addEventListener('click', () => actions.pinStart(api));
document.getElementById('pinEnd').addEventListener('click', () => actions.pinEnd(api));
document.getElementById('unpin').addEventListener('click', () => actions.unpin(api));
document.getElementById('first').addEventListener('click', () => actions.first(api));
document.getElementById('wider').addEventListener('click', () => actions.wider(api));
document.getElementById('hide').addEventListener('click', () => actions.hide(api));
document.getElementById('showAll').addEventListener('click', () => actions.showAll(api));
document.getElementById('language').addEventListener('change', (event) => actions.language(api, event.target.value));const names = ['Liam Carter', 'Emma Stone', 'Noah Hayes', 'Olivia Reed', 'Ethan Cole'];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const cities = ['Seattle', 'Boston', 'Denver', 'Honolulu'];
// When the default menu (columnMenu) is not quite right, build the menu yourself. The menu is your own UI, and the chosen item just calls the column API.
// Here it is imitated with two boxes that pick a column and a command. It also shows how to change the menu text (locale, messages).
export const options = {
columnMenu: true,
columns: [
{ id: 'id', title: 'No', width: 70, align: 'end' },
{ id: 'name', title: 'Name', width: 130 },
{ id: 'team', title: 'Team', width: 120 },
{ id: 'city', title: 'City', width: 110 },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5],
team: teams[(i * 3) % 4],
city: cities[i % 4],
salary: (3800 + ((i * 530) % 4200)) * 10,
})),
rowKey: 'id',
};
let column = 'name';
let say = () => { };
export function setup(api, log) {
column = 'name';
say = log;
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
let timer;
const offs = [
// Moving one column also sends moves for the columns in between, so collect them briefly and report the new order in one line.
api.on('columnMoved', () => {
clearTimeout(timer);
timer = setTimeout(() => log(`New order: ${api.getColumnOrder().map(title).join(' · ')}`), 80);
}),
api.on('columnResized', (e) => log(`${title(e.columnId)} column width set to ${Math.round(e.width)}px`)),
api.on('columnPinned', (e) => log(`${title(e.columnId)} column ${e.pinned === 'start' ? 'pinned to the left' : e.pinned === 'end' ? 'pinned to the right' : 'unpinned'}`)),
api.on('columnVisibilityChanged', (e) => log(`${title(e.columnId)} column ${e.hidden ? 'hidden' : 'shown again'}`)),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
const run = (api, command) => {
if (command === 'pin-start')
api.pinColumn(column, 'start');
else if (command === 'pin-end')
api.pinColumn(column, 'end');
else if (command === 'unpin')
api.pinColumn(column, null);
else if (command === 'first')
api.moveColumn(column, 0);
else if (command === 'wider') {
const width = api.getColumnState().find((s) => s.id === column)?.width ?? 120;
api.resizeColumn(column, width + 40);
}
else if (command === 'hide') {
// The last remaining column is not hidden.
if (api.getColumnState().filter((s) => !s.hidden).length > 1)
api.setColumnVisible(column, false);
else
say('The last column cannot be hidden');
}
};
export const actions = {
target: (_api, value) => {
column = value ?? 'name';
},
pinStart: (api) => run(api, 'pin-start'),
pinEnd: (api) => run(api, 'pin-end'),
unpin: (api) => run(api, 'unpin'),
first: (api) => run(api, 'first'),
wider: (api) => run(api, 'wider'),
hide: (api) => run(api, 'hide'),
showAll: (api) => api.getColumns().forEach((c) => api.setColumnVisible(c.id, true)),
// The default menu text can be switched to English, or to any wording you want.
language: (api, value) => {
api.setOptions({ locale: value === 'en' ? 'en' : 'ko' });
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Your own column menu with only the commands you want</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Column" id="target">
<option value="name" selected>Name</option>
<option value="team">Team</option>
<option value="city">City</option>
<option value="salary">Salary</option>
</select>
<button type="button" id="pinStart">Pin left</button>
<button type="button" id="pinEnd">Pin right</button>
<button type="button" id="unpin">Unpin</button>
<button type="button" id="first">Move first</button>
<button type="button" id="wider">40px wider</button>
<button type="button" id="hide">Hide</button>
<button type="button" id="showAll">Show all columns</button>
<select aria-label="Built-in menu language" id="language">
<option value="ko" selected>Korean (default)</option>
<option value="en">English</option>
</select>
</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 names = ['Liam Carter', 'Emma Stone', 'Noah Hayes', 'Olivia Reed', 'Ethan Cole'];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const cities = ['Seattle', 'Boston', 'Denver', 'Honolulu'];
// When the default menu (columnMenu) is not quite right, build the menu yourself. The menu is your own UI, and the chosen item just calls the column API.
// Here it is imitated with two boxes that pick a column and a command. It also shows how to change the menu text (locale, messages).
const options = {
columnMenu: true,
columns: [
{ id: 'id', title: 'No', width: 70, align: 'end' },
{ id: 'name', title: 'Name', width: 130 },
{ id: 'team', title: 'Team', width: 120 },
{ id: 'city', title: 'City', width: 110 },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5],
team: teams[(i * 3) % 4],
city: cities[i % 4],
salary: (3800 + ((i * 530) % 4200)) * 10,
})),
rowKey: 'id',
};
let column = 'name';
let say = () => { };
function setup(api, log) {
column = 'name';
say = log;
const title = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
let timer;
const offs = [
// Moving one column also sends moves for the columns in between, so collect them briefly and report the new order in one line.
api.on('columnMoved', () => {
clearTimeout(timer);
timer = setTimeout(() => log(`New order: ${api.getColumnOrder().map(title).join(' · ')}`), 80);
}),
api.on('columnResized', (e) => log(`${title(e.columnId)} column width set to ${Math.round(e.width)}px`)),
api.on('columnPinned', (e) => log(`${title(e.columnId)} column ${e.pinned === 'start' ? 'pinned to the left' : e.pinned === 'end' ? 'pinned to the right' : 'unpinned'}`)),
api.on('columnVisibilityChanged', (e) => log(`${title(e.columnId)} column ${e.hidden ? 'hidden' : 'shown again'}`)),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
const run = (api, command) => {
if (command === 'pin-start')
api.pinColumn(column, 'start');
else if (command === 'pin-end')
api.pinColumn(column, 'end');
else if (command === 'unpin')
api.pinColumn(column, null);
else if (command === 'first')
api.moveColumn(column, 0);
else if (command === 'wider') {
const width = api.getColumnState().find((s) => s.id === column)?.width ?? 120;
api.resizeColumn(column, width + 40);
}
else if (command === 'hide') {
// The last remaining column is not hidden.
if (api.getColumnState().filter((s) => !s.hidden).length > 1)
api.setColumnVisible(column, false);
else
say('The last column cannot be hidden');
}
};
const actions = {
target: (_api, value) => {
column = value ?? 'name';
},
pinStart: (api) => run(api, 'pin-start'),
pinEnd: (api) => run(api, 'pin-end'),
unpin: (api) => run(api, 'unpin'),
first: (api) => run(api, 'first'),
wider: (api) => run(api, 'wider'),
hide: (api) => run(api, 'hide'),
showAll: (api) => api.getColumns().forEach((c) => api.setColumnVisible(c.id, true)),
// The default menu text can be switched to English, or to any wording you want.
language: (api, value) => {
api.setOptions({ locale: value === 'en' ? 'en' : 'ko' });
},
};
options.ariaLabel = "Your own column menu with only the commands you want";
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('target').addEventListener('change', (event) => actions.target(api, event.target.value));
document.getElementById('pinStart').addEventListener('click', () => actions.pinStart(api));
document.getElementById('pinEnd').addEventListener('click', () => actions.pinEnd(api));
document.getElementById('unpin').addEventListener('click', () => actions.unpin(api));
document.getElementById('first').addEventListener('click', () => actions.first(api));
document.getElementById('wider').addEventListener('click', () => actions.wider(api));
document.getElementById('hide').addEventListener('click', () => actions.hide(api));
document.getElementById('showAll').addEventListener('click', () => actions.showAll(api));
document.getElementById('language').addEventListener('change', (event) => actions.language(api, event.target.value));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="Column"
disabled={!api}
onChange={(event) => api && actions.target(api, event.target.value)}
>
<option value="name">Name</option>
<option value="team">Team</option>
<option value="city">City</option>
<option value="salary">Salary</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pinStart(api)}
>Pin left</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pinEnd(api)}
>Pin right</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.unpin(api)}
>Unpin</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.first(api)}
>Move first</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.wider(api)}
>40px wider</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.hide(api)}
>Hide</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.showAll(api)}
>Show all columns</button>
<select defaultValue="name"
aria-label="Built-in menu language"
disabled={!api}
onChange={(event) => api && actions.language(api, event.target.value)}
>
<option value="ko">Korean (default)</option>
<option value="en">English</option>
</select>
</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;
name: string;
team: string;
city: string;
salary: number;
}
const names = ['Liam Carter', 'Emma Stone', 'Noah Hayes', 'Olivia Reed', 'Ethan Cole'];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const cities = ['Seattle', 'Boston', 'Denver', 'Honolulu'];
// When the default menu (columnMenu) is not quite right, build the menu yourself. The menu is your own UI, and the chosen item just calls the column API.
// Here it is imitated with two boxes that pick a column and a command. It also shows how to change the menu text (locale, messages).
export const options: GridOptions<Row> = {
columnMenu: true,
columns: [
{ id: 'id', title: 'No', width: 70, align: 'end' },
{ id: 'name', title: 'Name', width: 130 },
{ id: 'team', title: 'Team', width: 120 },
{ id: 'city', title: 'City', width: 110 },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
city: cities[i % 4] as string,
salary: (3800 + ((i * 530) % 4200)) * 10,
})),
rowKey: 'id',
};
let column = 'name';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
column = 'name';
say = log;
const title = (id: string): string => api.getColumns().find((c) => c.id === id)?.title ?? id;
let timer: ReturnType<typeof setTimeout> | undefined;
const offs = [
// Moving one column also sends moves for the columns in between, so collect them briefly and report the new order in one line.
api.on('columnMoved', () => {
clearTimeout(timer);
timer = setTimeout(
() => log(`New order: ${api.getColumnOrder().map(title).join(' · ')}`),
80,
);
}),
api.on('columnResized', (e) =>
log(`${title(e.columnId)} column width set to ${Math.round(e.width)}px`),
),
api.on('columnPinned', (e) =>
log(
`${title(e.columnId)} column ${e.pinned === 'start' ? 'pinned to the left' : e.pinned === 'end' ? 'pinned to the right' : 'unpinned'}`,
),
),
api.on('columnVisibilityChanged', (e) =>
log(`${title(e.columnId)} column ${e.hidden ? 'hidden' : 'shown again'}`),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
const run = (api: GridApi<Row>, command: string): void => {
if (command === 'pin-start') api.pinColumn(column, 'start');
else if (command === 'pin-end') api.pinColumn(column, 'end');
else if (command === 'unpin') api.pinColumn(column, null);
else if (command === 'first') api.moveColumn(column, 0);
else if (command === 'wider') {
const width = api.getColumnState().find((s) => s.id === column)?.width ?? 120;
api.resizeColumn(column, width + 40);
} else if (command === 'hide') {
// The last remaining column is not hidden.
if (api.getColumnState().filter((s) => !s.hidden).length > 1)
api.setColumnVisible(column, false);
else say('The last column cannot be hidden');
}
};
export const actions = {
target: (_api: GridApi<Row>, value?: string) => {
column = value ?? 'name';
},
pinStart: (api: GridApi<Row>) => run(api, 'pin-start'),
pinEnd: (api: GridApi<Row>) => run(api, 'pin-end'),
unpin: (api: GridApi<Row>) => run(api, 'unpin'),
first: (api: GridApi<Row>) => run(api, 'first'),
wider: (api: GridApi<Row>) => run(api, 'wider'),
hide: (api: GridApi<Row>) => run(api, 'hide'),
showAll: (api: GridApi<Row>) => api.getColumns().forEach((c) => api.setColumnVisible(c.id, true)),
// The default menu text can be switched to English, or to any wording you want.
language: (api: GridApi<Row>, value?: string) => {
api.setOptions({ locale: value === 'en' ? 'en' : 'ko' });
},
};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="Column"
:disabled="!api"
@change="api && actions.target(api, ($event.target as HTMLSelectElement).value)"
>
<option value="name" selected>Name</option>
<option value="team">Team</option>
<option value="city">City</option>
<option value="salary">Salary</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.pinStart(api)"
>Pin left</button>
<button type="button" :disabled="!api" @click="api && actions.pinEnd(api)">Pin right</button>
<button type="button" :disabled="!api" @click="api && actions.unpin(api)">Unpin</button>
<button type="button" :disabled="!api" @click="api && actions.first(api)">Move first</button>
<button type="button" :disabled="!api" @click="api && actions.wider(api)">40px wider</button>
<button type="button" :disabled="!api" @click="api && actions.hide(api)">Hide</button>
<button type="button" :disabled="!api" @click="api && actions.showAll(api)">Show all columns</button>
<select
aria-label="Built-in menu language"
:disabled="!api"
@change="api && actions.language(api, ($event.target as HTMLSelectElement).value)"
>
<option value="ko" selected>Korean (default)</option>
<option value="en">English</option>
</select>
</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;
name: string;
team: string;
city: string;
salary: number;
}
const names = ['Liam Carter', 'Emma Stone', 'Noah Hayes', 'Olivia Reed', 'Ethan Cole'];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const cities = ['Seattle', 'Boston', 'Denver', 'Honolulu'];
// When the default menu (columnMenu) is not quite right, build the menu yourself. The menu is your own UI, and the chosen item just calls the column API.
// Here it is imitated with two boxes that pick a column and a command. It also shows how to change the menu text (locale, messages).
export const options: GridOptions<Row> = {
columnMenu: true,
columns: [
{ id: 'id', title: 'No', width: 70, align: 'end' },
{ id: 'name', title: 'Name', width: 130 },
{ id: 'team', title: 'Team', width: 120 },
{ id: 'city', title: 'City', width: 110 },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
city: cities[i % 4] as string,
salary: (3800 + ((i * 530) % 4200)) * 10,
})),
rowKey: 'id',
};
let column = 'name';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
column = 'name';
say = log;
const title = (id: string): string => api.getColumns().find((c) => c.id === id)?.title ?? id;
let timer: ReturnType<typeof setTimeout> | undefined;
const offs = [
// Moving one column also sends moves for the columns in between, so collect them briefly and report the new order in one line.
api.on('columnMoved', () => {
clearTimeout(timer);
timer = setTimeout(
() => log(`New order: ${api.getColumnOrder().map(title).join(' · ')}`),
80,
);
}),
api.on('columnResized', (e) =>
log(`${title(e.columnId)} column width set to ${Math.round(e.width)}px`),
),
api.on('columnPinned', (e) =>
log(
`${title(e.columnId)} column ${e.pinned === 'start' ? 'pinned to the left' : e.pinned === 'end' ? 'pinned to the right' : 'unpinned'}`,
),
),
api.on('columnVisibilityChanged', (e) =>
log(`${title(e.columnId)} column ${e.hidden ? 'hidden' : 'shown again'}`),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
const run = (api: GridApi<Row>, command: string): void => {
if (command === 'pin-start') api.pinColumn(column, 'start');
else if (command === 'pin-end') api.pinColumn(column, 'end');
else if (command === 'unpin') api.pinColumn(column, null);
else if (command === 'first') api.moveColumn(column, 0);
else if (command === 'wider') {
const width = api.getColumnState().find((s) => s.id === column)?.width ?? 120;
api.resizeColumn(column, width + 40);
} else if (command === 'hide') {
// The last remaining column is not hidden.
if (api.getColumnState().filter((s) => !s.hidden).length > 1)
api.setColumnVisible(column, false);
else say('The last column cannot be hidden');
}
};
export const actions = {
target: (_api: GridApi<Row>, value?: string) => {
column = value ?? 'name';
},
pinStart: (api: GridApi<Row>) => run(api, 'pin-start'),
pinEnd: (api: GridApi<Row>) => run(api, 'pin-end'),
unpin: (api: GridApi<Row>) => run(api, 'unpin'),
first: (api: GridApi<Row>) => run(api, 'first'),
wider: (api: GridApi<Row>) => run(api, 'wider'),
hide: (api: GridApi<Row>) => run(api, 'hide'),
showAll: (api: GridApi<Row>) => api.getColumns().forEach((c) => api.setColumnVisible(c.id, true)),
// The default menu text can be switched to English, or to any wording you want.
language: (api: GridApi<Row>, value?: string) => {
api.setOptions({ locale: value === 'en' ? 'en' : 'ko' });
},
};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="Column"
[disabled]="!api"
(change)="api && actions.target(api, $any($event.target).value)"
>
<option value="name" selected>Name</option>
<option value="team">Team</option>
<option value="city">City</option>
<option value="salary">Salary</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pinStart(api)"
>Pin left</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pinEnd(api)"
>Pin right</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.unpin(api)"
>Unpin</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.first(api)"
>Move first</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.wider(api)"
>40px wider</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.hide(api)"
>Hide</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.showAll(api)"
>Show all columns</button>
<select
aria-label="Built-in menu language"
[disabled]="!api"
(change)="api && actions.language(api, $any($event.target).value)"
>
<option value="ko" selected>Korean (default)</option>
<option value="en">English</option>
</select>
</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;
name: string;
team: string;
city: string;
salary: number;
}
const names = ['Liam Carter', 'Emma Stone', 'Noah Hayes', 'Olivia Reed', 'Ethan Cole'];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const cities = ['Seattle', 'Boston', 'Denver', 'Honolulu'];
// When the default menu (columnMenu) is not quite right, build the menu yourself. The menu is your own UI, and the chosen item just calls the column API.
// Here it is imitated with two boxes that pick a column and a command. It also shows how to change the menu text (locale, messages).
export const options: GridOptions<Row> = {
columnMenu: true,
columns: [
{ id: 'id', title: 'No', width: 70, align: 'end' },
{ id: 'name', title: 'Name', width: 130 },
{ id: 'team', title: 'Team', width: 120 },
{ id: 'city', title: 'City', width: 110 },
{ id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
],
rows: Array.from({ length: 6 }, (_, i) => ({
id: i + 1,
name: names[i % 5] as string,
team: teams[(i * 3) % 4] as string,
city: cities[i % 4] as string,
salary: (3800 + ((i * 530) % 4200)) * 10,
})),
rowKey: 'id',
};
let column = 'name';
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
column = 'name';
say = log;
const title = (id: string): string => api.getColumns().find((c) => c.id === id)?.title ?? id;
let timer: ReturnType<typeof setTimeout> | undefined;
const offs = [
// Moving one column also sends moves for the columns in between, so collect them briefly and report the new order in one line.
api.on('columnMoved', () => {
clearTimeout(timer);
timer = setTimeout(
() => log(`New order: ${api.getColumnOrder().map(title).join(' · ')}`),
80,
);
}),
api.on('columnResized', (e) =>
log(`${title(e.columnId)} column width set to ${Math.round(e.width)}px`),
),
api.on('columnPinned', (e) =>
log(
`${title(e.columnId)} column ${e.pinned === 'start' ? 'pinned to the left' : e.pinned === 'end' ? 'pinned to the right' : 'unpinned'}`,
),
),
api.on('columnVisibilityChanged', (e) =>
log(`${title(e.columnId)} column ${e.hidden ? 'hidden' : 'shown again'}`),
),
];
return () => {
clearTimeout(timer);
offs.forEach((off) => off());
};
}
const run = (api: GridApi<Row>, command: string): void => {
if (command === 'pin-start') api.pinColumn(column, 'start');
else if (command === 'pin-end') api.pinColumn(column, 'end');
else if (command === 'unpin') api.pinColumn(column, null);
else if (command === 'first') api.moveColumn(column, 0);
else if (command === 'wider') {
const width = api.getColumnState().find((s) => s.id === column)?.width ?? 120;
api.resizeColumn(column, width + 40);
} else if (command === 'hide') {
// The last remaining column is not hidden.
if (api.getColumnState().filter((s) => !s.hidden).length > 1)
api.setColumnVisible(column, false);
else say('The last column cannot be hidden');
}
};
export const actions = {
target: (_api: GridApi<Row>, value?: string) => {
column = value ?? 'name';
},
pinStart: (api: GridApi<Row>) => run(api, 'pin-start'),
pinEnd: (api: GridApi<Row>) => run(api, 'pin-end'),
unpin: (api: GridApi<Row>) => run(api, 'unpin'),
first: (api: GridApi<Row>) => run(api, 'first'),
wider: (api: GridApi<Row>) => run(api, 'wider'),
hide: (api: GridApi<Row>) => run(api, 'hide'),
showAll: (api: GridApi<Row>) => api.getColumns().forEach((c) => api.setColumnVisible(c.id, true)),
// The default menu text can be switched to English, or to any wording you want.
language: (api: GridApi<Row>, value?: string) => {
api.setOptions({ locale: value === 'en' ? 'en' : 'ko' });
},
};