조건에 따라 편집 막기Lock cells depending on conditions
줄마다 규칙으로 편집 가능 여부를 정할 수 있어요. 발송된 주문은 메모를 잠그고, 접수 상태일 때만 금액을 고치게 하는 식이에요. 상태를 바꾸면 규칙이 바로 적용돼요.You can decide per row whether a cell can be edited. A shipped order locks its memo, and the amount is editable only while the status is received. Changing the status applies the rule at once.
코드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="rule">
<option value="status" selected>상태에 따라</option>
<option value="open">모두 열기</option>
<option value="locked">모두 잠그기</option>
</select>
</div>
<div id="grid" style="height: 300px"></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('rule').addEventListener('change', (event) => actions.rule(api, event.target.value));const rows = [
{ id: 1, order: 'A-1001', status: 'open', note: '선물 포장 요청', amount: 120000 },
{ id: 2, order: 'A-1002', status: 'packed', note: '배송 전에 전화 주세요', amount: 80000 },
{ id: 3, order: 'A-1003', status: 'shipped', note: '문 앞에 두었어요', amount: 45000 },
{ id: 4, order: 'A-1004', status: 'open', note: '', amount: 260000 },
{ id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99000 },
{ id: 6, order: 'A-1006', status: 'shipped', note: '경비실 보관', amount: 31000 },
];
let rule = 'status';
const statusLabel = { open: '접수', packed: '포장', shipped: '발송' };
// editable에 함수를 주면 줄마다 고칠 수 있는지가 달라져요. 편집을 시작할 때마다 함수를 다시 읽기 때문에
// 상태를 바꾸는 즉시 규칙이 적용돼요. 규칙(rule)을 "모두 열기"나 "모두 잠그기"로 바꾸면 컬럼 정의를 새로 넣어요.
const noteEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = () => [
{ id: 'order', title: '주문', width: 100 },
{
id: 'status',
title: '상태',
kind: 'select',
width: 100,
editable: rule !== 'locked',
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value), // 칸에도 코드(open) 대신 이름(접수)을 보여 줘요.
},
{ id: 'note', title: '메모 (발송 전만)', width: 190, editable: noteEditable },
{
id: 'amount',
title: '금액 (접수 상태만)',
kind: 'number',
width: 140,
align: 'end',
editable: amountEditable,
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
// 잠겼는지 한눈에 보도록 같은 규칙으로 계산한 칸을 하나 더 두었어요(저장하지 않고 getValue로 계산).
{
id: 'lock',
title: '메모·금액',
width: 110,
getValue: (row) => `${noteEditable(row) ? '메모 ✓' : '메모 ✗'} ${amountEditable(row) ? '금액 ✓' : '금액 ✗'}`,
},
];
export const options = {
columns: columns(),
rows,
rowKey: 'id',
};
// 잠긴 칸을 더블클릭하면 아무 일도 안 일어나는 것처럼 보이기 쉬워서, 왜 안 열리는지 기록에 알려 줘요.
const titleOf = (api, id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id, value) => id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
export function setup(api, log) {
log({
ko: '"메모"와 "금액" 칸을 더블클릭해 보세요. 상태에 따라 열리거나 열리지 않아요.',
en: 'Double-click a "메모" (note) or "금액" (amount) cell. Whether it opens depends on the status.',
});
const offs = [
api.on('editStarted', (e) => log({
ko: `${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)} 편집을 시작했어요`,
en: `Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`,
})),
api.on('editCommitted', (e) => {
const order = api.getRowByKey(e.rowKey)?.order;
log(`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`);
// 상태를 바꾸면 잠금 표시 칸이 바로 다시 계산되도록 줄을 다시 그려요.
if (e.columnId === 'status')
api.refresh();
}),
api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
const row = api.getRowByKey(rowKey);
if (!row || !['status', 'note', 'amount'].includes(columnId))
return;
const ok = columnId === 'note'
? noteEditable(row)
: columnId === 'amount'
? amountEditable(row)
: rule !== 'locked';
if (ok)
return;
const why = rule === 'locked'
? '지금은 "모두 잠그기"라서 모든 칸을 고칠 수 없어요.'
: columnId === 'note'
? `${statusLabel[row.status]} 상태에서는 메모를 고칠 수 없어요(발송 전에만 가능해요).`
: `${statusLabel[row.status]} 상태에서는 금액을 고칠 수 없어요(접수 상태일 때만 가능해요).`;
log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
rule: (api, value) => {
rule = (value ?? 'status');
api.setColumns(columns());
},
};<!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="rule">
<option value="status" selected>상태에 따라</option>
<option value="open">모두 열기</option>
<option value="locked">모두 잠그기</option>
</select>
</div>
<div id="grid" style="height: 300px"></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, order: 'A-1001', status: 'open', note: '선물 포장 요청', amount: 120000 },
{ id: 2, order: 'A-1002', status: 'packed', note: '배송 전에 전화 주세요', amount: 80000 },
{ id: 3, order: 'A-1003', status: 'shipped', note: '문 앞에 두었어요', amount: 45000 },
{ id: 4, order: 'A-1004', status: 'open', note: '', amount: 260000 },
{ id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99000 },
{ id: 6, order: 'A-1006', status: 'shipped', note: '경비실 보관', amount: 31000 },
];
let rule = 'status';
const statusLabel = { open: '접수', packed: '포장', shipped: '발송' };
// editable에 함수를 주면 줄마다 고칠 수 있는지가 달라져요. 편집을 시작할 때마다 함수를 다시 읽기 때문에
// 상태를 바꾸는 즉시 규칙이 적용돼요. 규칙(rule)을 "모두 열기"나 "모두 잠그기"로 바꾸면 컬럼 정의를 새로 넣어요.
const noteEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = () => [
{ id: 'order', title: '주문', width: 100 },
{
id: 'status',
title: '상태',
kind: 'select',
width: 100,
editable: rule !== 'locked',
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value), // 칸에도 코드(open) 대신 이름(접수)을 보여 줘요.
},
{ id: 'note', title: '메모 (발송 전만)', width: 190, editable: noteEditable },
{
id: 'amount',
title: '금액 (접수 상태만)',
kind: 'number',
width: 140,
align: 'end',
editable: amountEditable,
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
// 잠겼는지 한눈에 보도록 같은 규칙으로 계산한 칸을 하나 더 두었어요(저장하지 않고 getValue로 계산).
{
id: 'lock',
title: '메모·금액',
width: 110,
getValue: (row) => `${noteEditable(row) ? '메모 ✓' : '메모 ✗'} ${amountEditable(row) ? '금액 ✓' : '금액 ✗'}`,
},
];
const options = {
columns: columns(),
rows,
rowKey: 'id',
};
// 잠긴 칸을 더블클릭하면 아무 일도 안 일어나는 것처럼 보이기 쉬워서, 왜 안 열리는지 기록에 알려 줘요.
const titleOf = (api, id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id, value) => id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
function setup(api, log) {
log({
ko: '"메모"와 "금액" 칸을 더블클릭해 보세요. 상태에 따라 열리거나 열리지 않아요.',
en: 'Double-click a "메모" (note) or "금액" (amount) cell. Whether it opens depends on the status.',
});
const offs = [
api.on('editStarted', (e) => log({
ko: `${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)} 편집을 시작했어요`,
en: `Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`,
})),
api.on('editCommitted', (e) => {
const order = api.getRowByKey(e.rowKey)?.order;
log(`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`);
// 상태를 바꾸면 잠금 표시 칸이 바로 다시 계산되도록 줄을 다시 그려요.
if (e.columnId === 'status')
api.refresh();
}),
api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
const row = api.getRowByKey(rowKey);
if (!row || !['status', 'note', 'amount'].includes(columnId))
return;
const ok = columnId === 'note'
? noteEditable(row)
: columnId === 'amount'
? amountEditable(row)
: rule !== 'locked';
if (ok)
return;
const why = rule === 'locked'
? '지금은 "모두 잠그기"라서 모든 칸을 고칠 수 없어요.'
: columnId === 'note'
? `${statusLabel[row.status]} 상태에서는 메모를 고칠 수 없어요(발송 전에만 가능해요).`
: `${statusLabel[row.status]} 상태에서는 금액을 고칠 수 없어요(접수 상태일 때만 가능해요).`;
log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
}),
];
return () => offs.forEach((off) => off());
}
const actions = {
rule: (api, value) => {
rule = (value ?? 'status');
api.setColumns(columns());
},
};
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('rule').addEventListener('change', (event) => actions.rule(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.rule(api, event.target.value)}
>
<option value="status">상태에 따라</option>
<option value="open">모두 열기</option>
<option value="locked">모두 잠그기</option>
</select>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import type { ColumnDef, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
order: string;
status: string;
note: string;
amount: number;
}
const rows: Row[] = [
{ id: 1, order: 'A-1001', status: 'open', note: '선물 포장 요청', amount: 120000 },
{ id: 2, order: 'A-1002', status: 'packed', note: '배송 전에 전화 주세요', amount: 80000 },
{ id: 3, order: 'A-1003', status: 'shipped', note: '문 앞에 두었어요', amount: 45000 },
{ id: 4, order: 'A-1004', status: 'open', note: '', amount: 260000 },
{ id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99000 },
{ id: 6, order: 'A-1006', status: 'shipped', note: '경비실 보관', amount: 31000 },
];
type Rule = 'status' | 'open' | 'locked';
let rule: Rule = 'status';
const statusLabel: Record<string, string> = { open: '접수', packed: '포장', shipped: '발송' };
// editable에 함수를 주면 줄마다 고칠 수 있는지가 달라져요. 편집을 시작할 때마다 함수를 다시 읽기 때문에
// 상태를 바꾸는 즉시 규칙이 적용돼요. 규칙(rule)을 "모두 열기"나 "모두 잠그기"로 바꾸면 컬럼 정의를 새로 넣어요.
const noteEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = (): ColumnDef<Row>[] => [
{ id: 'order', title: '주문', width: 100 },
{
id: 'status',
title: '상태',
kind: 'select',
width: 100,
editable: rule !== 'locked',
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value), // 칸에도 코드(open) 대신 이름(접수)을 보여 줘요.
},
{ id: 'note', title: '메모 (발송 전만)', width: 190, editable: noteEditable },
{
id: 'amount',
title: '금액 (접수 상태만)',
kind: 'number',
width: 140,
align: 'end',
editable: amountEditable,
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
// 잠겼는지 한눈에 보도록 같은 규칙으로 계산한 칸을 하나 더 두었어요(저장하지 않고 getValue로 계산).
{
id: 'lock',
title: '메모·금액',
width: 110,
getValue: (row) =>
`${noteEditable(row) ? '메모 ✓' : '메모 ✗'} ${amountEditable(row) ? '금액 ✓' : '금액 ✗'}`,
},
];
export const options: GridOptions<Row> = {
columns: columns(),
rows,
rowKey: 'id',
};
// 잠긴 칸을 더블클릭하면 아무 일도 안 일어나는 것처럼 보이기 쉬워서, 왜 안 열리는지 기록에 알려 줘요.
const titleOf = (api: GridApi<Row>, id: string) =>
api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id: string, value: unknown) =>
id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '"메모"와 "금액" 칸을 더블클릭해 보세요. 상태에 따라 열리거나 열리지 않아요.',
en: 'Double-click a "메모" (note) or "금액" (amount) cell. Whether it opens depends on the status.',
});
const offs = [
api.on('editStarted', (e) =>
log({
ko: `${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)} 편집을 시작했어요`,
en: `Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`,
}),
),
api.on('editCommitted', (e) => {
const order = api.getRowByKey(e.rowKey)?.order;
log(
`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`,
);
// 상태를 바꾸면 잠금 표시 칸이 바로 다시 계산되도록 줄을 다시 그려요.
if (e.columnId === 'status') api.refresh();
}),
api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
const row = api.getRowByKey(rowKey);
if (!row || !['status', 'note', 'amount'].includes(columnId)) return;
const ok =
columnId === 'note'
? noteEditable(row)
: columnId === 'amount'
? amountEditable(row)
: rule !== 'locked';
if (ok) return;
const why =
rule === 'locked'
? '지금은 "모두 잠그기"라서 모든 칸을 고칠 수 없어요.'
: columnId === 'note'
? `${statusLabel[row.status]} 상태에서는 메모를 고칠 수 없어요(발송 전에만 가능해요).`
: `${statusLabel[row.status]} 상태에서는 금액을 고칠 수 없어요(접수 상태일 때만 가능해요).`;
log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
rule: (api: GridApi<Row>, value?: string) => {
rule = (value ?? 'status') as Rule;
api.setColumns(columns());
},
};버튼을 누르면 이 예제의 코드가 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.rule(api, ($event.target as HTMLSelectElement).value)"
>
<option value="status" selected>상태에 따라</option>
<option value="open">모두 열기</option>
<option value="locked">모두 잠그기</option>
</select>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import type { ColumnDef, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
order: string;
status: string;
note: string;
amount: number;
}
const rows: Row[] = [
{ id: 1, order: 'A-1001', status: 'open', note: '선물 포장 요청', amount: 120000 },
{ id: 2, order: 'A-1002', status: 'packed', note: '배송 전에 전화 주세요', amount: 80000 },
{ id: 3, order: 'A-1003', status: 'shipped', note: '문 앞에 두었어요', amount: 45000 },
{ id: 4, order: 'A-1004', status: 'open', note: '', amount: 260000 },
{ id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99000 },
{ id: 6, order: 'A-1006', status: 'shipped', note: '경비실 보관', amount: 31000 },
];
type Rule = 'status' | 'open' | 'locked';
let rule: Rule = 'status';
const statusLabel: Record<string, string> = { open: '접수', packed: '포장', shipped: '발송' };
// editable에 함수를 주면 줄마다 고칠 수 있는지가 달라져요. 편집을 시작할 때마다 함수를 다시 읽기 때문에
// 상태를 바꾸는 즉시 규칙이 적용돼요. 규칙(rule)을 "모두 열기"나 "모두 잠그기"로 바꾸면 컬럼 정의를 새로 넣어요.
const noteEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = (): ColumnDef<Row>[] => [
{ id: 'order', title: '주문', width: 100 },
{
id: 'status',
title: '상태',
kind: 'select',
width: 100,
editable: rule !== 'locked',
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value), // 칸에도 코드(open) 대신 이름(접수)을 보여 줘요.
},
{ id: 'note', title: '메모 (발송 전만)', width: 190, editable: noteEditable },
{
id: 'amount',
title: '금액 (접수 상태만)',
kind: 'number',
width: 140,
align: 'end',
editable: amountEditable,
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
// 잠겼는지 한눈에 보도록 같은 규칙으로 계산한 칸을 하나 더 두었어요(저장하지 않고 getValue로 계산).
{
id: 'lock',
title: '메모·금액',
width: 110,
getValue: (row) =>
`${noteEditable(row) ? '메모 ✓' : '메모 ✗'} ${amountEditable(row) ? '금액 ✓' : '금액 ✗'}`,
},
];
export const options: GridOptions<Row> = {
columns: columns(),
rows,
rowKey: 'id',
};
// 잠긴 칸을 더블클릭하면 아무 일도 안 일어나는 것처럼 보이기 쉬워서, 왜 안 열리는지 기록에 알려 줘요.
const titleOf = (api: GridApi<Row>, id: string) =>
api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id: string, value: unknown) =>
id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '"메모"와 "금액" 칸을 더블클릭해 보세요. 상태에 따라 열리거나 열리지 않아요.',
en: 'Double-click a "메모" (note) or "금액" (amount) cell. Whether it opens depends on the status.',
});
const offs = [
api.on('editStarted', (e) =>
log({
ko: `${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)} 편집을 시작했어요`,
en: `Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`,
}),
),
api.on('editCommitted', (e) => {
const order = api.getRowByKey(e.rowKey)?.order;
log(
`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`,
);
// 상태를 바꾸면 잠금 표시 칸이 바로 다시 계산되도록 줄을 다시 그려요.
if (e.columnId === 'status') api.refresh();
}),
api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
const row = api.getRowByKey(rowKey);
if (!row || !['status', 'note', 'amount'].includes(columnId)) return;
const ok =
columnId === 'note'
? noteEditable(row)
: columnId === 'amount'
? amountEditable(row)
: rule !== 'locked';
if (ok) return;
const why =
rule === 'locked'
? '지금은 "모두 잠그기"라서 모든 칸을 고칠 수 없어요.'
: columnId === 'note'
? `${statusLabel[row.status]} 상태에서는 메모를 고칠 수 없어요(발송 전에만 가능해요).`
: `${statusLabel[row.status]} 상태에서는 금액을 고칠 수 없어요(접수 상태일 때만 가능해요).`;
log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
rule: (api: GridApi<Row>, value?: string) => {
rule = (value ?? 'status') as Rule;
api.setColumns(columns());
},
};버튼을 누르면 이 예제의 코드가 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.rule(api, $any($event.target).value)"
>
<option value="status" selected>상태에 따라</option>
<option value="open">모두 열기</option>
<option value="locked">모두 잠그기</option>
</select>
</div>
<mx-grid style="height: 300px" [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 { ColumnDef, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
order: string;
status: string;
note: string;
amount: number;
}
const rows: Row[] = [
{ id: 1, order: 'A-1001', status: 'open', note: '선물 포장 요청', amount: 120000 },
{ id: 2, order: 'A-1002', status: 'packed', note: '배송 전에 전화 주세요', amount: 80000 },
{ id: 3, order: 'A-1003', status: 'shipped', note: '문 앞에 두었어요', amount: 45000 },
{ id: 4, order: 'A-1004', status: 'open', note: '', amount: 260000 },
{ id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99000 },
{ id: 6, order: 'A-1006', status: 'shipped', note: '경비실 보관', amount: 31000 },
];
type Rule = 'status' | 'open' | 'locked';
let rule: Rule = 'status';
const statusLabel: Record<string, string> = { open: '접수', packed: '포장', shipped: '발송' };
// editable에 함수를 주면 줄마다 고칠 수 있는지가 달라져요. 편집을 시작할 때마다 함수를 다시 읽기 때문에
// 상태를 바꾸는 즉시 규칙이 적용돼요. 규칙(rule)을 "모두 열기"나 "모두 잠그기"로 바꾸면 컬럼 정의를 새로 넣어요.
const noteEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = (): ColumnDef<Row>[] => [
{ id: 'order', title: '주문', width: 100 },
{
id: 'status',
title: '상태',
kind: 'select',
width: 100,
editable: rule !== 'locked',
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value), // 칸에도 코드(open) 대신 이름(접수)을 보여 줘요.
},
{ id: 'note', title: '메모 (발송 전만)', width: 190, editable: noteEditable },
{
id: 'amount',
title: '금액 (접수 상태만)',
kind: 'number',
width: 140,
align: 'end',
editable: amountEditable,
formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
},
// 잠겼는지 한눈에 보도록 같은 규칙으로 계산한 칸을 하나 더 두었어요(저장하지 않고 getValue로 계산).
{
id: 'lock',
title: '메모·금액',
width: 110,
getValue: (row) =>
`${noteEditable(row) ? '메모 ✓' : '메모 ✗'} ${amountEditable(row) ? '금액 ✓' : '금액 ✗'}`,
},
];
export const options: GridOptions<Row> = {
columns: columns(),
rows,
rowKey: 'id',
};
// 잠긴 칸을 더블클릭하면 아무 일도 안 일어나는 것처럼 보이기 쉬워서, 왜 안 열리는지 기록에 알려 줘요.
const titleOf = (api: GridApi<Row>, id: string) =>
api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id: string, value: unknown) =>
id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '"메모"와 "금액" 칸을 더블클릭해 보세요. 상태에 따라 열리거나 열리지 않아요.',
en: 'Double-click a "메모" (note) or "금액" (amount) cell. Whether it opens depends on the status.',
});
const offs = [
api.on('editStarted', (e) =>
log({
ko: `${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)} 편집을 시작했어요`,
en: `Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`,
}),
),
api.on('editCommitted', (e) => {
const order = api.getRowByKey(e.rowKey)?.order;
log(
`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`,
);
// 상태를 바꾸면 잠금 표시 칸이 바로 다시 계산되도록 줄을 다시 그려요.
if (e.columnId === 'status') api.refresh();
}),
api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
const row = api.getRowByKey(rowKey);
if (!row || !['status', 'note', 'amount'].includes(columnId)) return;
const ok =
columnId === 'note'
? noteEditable(row)
: columnId === 'amount'
? amountEditable(row)
: rule !== 'locked';
if (ok) return;
const why =
rule === 'locked'
? '지금은 "모두 잠그기"라서 모든 칸을 고칠 수 없어요.'
: columnId === 'note'
? `${statusLabel[row.status]} 상태에서는 메모를 고칠 수 없어요(발송 전에만 가능해요).`
: `${statusLabel[row.status]} 상태에서는 금액을 고칠 수 없어요(접수 상태일 때만 가능해요).`;
log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
rule: (api: GridApi<Row>, value?: string) => {
rule = (value ?? 'status') as Rule;
api.setColumns(columns());
},
};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="Lock rule" id="rule">
<option value="status" selected>By status</option>
<option value="open">Open all</option>
<option value="locked">Lock all</option>
</select>
</div>
<div id="grid" style="height: 300px"></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('rule').addEventListener('change', (event) => actions.rule(api, event.target.value));const rows = [
{ id: 1, order: 'A-1001', status: 'open', note: 'Gift wrap requested', amount: 120 },
{ id: 2, order: 'A-1002', status: 'packed', note: 'Call before delivery', amount: 80 },
{ id: 3, order: 'A-1003', status: 'shipped', note: 'Left at the door', amount: 45 },
{ id: 4, order: 'A-1004', status: 'open', note: '', amount: 260 },
{ id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99 },
{ id: 6, order: 'A-1006', status: 'shipped', note: 'Kept at the front desk', amount: 31 },
];
let rule = 'status';
const statusLabel = {
open: 'Received',
packed: 'Packed',
shipped: 'Shipped',
};
// When editable is a function, whether a row can be edited differs per row. The function is read again each time editing starts,
// so a rule applies as soon as the status changes. Switching the rule to "Open all" or "Lock all" passes in new column definitions.
const noteEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = () => [
{ id: 'order', title: 'Order', width: 100 },
{
id: 'status',
title: 'Status',
kind: 'select',
width: 110,
editable: rule !== 'locked',
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value), // The cell also shows the name (Received) instead of the code (open).
},
{ id: 'note', title: 'Note (before shipping only)', width: 220, editable: noteEditable },
{
id: 'amount',
title: 'Amount (Received only)',
kind: 'number',
width: 180,
align: 'end',
editable: amountEditable,
formatValue: (v) => `$${Number(v).toLocaleString('en-US', { minimumFractionDigits: 2 })}`,
},
// One more cell computed with the same rules so the lock state is visible at a glance (not stored; computed with getValue).
{
id: 'lock',
title: 'Note / Amount',
width: 150,
getValue: (row) => `${noteEditable(row) ? 'Note ✓' : 'Note ✗'} ${amountEditable(row) ? 'Amount ✓' : 'Amount ✗'}`,
},
];
export const options = {
columns: columns(),
rows,
rowKey: 'id',
};
// Double-clicking a locked cell can look like nothing happens, so the log explains why it does not open.
const titleOf = (api, id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id, value) => id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
export function setup(api, log) {
log('Double-click a "Note" or "Amount" cell. Whether it opens depends on the status.');
const offs = [
api.on('editStarted', (e) => log(`Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`)),
api.on('editCommitted', (e) => {
const order = api.getRowByKey(e.rowKey)?.order;
log(`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`);
// Redraw rows so the lock-state cell is recomputed right after the status changes.
if (e.columnId === 'status')
api.refresh();
}),
api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
const row = api.getRowByKey(rowKey);
if (!row || !['status', 'note', 'amount'].includes(columnId))
return;
const ok = columnId === 'note'
? noteEditable(row)
: columnId === 'amount'
? amountEditable(row)
: rule !== 'locked';
if (ok)
return;
const why = rule === 'locked'
? 'The rule is "Lock all" right now, so no cell can be edited.'
: columnId === 'note'
? `The note cannot be edited in the ${statusLabel[row.status]} status (only before shipping).`
: `The amount cannot be edited in the ${statusLabel[row.status]} status (only while Received).`;
log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
rule: (api, value) => {
rule = (value ?? 'status');
api.setColumns(columns());
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Lock cells depending on conditions</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Lock rule" id="rule">
<option value="status" selected>By status</option>
<option value="open">Open all</option>
<option value="locked">Lock all</option>
</select>
</div>
<div id="grid" style="height: 300px"></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, order: 'A-1001', status: 'open', note: 'Gift wrap requested', amount: 120 },
{ id: 2, order: 'A-1002', status: 'packed', note: 'Call before delivery', amount: 80 },
{ id: 3, order: 'A-1003', status: 'shipped', note: 'Left at the door', amount: 45 },
{ id: 4, order: 'A-1004', status: 'open', note: '', amount: 260 },
{ id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99 },
{ id: 6, order: 'A-1006', status: 'shipped', note: 'Kept at the front desk', amount: 31 },
];
let rule = 'status';
const statusLabel = {
open: 'Received',
packed: 'Packed',
shipped: 'Shipped',
};
// When editable is a function, whether a row can be edited differs per row. The function is read again each time editing starts,
// so a rule applies as soon as the status changes. Switching the rule to "Open all" or "Lock all" passes in new column definitions.
const noteEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row) => rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = () => [
{ id: 'order', title: 'Order', width: 100 },
{
id: 'status',
title: 'Status',
kind: 'select',
width: 110,
editable: rule !== 'locked',
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value), // The cell also shows the name (Received) instead of the code (open).
},
{ id: 'note', title: 'Note (before shipping only)', width: 220, editable: noteEditable },
{
id: 'amount',
title: 'Amount (Received only)',
kind: 'number',
width: 180,
align: 'end',
editable: amountEditable,
formatValue: (v) => `$${Number(v).toLocaleString('en-US', { minimumFractionDigits: 2 })}`,
},
// One more cell computed with the same rules so the lock state is visible at a glance (not stored; computed with getValue).
{
id: 'lock',
title: 'Note / Amount',
width: 150,
getValue: (row) => `${noteEditable(row) ? 'Note ✓' : 'Note ✗'} ${amountEditable(row) ? 'Amount ✓' : 'Amount ✗'}`,
},
];
const options = {
columns: columns(),
rows,
rowKey: 'id',
};
// Double-clicking a locked cell can look like nothing happens, so the log explains why it does not open.
const titleOf = (api, id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id, value) => id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
function setup(api, log) {
log('Double-click a "Note" or "Amount" cell. Whether it opens depends on the status.');
const offs = [
api.on('editStarted', (e) => log(`Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`)),
api.on('editCommitted', (e) => {
const order = api.getRowByKey(e.rowKey)?.order;
log(`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`);
// Redraw rows so the lock-state cell is recomputed right after the status changes.
if (e.columnId === 'status')
api.refresh();
}),
api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
const row = api.getRowByKey(rowKey);
if (!row || !['status', 'note', 'amount'].includes(columnId))
return;
const ok = columnId === 'note'
? noteEditable(row)
: columnId === 'amount'
? amountEditable(row)
: rule !== 'locked';
if (ok)
return;
const why = rule === 'locked'
? 'The rule is "Lock all" right now, so no cell can be edited.'
: columnId === 'note'
? `The note cannot be edited in the ${statusLabel[row.status]} status (only before shipping).`
: `The amount cannot be edited in the ${statusLabel[row.status]} status (only while Received).`;
log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
}),
];
return () => offs.forEach((off) => off());
}
const actions = {
rule: (api, value) => {
rule = (value ?? 'status');
api.setColumns(columns());
},
};
options.ariaLabel = "Lock cells depending on conditions";
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('rule').addEventListener('change', (event) => actions.rule(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="Lock rule"
disabled={!api}
onChange={(event) => api && actions.rule(api, event.target.value)}
>
<option value="status">By status</option>
<option value="open">Open all</option>
<option value="locked">Lock all</option>
</select>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import type { ColumnDef, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
order: string;
status: string;
note: string;
amount: number;
}
const rows: Row[] = [
{ id: 1, order: 'A-1001', status: 'open', note: 'Gift wrap requested', amount: 120 },
{ id: 2, order: 'A-1002', status: 'packed', note: 'Call before delivery', amount: 80 },
{ id: 3, order: 'A-1003', status: 'shipped', note: 'Left at the door', amount: 45 },
{ id: 4, order: 'A-1004', status: 'open', note: '', amount: 260 },
{ id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99 },
{ id: 6, order: 'A-1006', status: 'shipped', note: 'Kept at the front desk', amount: 31 },
];
type Rule = 'status' | 'open' | 'locked';
let rule: Rule = 'status';
const statusLabel: Record<string, string> = {
open: 'Received',
packed: 'Packed',
shipped: 'Shipped',
};
// When editable is a function, whether a row can be edited differs per row. The function is read again each time editing starts,
// so a rule applies as soon as the status changes. Switching the rule to "Open all" or "Lock all" passes in new column definitions.
const noteEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = (): ColumnDef<Row>[] => [
{ id: 'order', title: 'Order', width: 100 },
{
id: 'status',
title: 'Status',
kind: 'select',
width: 110,
editable: rule !== 'locked',
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value), // The cell also shows the name (Received) instead of the code (open).
},
{ id: 'note', title: 'Note (before shipping only)', width: 220, editable: noteEditable },
{
id: 'amount',
title: 'Amount (Received only)',
kind: 'number',
width: 180,
align: 'end',
editable: amountEditable,
formatValue: (v) => `$${Number(v).toLocaleString('en-US', { minimumFractionDigits: 2 })}`,
},
// One more cell computed with the same rules so the lock state is visible at a glance (not stored; computed with getValue).
{
id: 'lock',
title: 'Note / Amount',
width: 150,
getValue: (row) =>
`${noteEditable(row) ? 'Note ✓' : 'Note ✗'} ${amountEditable(row) ? 'Amount ✓' : 'Amount ✗'}`,
},
];
export const options: GridOptions<Row> = {
columns: columns(),
rows,
rowKey: 'id',
};
// Double-clicking a locked cell can look like nothing happens, so the log explains why it does not open.
const titleOf = (api: GridApi<Row>, id: string) =>
api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id: string, value: unknown) =>
id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log('Double-click a "Note" or "Amount" cell. Whether it opens depends on the status.');
const offs = [
api.on('editStarted', (e) =>
log(`Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`),
),
api.on('editCommitted', (e) => {
const order = api.getRowByKey(e.rowKey)?.order;
log(
`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`,
);
// Redraw rows so the lock-state cell is recomputed right after the status changes.
if (e.columnId === 'status') api.refresh();
}),
api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
const row = api.getRowByKey(rowKey);
if (!row || !['status', 'note', 'amount'].includes(columnId)) return;
const ok =
columnId === 'note'
? noteEditable(row)
: columnId === 'amount'
? amountEditable(row)
: rule !== 'locked';
if (ok) return;
const why =
rule === 'locked'
? 'The rule is "Lock all" right now, so no cell can be edited.'
: columnId === 'note'
? `The note cannot be edited in the ${statusLabel[row.status]} status (only before shipping).`
: `The amount cannot be edited in the ${statusLabel[row.status]} status (only while Received).`;
log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
rule: (api: GridApi<Row>, value?: string) => {
rule = (value ?? 'status') as Rule;
api.setColumns(columns());
},
};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="Lock rule"
:disabled="!api"
@change="api && actions.rule(api, ($event.target as HTMLSelectElement).value)"
>
<option value="status" selected>By status</option>
<option value="open">Open all</option>
<option value="locked">Lock all</option>
</select>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import type { ColumnDef, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
order: string;
status: string;
note: string;
amount: number;
}
const rows: Row[] = [
{ id: 1, order: 'A-1001', status: 'open', note: 'Gift wrap requested', amount: 120 },
{ id: 2, order: 'A-1002', status: 'packed', note: 'Call before delivery', amount: 80 },
{ id: 3, order: 'A-1003', status: 'shipped', note: 'Left at the door', amount: 45 },
{ id: 4, order: 'A-1004', status: 'open', note: '', amount: 260 },
{ id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99 },
{ id: 6, order: 'A-1006', status: 'shipped', note: 'Kept at the front desk', amount: 31 },
];
type Rule = 'status' | 'open' | 'locked';
let rule: Rule = 'status';
const statusLabel: Record<string, string> = {
open: 'Received',
packed: 'Packed',
shipped: 'Shipped',
};
// When editable is a function, whether a row can be edited differs per row. The function is read again each time editing starts,
// so a rule applies as soon as the status changes. Switching the rule to "Open all" or "Lock all" passes in new column definitions.
const noteEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = (): ColumnDef<Row>[] => [
{ id: 'order', title: 'Order', width: 100 },
{
id: 'status',
title: 'Status',
kind: 'select',
width: 110,
editable: rule !== 'locked',
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value), // The cell also shows the name (Received) instead of the code (open).
},
{ id: 'note', title: 'Note (before shipping only)', width: 220, editable: noteEditable },
{
id: 'amount',
title: 'Amount (Received only)',
kind: 'number',
width: 180,
align: 'end',
editable: amountEditable,
formatValue: (v) => `$${Number(v).toLocaleString('en-US', { minimumFractionDigits: 2 })}`,
},
// One more cell computed with the same rules so the lock state is visible at a glance (not stored; computed with getValue).
{
id: 'lock',
title: 'Note / Amount',
width: 150,
getValue: (row) =>
`${noteEditable(row) ? 'Note ✓' : 'Note ✗'} ${amountEditable(row) ? 'Amount ✓' : 'Amount ✗'}`,
},
];
export const options: GridOptions<Row> = {
columns: columns(),
rows,
rowKey: 'id',
};
// Double-clicking a locked cell can look like nothing happens, so the log explains why it does not open.
const titleOf = (api: GridApi<Row>, id: string) =>
api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id: string, value: unknown) =>
id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log('Double-click a "Note" or "Amount" cell. Whether it opens depends on the status.');
const offs = [
api.on('editStarted', (e) =>
log(`Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`),
),
api.on('editCommitted', (e) => {
const order = api.getRowByKey(e.rowKey)?.order;
log(
`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`,
);
// Redraw rows so the lock-state cell is recomputed right after the status changes.
if (e.columnId === 'status') api.refresh();
}),
api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
const row = api.getRowByKey(rowKey);
if (!row || !['status', 'note', 'amount'].includes(columnId)) return;
const ok =
columnId === 'note'
? noteEditable(row)
: columnId === 'amount'
? amountEditable(row)
: rule !== 'locked';
if (ok) return;
const why =
rule === 'locked'
? 'The rule is "Lock all" right now, so no cell can be edited.'
: columnId === 'note'
? `The note cannot be edited in the ${statusLabel[row.status]} status (only before shipping).`
: `The amount cannot be edited in the ${statusLabel[row.status]} status (only while Received).`;
log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
rule: (api: GridApi<Row>, value?: string) => {
rule = (value ?? 'status') as Rule;
api.setColumns(columns());
},
};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="Lock rule"
[disabled]="!api"
(change)="api && actions.rule(api, $any($event.target).value)"
>
<option value="status" selected>By status</option>
<option value="open">Open all</option>
<option value="locked">Lock all</option>
</select>
</div>
<mx-grid style="height: 300px" [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 { ColumnDef, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
order: string;
status: string;
note: string;
amount: number;
}
const rows: Row[] = [
{ id: 1, order: 'A-1001', status: 'open', note: 'Gift wrap requested', amount: 120 },
{ id: 2, order: 'A-1002', status: 'packed', note: 'Call before delivery', amount: 80 },
{ id: 3, order: 'A-1003', status: 'shipped', note: 'Left at the door', amount: 45 },
{ id: 4, order: 'A-1004', status: 'open', note: '', amount: 260 },
{ id: 5, order: 'A-1005', status: 'packed', note: '', amount: 99 },
{ id: 6, order: 'A-1006', status: 'shipped', note: 'Kept at the front desk', amount: 31 },
];
type Rule = 'status' | 'open' | 'locked';
let rule: Rule = 'status';
const statusLabel: Record<string, string> = {
open: 'Received',
packed: 'Packed',
shipped: 'Shipped',
};
// When editable is a function, whether a row can be edited differs per row. The function is read again each time editing starts,
// so a rule applies as soon as the status changes. Switching the rule to "Open all" or "Lock all" passes in new column definitions.
const noteEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status !== 'shipped';
const amountEditable = (row: Row): boolean =>
rule === 'open' ? true : rule === 'locked' ? false : row.status === 'open';
const columns = (): ColumnDef<Row>[] => [
{ id: 'order', title: 'Order', width: 100 },
{
id: 'status',
title: 'Status',
kind: 'select',
width: 110,
editable: rule !== 'locked',
editorOptions: Object.entries(statusLabel).map(([value, label]) => ({ value, label })),
formatValue: (value) => statusLabel[String(value)] ?? String(value), // The cell also shows the name (Received) instead of the code (open).
},
{ id: 'note', title: 'Note (before shipping only)', width: 220, editable: noteEditable },
{
id: 'amount',
title: 'Amount (Received only)',
kind: 'number',
width: 180,
align: 'end',
editable: amountEditable,
formatValue: (v) => `$${Number(v).toLocaleString('en-US', { minimumFractionDigits: 2 })}`,
},
// One more cell computed with the same rules so the lock state is visible at a glance (not stored; computed with getValue).
{
id: 'lock',
title: 'Note / Amount',
width: 150,
getValue: (row) =>
`${noteEditable(row) ? 'Note ✓' : 'Note ✗'} ${amountEditable(row) ? 'Amount ✓' : 'Amount ✗'}`,
},
];
export const options: GridOptions<Row> = {
columns: columns(),
rows,
rowKey: 'id',
};
// Double-clicking a locked cell can look like nothing happens, so the log explains why it does not open.
const titleOf = (api: GridApi<Row>, id: string) =>
api.getColumns().find((c) => c.id === id)?.title ?? id;
const nameOf = (id: string, value: unknown) =>
id === 'status' ? (statusLabel[String(value)] ?? String(value)) : String(value);
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log('Double-click a "Note" or "Amount" cell. Whether it opens depends on the status.');
const offs = [
api.on('editStarted', (e) =>
log(`Started editing ${api.getRowByKey(e.rowKey)?.order} ${titleOf(api, e.columnId)}`),
),
api.on('editCommitted', (e) => {
const order = api.getRowByKey(e.rowKey)?.order;
log(
`${order} ${titleOf(api, e.columnId)}: ${nameOf(e.columnId, e.oldValue)} → ${nameOf(e.columnId, e.newValue)}`,
);
// Redraw rows so the lock-state cell is recomputed right after the status changes.
if (e.columnId === 'status') api.refresh();
}),
api.on('cellDoubleClicked', ({ rowKey, columnId }) => {
const row = api.getRowByKey(rowKey);
if (!row || !['status', 'note', 'amount'].includes(columnId)) return;
const ok =
columnId === 'note'
? noteEditable(row)
: columnId === 'amount'
? amountEditable(row)
: rule !== 'locked';
if (ok) return;
const why =
rule === 'locked'
? 'The rule is "Lock all" right now, so no cell can be edited.'
: columnId === 'note'
? `The note cannot be edited in the ${statusLabel[row.status]} status (only before shipping).`
: `The amount cannot be edited in the ${statusLabel[row.status]} status (only while Received).`;
log(`🔒 ${row.order} ${titleOf(api, columnId)}: ${why}`);
}),
];
return () => offs.forEach((off) => off());
}
export const actions = {
rule: (api: GridApi<Row>, value?: string) => {
rule = (value ?? 'status') as Rule;
api.setColumns(columns());
},
};