고른 행에 한꺼번에 승인·반려·삭제Approve, reject or delete the selected rows at once
체크박스로 여러 행을 고른 뒤 툴바 버튼으로 한꺼번에 처리하는 화면이에요. 접수 상태인 행만 승인·반려가 되고 나머지는 건너뛰어요. 처리한 결과와 건너뛴 행 수를 기록 창에 알려 줘요.Tick several rows, then act on them all from toolbar buttons. Only received rows can be approved or rejected; others are skipped, and the log reports what changed and what was skipped.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="selectWaiting">접수 행 모두 선택</button>
<button type="button" id="approve">승인</button>
<button type="button" id="reject">반려</button>
<button type="button" id="removeSelected">선택 삭제</button>
<button type="button" id="reset">처음 목록으로</button>
</div>
<div id="grid" style="height: 380px"></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('selectWaiting').addEventListener('click', () => actions.selectWaiting(api));
document.getElementById('approve').addEventListener('click', () => actions.approve(api));
document.getElementById('reject').addEventListener('click', () => actions.reject(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'바다유통',
'해든전자',
];
const statuses = ['접수', '승인', '접수', '반려', '접수', '접수', '승인', '접수'];
const initial = () => customers.map((customer, i) => ({
id: i + 1,
customer,
total: 430000 + ((i * 613000) % 2900000),
status: statuses[i],
}));
export const options = {
columns: [
{ id: 'customer', title: '고객사', width: 150 },
{
id: 'total',
title: '주문 금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{ id: 'status', title: '상태', width: 90 },
],
rows: initial(),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0)
return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const euroRo = (word) => (batchim(word) && batchim(word) !== 8 ? '으로' : '로');
let say = () => { };
const selectedRows = (api) => api
.getSelectedKeys()
.map((key) => api.getRowByKey(key))
.filter((row) => row !== undefined);
// 고른 행이 없으면 버튼을 흐리게(비활성) 해서, 눌러도 아무 일 없는 상태를 미리 보여 줘요.
function refreshButtons(api) {
const picked = selectedRows(api);
const waiting = picked.filter((row) => row.status === '접수').length;
const set = (id, disabled) => {
const el = document.getElementById(id);
if (el instanceof HTMLButtonElement)
el.disabled = disabled;
};
set('approve', waiting === 0);
set('reject', waiting === 0);
set('removeSelected', picked.length === 0);
}
export function setup(api, log) {
say = log;
refreshButtons(api);
const offs = [
api.on('selectionChanged', (e) => {
const waiting = selectedRows(api).filter((row) => row.status === '접수').length;
log({
ko: `${e.selectedKeys.length}행 선택 (그중 접수 ${waiting}행)`,
en: `${e.selectedKeys.length} rows selected (${waiting} of them waiting)`,
});
refreshButtons(api);
}),
api.on('rowsChanged', () => refreshButtons(api)),
];
return () => offs.forEach((off) => off());
}
// 고른 행에 한꺼번에 일을 시키는 툴바예요. '접수' 상태인 행만 승인·반려할 수 있고, 나머지는 건드리지 않아요.
function decide(api, status) {
const picked = selectedRows(api);
const targets = picked.filter((row) => row.status === '접수').map((row) => ({ ...row, status }));
if (picked.length === 0)
return say({ ko: '먼저 행을 골라 주세요', en: 'Select rows first' });
if (targets.length === 0)
return say({
ko: '고른 행 중에 접수 상태인 행이 없어서 바꾼 게 없어요',
en: 'None of the selected rows is waiting, so nothing changed',
});
api.updateRows(targets);
say({
ko: `${targets.length}행을 '${status}'${euroRo(status)} 바꿨어요 (건너뛴 행 ${picked.length - targets.length})`,
en: `${targets.length} rows changed to '${status}' (${picked.length - targets.length} skipped)`,
});
}
export const actions = {
approve: (api) => decide(api, '승인'),
reject: (api) => decide(api, '반려'),
removeSelected: (api) => {
const keys = api.getSelectedKeys();
if (keys.length === 0)
return say({ ko: '먼저 행을 골라 주세요', en: 'Select rows first' });
api.removeRows(keys);
say({ ko: `${keys.length}행을 지웠어요`, en: `${keys.length} rows deleted` });
},
selectWaiting: (api) => api.setSelectedKeys(api
.getRows()
.filter((row) => row.status === '접수')
.map((row) => row.id)),
reset: (api) => {
api.setRows(initial());
api.clearSelection();
say({ ko: '처음 목록으로 되돌렸어요', en: 'Back to the first list' });
},
};<!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">
<button type="button" id="selectWaiting">접수 행 모두 선택</button>
<button type="button" id="approve">승인</button>
<button type="button" id="reject">반려</button>
<button type="button" id="removeSelected">선택 삭제</button>
<button type="button" id="reset">처음 목록으로</button>
</div>
<div id="grid" style="height: 380px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'바다유통',
'해든전자',
];
const statuses = ['접수', '승인', '접수', '반려', '접수', '접수', '승인', '접수'];
const initial = () => customers.map((customer, i) => ({
id: i + 1,
customer,
total: 430000 + ((i * 613000) % 2900000),
status: statuses[i],
}));
const options = {
columns: [
{ id: 'customer', title: '고객사', width: 150 },
{
id: 'total',
title: '주문 금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{ id: 'status', title: '상태', width: 90 },
],
rows: initial(),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word) => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0)
return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const euroRo = (word) => (batchim(word) && batchim(word) !== 8 ? '으로' : '로');
let say = () => { };
const selectedRows = (api) => api
.getSelectedKeys()
.map((key) => api.getRowByKey(key))
.filter((row) => row !== undefined);
// 고른 행이 없으면 버튼을 흐리게(비활성) 해서, 눌러도 아무 일 없는 상태를 미리 보여 줘요.
function refreshButtons(api) {
const picked = selectedRows(api);
const waiting = picked.filter((row) => row.status === '접수').length;
const set = (id, disabled) => {
const el = document.getElementById(id);
if (el instanceof HTMLButtonElement)
el.disabled = disabled;
};
set('approve', waiting === 0);
set('reject', waiting === 0);
set('removeSelected', picked.length === 0);
}
function setup(api, log) {
say = log;
refreshButtons(api);
const offs = [
api.on('selectionChanged', (e) => {
const waiting = selectedRows(api).filter((row) => row.status === '접수').length;
log({
ko: `${e.selectedKeys.length}행 선택 (그중 접수 ${waiting}행)`,
en: `${e.selectedKeys.length} rows selected (${waiting} of them waiting)`,
});
refreshButtons(api);
}),
api.on('rowsChanged', () => refreshButtons(api)),
];
return () => offs.forEach((off) => off());
}
// 고른 행에 한꺼번에 일을 시키는 툴바예요. '접수' 상태인 행만 승인·반려할 수 있고, 나머지는 건드리지 않아요.
function decide(api, status) {
const picked = selectedRows(api);
const targets = picked.filter((row) => row.status === '접수').map((row) => ({ ...row, status }));
if (picked.length === 0)
return say({ ko: '먼저 행을 골라 주세요', en: 'Select rows first' });
if (targets.length === 0)
return say({
ko: '고른 행 중에 접수 상태인 행이 없어서 바꾼 게 없어요',
en: 'None of the selected rows is waiting, so nothing changed',
});
api.updateRows(targets);
say({
ko: `${targets.length}행을 '${status}'${euroRo(status)} 바꿨어요 (건너뛴 행 ${picked.length - targets.length})`,
en: `${targets.length} rows changed to '${status}' (${picked.length - targets.length} skipped)`,
});
}
const actions = {
approve: (api) => decide(api, '승인'),
reject: (api) => decide(api, '반려'),
removeSelected: (api) => {
const keys = api.getSelectedKeys();
if (keys.length === 0)
return say({ ko: '먼저 행을 골라 주세요', en: 'Select rows first' });
api.removeRows(keys);
say({ ko: `${keys.length}행을 지웠어요`, en: `${keys.length} rows deleted` });
},
selectWaiting: (api) => api.setSelectedKeys(api
.getRows()
.filter((row) => row.status === '접수')
.map((row) => row.id)),
reset: (api) => {
api.setRows(initial());
api.clearSelection();
say({ ko: '처음 목록으로 되돌렸어요', en: 'Back to the first list' });
},
};
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('selectWaiting').addEventListener('click', () => actions.selectWaiting(api));
document.getElementById('approve').addEventListener('click', () => actions.approve(api));
document.getElementById('reject').addEventListener('click', () => actions.reject(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.selectWaiting(api)}
>접수 행 모두 선택</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.approve(api)}
>승인</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reject(api)}
>반려</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeSelected(api)}
>선택 삭제</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reset(api)}
>처음 목록으로</button>
</div>
<Grid style={{ height: 380 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
total: number;
status: string;
}
const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'바다유통',
'해든전자',
];
const statuses = ['접수', '승인', '접수', '반려', '접수', '접수', '승인', '접수'];
const initial = (): Row[] =>
customers.map((customer, i) => ({
id: i + 1,
customer,
total: 430000 + ((i * 613000) % 2900000),
status: statuses[i] as string,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객사', width: 150 },
{
id: 'total',
title: '주문 금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{ id: 'status', title: '상태', width: 90 },
],
rows: initial(),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0) return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const euroRo = (word: string): string => (batchim(word) && batchim(word) !== 8 ? '으로' : '로');
let say: (message: LogText) => void = () => {};
const selectedRows = (api: GridApi<Row>): Row[] =>
api
.getSelectedKeys()
.map((key) => api.getRowByKey(key))
.filter((row): row is Row => row !== undefined);
// 고른 행이 없으면 버튼을 흐리게(비활성) 해서, 눌러도 아무 일 없는 상태를 미리 보여 줘요.
function refreshButtons(api: GridApi<Row>): void {
const picked = selectedRows(api);
const waiting = picked.filter((row) => row.status === '접수').length;
const set = (id: string, disabled: boolean): void => {
const el = document.getElementById(id);
if (el instanceof HTMLButtonElement) el.disabled = disabled;
};
set('approve', waiting === 0);
set('reject', waiting === 0);
set('removeSelected', picked.length === 0);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
refreshButtons(api);
const offs = [
api.on('selectionChanged', (e) => {
const waiting = selectedRows(api).filter((row) => row.status === '접수').length;
log({
ko: `${e.selectedKeys.length}행 선택 (그중 접수 ${waiting}행)`,
en: `${e.selectedKeys.length} rows selected (${waiting} of them waiting)`,
});
refreshButtons(api);
}),
api.on('rowsChanged', () => refreshButtons(api)),
];
return () => offs.forEach((off) => off());
}
// 고른 행에 한꺼번에 일을 시키는 툴바예요. '접수' 상태인 행만 승인·반려할 수 있고, 나머지는 건드리지 않아요.
function decide(api: GridApi<Row>, status: string): void {
const picked = selectedRows(api);
const targets = picked.filter((row) => row.status === '접수').map((row) => ({ ...row, status }));
if (picked.length === 0) return say({ ko: '먼저 행을 골라 주세요', en: 'Select rows first' });
if (targets.length === 0)
return say({
ko: '고른 행 중에 접수 상태인 행이 없어서 바꾼 게 없어요',
en: 'None of the selected rows is waiting, so nothing changed',
});
api.updateRows(targets);
say({
ko: `${targets.length}행을 '${status}'${euroRo(status)} 바꿨어요 (건너뛴 행 ${picked.length - targets.length})`,
en: `${targets.length} rows changed to '${status}' (${picked.length - targets.length} skipped)`,
});
}
export const actions = {
approve: (api: GridApi<Row>) => decide(api, '승인'),
reject: (api: GridApi<Row>) => decide(api, '반려'),
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (keys.length === 0) return say({ ko: '먼저 행을 골라 주세요', en: 'Select rows first' });
api.removeRows(keys);
say({ ko: `${keys.length}행을 지웠어요`, en: `${keys.length} rows deleted` });
},
selectWaiting: (api: GridApi<Row>) =>
api.setSelectedKeys(
api
.getRows()
.filter((row) => row.status === '접수')
.map((row) => row.id),
),
reset: (api: GridApi<Row>) => {
api.setRows(initial());
api.clearSelection();
say({ ko: '처음 목록으로 되돌렸어요', en: 'Back to the first list' });
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.selectWaiting(api)"
>접수 행 모두 선택</button>
<button type="button" :disabled="!api" @click="api && actions.approve(api)">승인</button>
<button type="button" :disabled="!api" @click="api && actions.reject(api)">반려</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeSelected(api)"
>선택 삭제</button>
<button type="button" :disabled="!api" @click="api && actions.reset(api)">처음 목록으로</button>
</div>
<Grid style="height: 380px" :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;
customer: string;
total: number;
status: string;
}
const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'바다유통',
'해든전자',
];
const statuses = ['접수', '승인', '접수', '반려', '접수', '접수', '승인', '접수'];
const initial = (): Row[] =>
customers.map((customer, i) => ({
id: i + 1,
customer,
total: 430000 + ((i * 613000) % 2900000),
status: statuses[i] as string,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객사', width: 150 },
{
id: 'total',
title: '주문 금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{ id: 'status', title: '상태', width: 90 },
],
rows: initial(),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0) return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const euroRo = (word: string): string => (batchim(word) && batchim(word) !== 8 ? '으로' : '로');
let say: (message: LogText) => void = () => {};
const selectedRows = (api: GridApi<Row>): Row[] =>
api
.getSelectedKeys()
.map((key) => api.getRowByKey(key))
.filter((row): row is Row => row !== undefined);
// 고른 행이 없으면 버튼을 흐리게(비활성) 해서, 눌러도 아무 일 없는 상태를 미리 보여 줘요.
function refreshButtons(api: GridApi<Row>): void {
const picked = selectedRows(api);
const waiting = picked.filter((row) => row.status === '접수').length;
const set = (id: string, disabled: boolean): void => {
const el = document.getElementById(id);
if (el instanceof HTMLButtonElement) el.disabled = disabled;
};
set('approve', waiting === 0);
set('reject', waiting === 0);
set('removeSelected', picked.length === 0);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
refreshButtons(api);
const offs = [
api.on('selectionChanged', (e) => {
const waiting = selectedRows(api).filter((row) => row.status === '접수').length;
log({
ko: `${e.selectedKeys.length}행 선택 (그중 접수 ${waiting}행)`,
en: `${e.selectedKeys.length} rows selected (${waiting} of them waiting)`,
});
refreshButtons(api);
}),
api.on('rowsChanged', () => refreshButtons(api)),
];
return () => offs.forEach((off) => off());
}
// 고른 행에 한꺼번에 일을 시키는 툴바예요. '접수' 상태인 행만 승인·반려할 수 있고, 나머지는 건드리지 않아요.
function decide(api: GridApi<Row>, status: string): void {
const picked = selectedRows(api);
const targets = picked.filter((row) => row.status === '접수').map((row) => ({ ...row, status }));
if (picked.length === 0) return say({ ko: '먼저 행을 골라 주세요', en: 'Select rows first' });
if (targets.length === 0)
return say({
ko: '고른 행 중에 접수 상태인 행이 없어서 바꾼 게 없어요',
en: 'None of the selected rows is waiting, so nothing changed',
});
api.updateRows(targets);
say({
ko: `${targets.length}행을 '${status}'${euroRo(status)} 바꿨어요 (건너뛴 행 ${picked.length - targets.length})`,
en: `${targets.length} rows changed to '${status}' (${picked.length - targets.length} skipped)`,
});
}
export const actions = {
approve: (api: GridApi<Row>) => decide(api, '승인'),
reject: (api: GridApi<Row>) => decide(api, '반려'),
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (keys.length === 0) return say({ ko: '먼저 행을 골라 주세요', en: 'Select rows first' });
api.removeRows(keys);
say({ ko: `${keys.length}행을 지웠어요`, en: `${keys.length} rows deleted` });
},
selectWaiting: (api: GridApi<Row>) =>
api.setSelectedKeys(
api
.getRows()
.filter((row) => row.status === '접수')
.map((row) => row.id),
),
reset: (api: GridApi<Row>) => {
api.setRows(initial());
api.clearSelection();
say({ ko: '처음 목록으로 되돌렸어요', en: 'Back to the first list' });
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.selectWaiting(api)"
>접수 행 모두 선택</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.approve(api)"
>승인</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reject(api)"
>반려</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeSelected(api)"
>선택 삭제</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reset(api)"
>처음 목록으로</button>
</div>
<mx-grid style="height: 380px" [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;
customer: string;
total: number;
status: string;
}
const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'바다유통',
'해든전자',
];
const statuses = ['접수', '승인', '접수', '반려', '접수', '접수', '승인', '접수'];
const initial = (): Row[] =>
customers.map((customer, i) => ({
id: i + 1,
customer,
total: 430000 + ((i * 613000) % 2900000),
status: statuses[i] as string,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객사', width: 150 },
{
id: 'total',
title: '주문 금액(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{ id: 'status', title: '상태', width: 90 },
],
rows: initial(),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
// 데이터 값 뒤에 붙는 조사는 마지막 글자의 받침에 맞춰 골라요(숫자는 읽는 소리 기준).
const batchim = (word: string): number => {
const ch = word.trim().slice(-1);
const digit = '0123456789'.indexOf(ch);
if (digit >= 0) return [21, 8, 0, 16, 0, 0, 1, 8, 8, 0][digit] ?? 0; // 영 일 이 삼 사 오 육 칠 팔 구
const code = ch.charCodeAt(0) - 0xac00;
return code >= 0 && code <= 11171 ? code % 28 : 0;
};
const euroRo = (word: string): string => (batchim(word) && batchim(word) !== 8 ? '으로' : '로');
let say: (message: LogText) => void = () => {};
const selectedRows = (api: GridApi<Row>): Row[] =>
api
.getSelectedKeys()
.map((key) => api.getRowByKey(key))
.filter((row): row is Row => row !== undefined);
// 고른 행이 없으면 버튼을 흐리게(비활성) 해서, 눌러도 아무 일 없는 상태를 미리 보여 줘요.
function refreshButtons(api: GridApi<Row>): void {
const picked = selectedRows(api);
const waiting = picked.filter((row) => row.status === '접수').length;
const set = (id: string, disabled: boolean): void => {
const el = document.getElementById(id);
if (el instanceof HTMLButtonElement) el.disabled = disabled;
};
set('approve', waiting === 0);
set('reject', waiting === 0);
set('removeSelected', picked.length === 0);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
refreshButtons(api);
const offs = [
api.on('selectionChanged', (e) => {
const waiting = selectedRows(api).filter((row) => row.status === '접수').length;
log({
ko: `${e.selectedKeys.length}행 선택 (그중 접수 ${waiting}행)`,
en: `${e.selectedKeys.length} rows selected (${waiting} of them waiting)`,
});
refreshButtons(api);
}),
api.on('rowsChanged', () => refreshButtons(api)),
];
return () => offs.forEach((off) => off());
}
// 고른 행에 한꺼번에 일을 시키는 툴바예요. '접수' 상태인 행만 승인·반려할 수 있고, 나머지는 건드리지 않아요.
function decide(api: GridApi<Row>, status: string): void {
const picked = selectedRows(api);
const targets = picked.filter((row) => row.status === '접수').map((row) => ({ ...row, status }));
if (picked.length === 0) return say({ ko: '먼저 행을 골라 주세요', en: 'Select rows first' });
if (targets.length === 0)
return say({
ko: '고른 행 중에 접수 상태인 행이 없어서 바꾼 게 없어요',
en: 'None of the selected rows is waiting, so nothing changed',
});
api.updateRows(targets);
say({
ko: `${targets.length}행을 '${status}'${euroRo(status)} 바꿨어요 (건너뛴 행 ${picked.length - targets.length})`,
en: `${targets.length} rows changed to '${status}' (${picked.length - targets.length} skipped)`,
});
}
export const actions = {
approve: (api: GridApi<Row>) => decide(api, '승인'),
reject: (api: GridApi<Row>) => decide(api, '반려'),
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (keys.length === 0) return say({ ko: '먼저 행을 골라 주세요', en: 'Select rows first' });
api.removeRows(keys);
say({ ko: `${keys.length}행을 지웠어요`, en: `${keys.length} rows deleted` });
},
selectWaiting: (api: GridApi<Row>) =>
api.setSelectedKeys(
api
.getRows()
.filter((row) => row.status === '접수')
.map((row) => row.id),
),
reset: (api: GridApi<Row>) => {
api.setRows(initial());
api.clearSelection();
say({ ko: '처음 목록으로 되돌렸어요', en: 'Back to the first list' });
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="selectWaiting">Select received rows</button>
<button type="button" id="approve">Approve</button>
<button type="button" id="reject">Reject</button>
<button type="button" id="removeSelected">Delete selected</button>
<button type="button" id="reset">Reset list</button>
</div>
<div id="grid" style="height: 380px"></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('selectWaiting').addEventListener('click', () => actions.selectWaiting(api));
document.getElementById('approve').addEventListener('click', () => actions.approve(api));
document.getElementById('reject').addEventListener('click', () => actions.reject(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harbor & Co.',
'Dawn Farms',
'Mode Fashion',
'Seaside Supply',
'Sunrise Electronics',
];
const statuses = [
'Pending',
'Approved',
'Pending',
'Rejected',
'Pending',
'Pending',
'Approved',
'Pending',
];
const initial = () => customers.map((customer, i) => ({
id: i + 1,
customer,
total: 430 + ((i * 613) % 2900),
status: statuses[i],
}));
export const options = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{
id: 'total',
title: 'Order amount ($)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{ id: 'status', title: 'Status', width: 100 },
],
rows: initial(),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
let say = () => { };
const selectedRows = (api) => api
.getSelectedKeys()
.map((key) => api.getRowByKey(key))
.filter((row) => row !== undefined);
// With no rows selected, dim (disable) the buttons so the user sees up front that pressing them does nothing.
function refreshButtons(api) {
const picked = selectedRows(api);
const waiting = picked.filter((row) => row.status === 'Pending').length;
const set = (id, disabled) => {
const el = document.getElementById(id);
if (el instanceof HTMLButtonElement)
el.disabled = disabled;
};
set('approve', waiting === 0);
set('reject', waiting === 0);
set('removeSelected', picked.length === 0);
}
export function setup(api, log) {
say = log;
refreshButtons(api);
const offs = [
api.on('selectionChanged', (e) => {
const waiting = selectedRows(api).filter((row) => row.status === 'Pending').length;
log(`${e.selectedKeys.length} rows selected (${waiting} of them pending)`);
refreshButtons(api);
}),
api.on('rowsChanged', () => refreshButtons(api)),
];
return () => offs.forEach((off) => off());
}
// A toolbar that acts on all selected rows at once. Only 'Pending' rows can be approved or rejected; the rest are left alone.
function decide(api, status) {
const picked = selectedRows(api);
const targets = picked
.filter((row) => row.status === 'Pending')
.map((row) => ({ ...row, status }));
if (picked.length === 0)
return say('Select rows first');
if (targets.length === 0)
return say('None of the selected rows is pending, so nothing changed');
api.updateRows(targets);
say(`${targets.length} rows changed to '${status}' (${picked.length - targets.length} skipped)`);
}
export const actions = {
approve: (api) => decide(api, 'Approved'),
reject: (api) => decide(api, 'Rejected'),
removeSelected: (api) => {
const keys = api.getSelectedKeys();
if (keys.length === 0)
return say('Select rows first');
api.removeRows(keys);
say(`${keys.length} rows deleted`);
},
selectWaiting: (api) => api.setSelectedKeys(api
.getRows()
.filter((row) => row.status === 'Pending')
.map((row) => row.id)),
reset: (api) => {
api.setRows(initial());
api.clearSelection();
say('Back to the first list');
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Approve, reject or delete the selected rows at once</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="selectWaiting">Select received rows</button>
<button type="button" id="approve">Approve</button>
<button type="button" id="reject">Reject</button>
<button type="button" id="removeSelected">Delete selected</button>
<button type="button" id="reset">Reset list</button>
</div>
<div id="grid" style="height: 380px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harbor & Co.',
'Dawn Farms',
'Mode Fashion',
'Seaside Supply',
'Sunrise Electronics',
];
const statuses = [
'Pending',
'Approved',
'Pending',
'Rejected',
'Pending',
'Pending',
'Approved',
'Pending',
];
const initial = () => customers.map((customer, i) => ({
id: i + 1,
customer,
total: 430 + ((i * 613) % 2900),
status: statuses[i],
}));
const options = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{
id: 'total',
title: 'Order amount ($)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{ id: 'status', title: 'Status', width: 100 },
],
rows: initial(),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
let say = () => { };
const selectedRows = (api) => api
.getSelectedKeys()
.map((key) => api.getRowByKey(key))
.filter((row) => row !== undefined);
// With no rows selected, dim (disable) the buttons so the user sees up front that pressing them does nothing.
function refreshButtons(api) {
const picked = selectedRows(api);
const waiting = picked.filter((row) => row.status === 'Pending').length;
const set = (id, disabled) => {
const el = document.getElementById(id);
if (el instanceof HTMLButtonElement)
el.disabled = disabled;
};
set('approve', waiting === 0);
set('reject', waiting === 0);
set('removeSelected', picked.length === 0);
}
function setup(api, log) {
say = log;
refreshButtons(api);
const offs = [
api.on('selectionChanged', (e) => {
const waiting = selectedRows(api).filter((row) => row.status === 'Pending').length;
log(`${e.selectedKeys.length} rows selected (${waiting} of them pending)`);
refreshButtons(api);
}),
api.on('rowsChanged', () => refreshButtons(api)),
];
return () => offs.forEach((off) => off());
}
// A toolbar that acts on all selected rows at once. Only 'Pending' rows can be approved or rejected; the rest are left alone.
function decide(api, status) {
const picked = selectedRows(api);
const targets = picked
.filter((row) => row.status === 'Pending')
.map((row) => ({ ...row, status }));
if (picked.length === 0)
return say('Select rows first');
if (targets.length === 0)
return say('None of the selected rows is pending, so nothing changed');
api.updateRows(targets);
say(`${targets.length} rows changed to '${status}' (${picked.length - targets.length} skipped)`);
}
const actions = {
approve: (api) => decide(api, 'Approved'),
reject: (api) => decide(api, 'Rejected'),
removeSelected: (api) => {
const keys = api.getSelectedKeys();
if (keys.length === 0)
return say('Select rows first');
api.removeRows(keys);
say(`${keys.length} rows deleted`);
},
selectWaiting: (api) => api.setSelectedKeys(api
.getRows()
.filter((row) => row.status === 'Pending')
.map((row) => row.id)),
reset: (api) => {
api.setRows(initial());
api.clearSelection();
say('Back to the first list');
},
};
options.ariaLabel = "Approve, reject or delete the selected rows at once";
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('selectWaiting').addEventListener('click', () => actions.selectWaiting(api));
document.getElementById('approve').addEventListener('click', () => actions.approve(api));
document.getElementById('reject').addEventListener('click', () => actions.reject(api));
document.getElementById('removeSelected').addEventListener('click', () => actions.removeSelected(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.selectWaiting(api)}
>Select received rows</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.approve(api)}
>Approve</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reject(api)}
>Reject</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.removeSelected(api)}
>Delete selected</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reset(api)}
>Reset list</button>
</div>
<Grid style={{ height: 380 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
customer: string;
total: number;
status: string;
}
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harbor & Co.',
'Dawn Farms',
'Mode Fashion',
'Seaside Supply',
'Sunrise Electronics',
];
const statuses = [
'Pending',
'Approved',
'Pending',
'Rejected',
'Pending',
'Pending',
'Approved',
'Pending',
];
const initial = (): Row[] =>
customers.map((customer, i) => ({
id: i + 1,
customer,
total: 430 + ((i * 613) % 2900),
status: statuses[i] as string,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{
id: 'total',
title: 'Order amount ($)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{ id: 'status', title: 'Status', width: 100 },
],
rows: initial(),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
let say: (message: LogText) => void = () => {};
const selectedRows = (api: GridApi<Row>): Row[] =>
api
.getSelectedKeys()
.map((key) => api.getRowByKey(key))
.filter((row): row is Row => row !== undefined);
// With no rows selected, dim (disable) the buttons so the user sees up front that pressing them does nothing.
function refreshButtons(api: GridApi<Row>): void {
const picked = selectedRows(api);
const waiting = picked.filter((row) => row.status === 'Pending').length;
const set = (id: string, disabled: boolean): void => {
const el = document.getElementById(id);
if (el instanceof HTMLButtonElement) el.disabled = disabled;
};
set('approve', waiting === 0);
set('reject', waiting === 0);
set('removeSelected', picked.length === 0);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
refreshButtons(api);
const offs = [
api.on('selectionChanged', (e) => {
const waiting = selectedRows(api).filter((row) => row.status === 'Pending').length;
log(`${e.selectedKeys.length} rows selected (${waiting} of them pending)`);
refreshButtons(api);
}),
api.on('rowsChanged', () => refreshButtons(api)),
];
return () => offs.forEach((off) => off());
}
// A toolbar that acts on all selected rows at once. Only 'Pending' rows can be approved or rejected; the rest are left alone.
function decide(api: GridApi<Row>, status: string): void {
const picked = selectedRows(api);
const targets = picked
.filter((row) => row.status === 'Pending')
.map((row) => ({ ...row, status }));
if (picked.length === 0) return say('Select rows first');
if (targets.length === 0) return say('None of the selected rows is pending, so nothing changed');
api.updateRows(targets);
say(`${targets.length} rows changed to '${status}' (${picked.length - targets.length} skipped)`);
}
export const actions = {
approve: (api: GridApi<Row>) => decide(api, 'Approved'),
reject: (api: GridApi<Row>) => decide(api, 'Rejected'),
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (keys.length === 0) return say('Select rows first');
api.removeRows(keys);
say(`${keys.length} rows deleted`);
},
selectWaiting: (api: GridApi<Row>) =>
api.setSelectedKeys(
api
.getRows()
.filter((row) => row.status === 'Pending')
.map((row) => row.id),
),
reset: (api: GridApi<Row>) => {
api.setRows(initial());
api.clearSelection();
say('Back to the first list');
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button
type="button"
:disabled="!api"
@click="api && actions.selectWaiting(api)"
>Select received rows</button>
<button type="button" :disabled="!api" @click="api && actions.approve(api)">Approve</button>
<button type="button" :disabled="!api" @click="api && actions.reject(api)">Reject</button>
<button
type="button"
:disabled="!api"
@click="api && actions.removeSelected(api)"
>Delete selected</button>
<button type="button" :disabled="!api" @click="api && actions.reset(api)">Reset list</button>
</div>
<Grid style="height: 380px" :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;
customer: string;
total: number;
status: string;
}
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harbor & Co.',
'Dawn Farms',
'Mode Fashion',
'Seaside Supply',
'Sunrise Electronics',
];
const statuses = [
'Pending',
'Approved',
'Pending',
'Rejected',
'Pending',
'Pending',
'Approved',
'Pending',
];
const initial = (): Row[] =>
customers.map((customer, i) => ({
id: i + 1,
customer,
total: 430 + ((i * 613) % 2900),
status: statuses[i] as string,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{
id: 'total',
title: 'Order amount ($)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{ id: 'status', title: 'Status', width: 100 },
],
rows: initial(),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
let say: (message: LogText) => void = () => {};
const selectedRows = (api: GridApi<Row>): Row[] =>
api
.getSelectedKeys()
.map((key) => api.getRowByKey(key))
.filter((row): row is Row => row !== undefined);
// With no rows selected, dim (disable) the buttons so the user sees up front that pressing them does nothing.
function refreshButtons(api: GridApi<Row>): void {
const picked = selectedRows(api);
const waiting = picked.filter((row) => row.status === 'Pending').length;
const set = (id: string, disabled: boolean): void => {
const el = document.getElementById(id);
if (el instanceof HTMLButtonElement) el.disabled = disabled;
};
set('approve', waiting === 0);
set('reject', waiting === 0);
set('removeSelected', picked.length === 0);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
refreshButtons(api);
const offs = [
api.on('selectionChanged', (e) => {
const waiting = selectedRows(api).filter((row) => row.status === 'Pending').length;
log(`${e.selectedKeys.length} rows selected (${waiting} of them pending)`);
refreshButtons(api);
}),
api.on('rowsChanged', () => refreshButtons(api)),
];
return () => offs.forEach((off) => off());
}
// A toolbar that acts on all selected rows at once. Only 'Pending' rows can be approved or rejected; the rest are left alone.
function decide(api: GridApi<Row>, status: string): void {
const picked = selectedRows(api);
const targets = picked
.filter((row) => row.status === 'Pending')
.map((row) => ({ ...row, status }));
if (picked.length === 0) return say('Select rows first');
if (targets.length === 0) return say('None of the selected rows is pending, so nothing changed');
api.updateRows(targets);
say(`${targets.length} rows changed to '${status}' (${picked.length - targets.length} skipped)`);
}
export const actions = {
approve: (api: GridApi<Row>) => decide(api, 'Approved'),
reject: (api: GridApi<Row>) => decide(api, 'Rejected'),
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (keys.length === 0) return say('Select rows first');
api.removeRows(keys);
say(`${keys.length} rows deleted`);
},
selectWaiting: (api: GridApi<Row>) =>
api.setSelectedKeys(
api
.getRows()
.filter((row) => row.status === 'Pending')
.map((row) => row.id),
),
reset: (api: GridApi<Row>) => {
api.setRows(initial());
api.clearSelection();
say('Back to the first list');
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.selectWaiting(api)"
>Select received rows</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.approve(api)"
>Approve</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reject(api)"
>Reject</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.removeSelected(api)"
>Delete selected</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reset(api)"
>Reset list</button>
</div>
<mx-grid style="height: 380px" [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;
customer: string;
total: number;
status: string;
}
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harbor & Co.',
'Dawn Farms',
'Mode Fashion',
'Seaside Supply',
'Sunrise Electronics',
];
const statuses = [
'Pending',
'Approved',
'Pending',
'Rejected',
'Pending',
'Pending',
'Approved',
'Pending',
];
const initial = (): Row[] =>
customers.map((customer, i) => ({
id: i + 1,
customer,
total: 430 + ((i * 613) % 2900),
status: statuses[i] as string,
}));
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{
id: 'total',
title: 'Order amount ($)',
kind: 'number',
width: 150,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{ id: 'status', title: 'Status', width: 100 },
],
rows: initial(),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
let say: (message: LogText) => void = () => {};
const selectedRows = (api: GridApi<Row>): Row[] =>
api
.getSelectedKeys()
.map((key) => api.getRowByKey(key))
.filter((row): row is Row => row !== undefined);
// With no rows selected, dim (disable) the buttons so the user sees up front that pressing them does nothing.
function refreshButtons(api: GridApi<Row>): void {
const picked = selectedRows(api);
const waiting = picked.filter((row) => row.status === 'Pending').length;
const set = (id: string, disabled: boolean): void => {
const el = document.getElementById(id);
if (el instanceof HTMLButtonElement) el.disabled = disabled;
};
set('approve', waiting === 0);
set('reject', waiting === 0);
set('removeSelected', picked.length === 0);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
refreshButtons(api);
const offs = [
api.on('selectionChanged', (e) => {
const waiting = selectedRows(api).filter((row) => row.status === 'Pending').length;
log(`${e.selectedKeys.length} rows selected (${waiting} of them pending)`);
refreshButtons(api);
}),
api.on('rowsChanged', () => refreshButtons(api)),
];
return () => offs.forEach((off) => off());
}
// A toolbar that acts on all selected rows at once. Only 'Pending' rows can be approved or rejected; the rest are left alone.
function decide(api: GridApi<Row>, status: string): void {
const picked = selectedRows(api);
const targets = picked
.filter((row) => row.status === 'Pending')
.map((row) => ({ ...row, status }));
if (picked.length === 0) return say('Select rows first');
if (targets.length === 0) return say('None of the selected rows is pending, so nothing changed');
api.updateRows(targets);
say(`${targets.length} rows changed to '${status}' (${picked.length - targets.length} skipped)`);
}
export const actions = {
approve: (api: GridApi<Row>) => decide(api, 'Approved'),
reject: (api: GridApi<Row>) => decide(api, 'Rejected'),
removeSelected: (api: GridApi<Row>) => {
const keys = api.getSelectedKeys();
if (keys.length === 0) return say('Select rows first');
api.removeRows(keys);
say(`${keys.length} rows deleted`);
},
selectWaiting: (api: GridApi<Row>) =>
api.setSelectedKeys(
api
.getRows()
.filter((row) => row.status === 'Pending')
.map((row) => row.id),
),
reset: (api: GridApi<Row>) => {
api.setRows(initial());
api.clearSelection();
say('Back to the first list');
},
};