조건에 맞는 행만 고르게 하기Let users select only matching rows
결제가 끝난 행처럼 고르면 안 되는 행은 선택이 바뀔 때 걸러 내서 다시 정해요. 잠긴 행은 흐리게 보여 주고, 고를 수 없는 이유는 기록 창에 알려 줘요.Rows that must not be selected, such as paid ones, are filtered out whenever the selection changes. Locked rows are dimmed and the log says why they were 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="selectAll">전체 선택</button>
<button type="button" id="clear">선택 지우기</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('selectAll').addEventListener('click', () => actions.selectAll(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'바다유통',
'해든전자',
];
const statuses = ['결제 완료', '대기', '연체'];
// 결제가 끝난 행은 잠가서 고를 수 없게 해요. 잠긴 행은 rowClass로 흐리게 보여 줘요.
const isLocked = (row) => row.status === '결제 완료';
export const options = {
columns: [
{ id: 'customer', title: '고객사', width: 150 },
{ id: 'status', title: '상태', width: 110 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: customers.map((customer, i) => ({
id: i + 1,
customer,
status: statuses[(i * 2) % 3],
amount: 430000 + ((i * 613000) % 2900000),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
rowClass: (row) => (isLocked(row) ? 'scr-locked' : undefined),
};
// '고를 수 없는 행' 옵션은 따로 없어서, 선택이 바뀐 뒤에 잠긴 행을 빼서 다시 정해요.
// 이 안에서 setSelectedKeys를 또 부르면 selectionChanged가 다시 오니까, 스스로 부른 호출은 건너뛰어요.
let fixing = false;
let previous = [];
let expected = null;
export function setup(api, log) {
const style = document.createElement('style');
style.textContent = '.scr-locked { opacity: 0.55; }';
document.head.append(style);
fixing = false;
previous = [];
const lockedKeys = api
.getRows()
.filter(isLocked)
.map((row) => row.id);
const selectable = api.getRows().filter((row) => !isLocked(row));
const off = api.on('selectionChanged', ({ selectedKeys }) => {
if (fixing)
return;
// 우리가 다시 정한 선택이 되돌아와서 오는 이벤트는 한 번 더 기록하지 않아요.
if (expected !== null && JSON.stringify(selectedKeys) === expected) {
expected = null;
return;
}
expected = null;
const allowed = selectedKeys.filter((key) => {
const row = api.getRowByKey(key);
return row !== undefined && !isLocked(row);
});
// 머리글 체크박스는 '모든 행'을 켜고 끄기 때문에, 고를 수 있는 행이 이미 모두 골라진 상태에서 누르면
// 잠긴 행들이 한꺼번에 더해져서 와요. 그때는 '전체 해제'를 누른 것으로 보고 모두 풀어 줘요.
const addedLocked = selectedKeys.filter((key) => lockedKeys.includes(key) && !previous.includes(key));
const wasAll = selectable.length > 0 && selectable.every((row) => previous.includes(row.id));
const clearing = wasAll && lockedKeys.length > 1 && addedLocked.length === lockedKeys.length;
const next = clearing ? [] : allowed;
previous = next;
if (!clearing && allowed.length === selectedKeys.length)
return log({ ko: `${allowed.length}행 선택`, en: `${allowed.length} rows selected` });
fixing = true;
expected = JSON.stringify(next);
try {
api.setSelectedKeys(next);
}
finally {
fixing = false;
}
log({
ko: clearing
? '전체 해제: 선택을 모두 풀었어요'
: `결제 완료 행 ${selectedKeys.length - allowed.length}개는 고를 수 없어서 뺐어요 → ${allowed.length}행 선택`,
en: clearing
? 'Clear all: selection removed'
: `${selectedKeys.length - allowed.length} paid rows cannot be selected and were left out → ${allowed.length} rows selected`,
});
});
return () => {
off();
style.remove();
};
}
export const actions = {
selectAll: (api) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
clear: (api) => api.clearSelection(),
};<!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="selectAll">전체 선택</button>
<button type="button" id="clear">선택 지우기</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 = ['결제 완료', '대기', '연체'];
// 결제가 끝난 행은 잠가서 고를 수 없게 해요. 잠긴 행은 rowClass로 흐리게 보여 줘요.
const isLocked = (row) => row.status === '결제 완료';
const options = {
columns: [
{ id: 'customer', title: '고객사', width: 150 },
{ id: 'status', title: '상태', width: 110 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: customers.map((customer, i) => ({
id: i + 1,
customer,
status: statuses[(i * 2) % 3],
amount: 430000 + ((i * 613000) % 2900000),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
rowClass: (row) => (isLocked(row) ? 'scr-locked' : undefined),
};
// '고를 수 없는 행' 옵션은 따로 없어서, 선택이 바뀐 뒤에 잠긴 행을 빼서 다시 정해요.
// 이 안에서 setSelectedKeys를 또 부르면 selectionChanged가 다시 오니까, 스스로 부른 호출은 건너뛰어요.
let fixing = false;
let previous = [];
let expected = null;
function setup(api, log) {
const style = document.createElement('style');
style.textContent = '.scr-locked { opacity: 0.55; }';
document.head.append(style);
fixing = false;
previous = [];
const lockedKeys = api
.getRows()
.filter(isLocked)
.map((row) => row.id);
const selectable = api.getRows().filter((row) => !isLocked(row));
const off = api.on('selectionChanged', ({ selectedKeys }) => {
if (fixing)
return;
// 우리가 다시 정한 선택이 되돌아와서 오는 이벤트는 한 번 더 기록하지 않아요.
if (expected !== null && JSON.stringify(selectedKeys) === expected) {
expected = null;
return;
}
expected = null;
const allowed = selectedKeys.filter((key) => {
const row = api.getRowByKey(key);
return row !== undefined && !isLocked(row);
});
// 머리글 체크박스는 '모든 행'을 켜고 끄기 때문에, 고를 수 있는 행이 이미 모두 골라진 상태에서 누르면
// 잠긴 행들이 한꺼번에 더해져서 와요. 그때는 '전체 해제'를 누른 것으로 보고 모두 풀어 줘요.
const addedLocked = selectedKeys.filter((key) => lockedKeys.includes(key) && !previous.includes(key));
const wasAll = selectable.length > 0 && selectable.every((row) => previous.includes(row.id));
const clearing = wasAll && lockedKeys.length > 1 && addedLocked.length === lockedKeys.length;
const next = clearing ? [] : allowed;
previous = next;
if (!clearing && allowed.length === selectedKeys.length)
return log({ ko: `${allowed.length}행 선택`, en: `${allowed.length} rows selected` });
fixing = true;
expected = JSON.stringify(next);
try {
api.setSelectedKeys(next);
}
finally {
fixing = false;
}
log({
ko: clearing
? '전체 해제: 선택을 모두 풀었어요'
: `결제 완료 행 ${selectedKeys.length - allowed.length}개는 고를 수 없어서 뺐어요 → ${allowed.length}행 선택`,
en: clearing
? 'Clear all: selection removed'
: `${selectedKeys.length - allowed.length} paid rows cannot be selected and were left out → ${allowed.length} rows selected`,
});
});
return () => {
off();
style.remove();
};
}
const actions = {
selectAll: (api) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
clear: (api) => api.clearSelection(),
};
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('selectAll').addEventListener('click', () => actions.selectAll(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.selectAll(api)}
>전체 선택</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(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;
status: string;
amount: number;
}
const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'바다유통',
'해든전자',
];
const statuses = ['결제 완료', '대기', '연체'];
// 결제가 끝난 행은 잠가서 고를 수 없게 해요. 잠긴 행은 rowClass로 흐리게 보여 줘요.
const isLocked = (row: Row): boolean => row.status === '결제 완료';
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객사', width: 150 },
{ id: 'status', title: '상태', width: 110 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: customers.map((customer, i) => ({
id: i + 1,
customer,
status: statuses[(i * 2) % 3] as string,
amount: 430000 + ((i * 613000) % 2900000),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
rowClass: (row) => (isLocked(row) ? 'scr-locked' : undefined),
};
// '고를 수 없는 행' 옵션은 따로 없어서, 선택이 바뀐 뒤에 잠긴 행을 빼서 다시 정해요.
// 이 안에서 setSelectedKeys를 또 부르면 selectionChanged가 다시 오니까, 스스로 부른 호출은 건너뛰어요.
let fixing = false;
let previous: (string | number)[] = [];
let expected: string | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const style = document.createElement('style');
style.textContent = '.scr-locked { opacity: 0.55; }';
document.head.append(style);
fixing = false;
previous = [];
const lockedKeys: (string | number)[] = api
.getRows()
.filter(isLocked)
.map((row) => row.id);
const selectable = api.getRows().filter((row) => !isLocked(row));
const off = api.on('selectionChanged', ({ selectedKeys }) => {
if (fixing) return;
// 우리가 다시 정한 선택이 되돌아와서 오는 이벤트는 한 번 더 기록하지 않아요.
if (expected !== null && JSON.stringify(selectedKeys) === expected) {
expected = null;
return;
}
expected = null;
const allowed = selectedKeys.filter((key) => {
const row = api.getRowByKey(key);
return row !== undefined && !isLocked(row);
});
// 머리글 체크박스는 '모든 행'을 켜고 끄기 때문에, 고를 수 있는 행이 이미 모두 골라진 상태에서 누르면
// 잠긴 행들이 한꺼번에 더해져서 와요. 그때는 '전체 해제'를 누른 것으로 보고 모두 풀어 줘요.
const addedLocked = selectedKeys.filter(
(key) => lockedKeys.includes(key) && !previous.includes(key),
);
const wasAll = selectable.length > 0 && selectable.every((row) => previous.includes(row.id));
const clearing = wasAll && lockedKeys.length > 1 && addedLocked.length === lockedKeys.length;
const next = clearing ? [] : allowed;
previous = next;
if (!clearing && allowed.length === selectedKeys.length)
return log({ ko: `${allowed.length}행 선택`, en: `${allowed.length} rows selected` });
fixing = true;
expected = JSON.stringify(next);
try {
api.setSelectedKeys(next);
} finally {
fixing = false;
}
log({
ko: clearing
? '전체 해제: 선택을 모두 풀었어요'
: `결제 완료 행 ${selectedKeys.length - allowed.length}개는 고를 수 없어서 뺐어요 → ${allowed.length}행 선택`,
en: clearing
? 'Clear all: selection removed'
: `${selectedKeys.length - allowed.length} paid rows cannot be selected and were left out → ${allowed.length} rows selected`,
});
});
return () => {
off();
style.remove();
};
}
export const actions = {
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
clear: (api: GridApi<Row>) => api.clearSelection(),
};버튼을 누르면 이 예제의 코드가 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.selectAll(api)"
>전체 선택</button>
<button type="button" :disabled="!api" @click="api && actions.clear(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;
status: string;
amount: number;
}
const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'바다유통',
'해든전자',
];
const statuses = ['결제 완료', '대기', '연체'];
// 결제가 끝난 행은 잠가서 고를 수 없게 해요. 잠긴 행은 rowClass로 흐리게 보여 줘요.
const isLocked = (row: Row): boolean => row.status === '결제 완료';
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객사', width: 150 },
{ id: 'status', title: '상태', width: 110 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: customers.map((customer, i) => ({
id: i + 1,
customer,
status: statuses[(i * 2) % 3] as string,
amount: 430000 + ((i * 613000) % 2900000),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
rowClass: (row) => (isLocked(row) ? 'scr-locked' : undefined),
};
// '고를 수 없는 행' 옵션은 따로 없어서, 선택이 바뀐 뒤에 잠긴 행을 빼서 다시 정해요.
// 이 안에서 setSelectedKeys를 또 부르면 selectionChanged가 다시 오니까, 스스로 부른 호출은 건너뛰어요.
let fixing = false;
let previous: (string | number)[] = [];
let expected: string | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const style = document.createElement('style');
style.textContent = '.scr-locked { opacity: 0.55; }';
document.head.append(style);
fixing = false;
previous = [];
const lockedKeys: (string | number)[] = api
.getRows()
.filter(isLocked)
.map((row) => row.id);
const selectable = api.getRows().filter((row) => !isLocked(row));
const off = api.on('selectionChanged', ({ selectedKeys }) => {
if (fixing) return;
// 우리가 다시 정한 선택이 되돌아와서 오는 이벤트는 한 번 더 기록하지 않아요.
if (expected !== null && JSON.stringify(selectedKeys) === expected) {
expected = null;
return;
}
expected = null;
const allowed = selectedKeys.filter((key) => {
const row = api.getRowByKey(key);
return row !== undefined && !isLocked(row);
});
// 머리글 체크박스는 '모든 행'을 켜고 끄기 때문에, 고를 수 있는 행이 이미 모두 골라진 상태에서 누르면
// 잠긴 행들이 한꺼번에 더해져서 와요. 그때는 '전체 해제'를 누른 것으로 보고 모두 풀어 줘요.
const addedLocked = selectedKeys.filter(
(key) => lockedKeys.includes(key) && !previous.includes(key),
);
const wasAll = selectable.length > 0 && selectable.every((row) => previous.includes(row.id));
const clearing = wasAll && lockedKeys.length > 1 && addedLocked.length === lockedKeys.length;
const next = clearing ? [] : allowed;
previous = next;
if (!clearing && allowed.length === selectedKeys.length)
return log({ ko: `${allowed.length}행 선택`, en: `${allowed.length} rows selected` });
fixing = true;
expected = JSON.stringify(next);
try {
api.setSelectedKeys(next);
} finally {
fixing = false;
}
log({
ko: clearing
? '전체 해제: 선택을 모두 풀었어요'
: `결제 완료 행 ${selectedKeys.length - allowed.length}개는 고를 수 없어서 뺐어요 → ${allowed.length}행 선택`,
en: clearing
? 'Clear all: selection removed'
: `${selectedKeys.length - allowed.length} paid rows cannot be selected and were left out → ${allowed.length} rows selected`,
});
});
return () => {
off();
style.remove();
};
}
export const actions = {
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
clear: (api: GridApi<Row>) => api.clearSelection(),
};버튼을 누르면 이 예제의 코드가 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.selectAll(api)"
>전체 선택</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(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;
status: string;
amount: number;
}
const customers = [
'한빛물류',
'푸른하늘식품',
'북극성무역',
'다온상사',
'새벽농원',
'모아패션',
'바다유통',
'해든전자',
];
const statuses = ['결제 완료', '대기', '연체'];
// 결제가 끝난 행은 잠가서 고를 수 없게 해요. 잠긴 행은 rowClass로 흐리게 보여 줘요.
const isLocked = (row: Row): boolean => row.status === '결제 완료';
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: '고객사', width: 150 },
{ id: 'status', title: '상태', width: 110 },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: customers.map((customer, i) => ({
id: i + 1,
customer,
status: statuses[(i * 2) % 3] as string,
amount: 430000 + ((i * 613000) % 2900000),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
rowClass: (row) => (isLocked(row) ? 'scr-locked' : undefined),
};
// '고를 수 없는 행' 옵션은 따로 없어서, 선택이 바뀐 뒤에 잠긴 행을 빼서 다시 정해요.
// 이 안에서 setSelectedKeys를 또 부르면 selectionChanged가 다시 오니까, 스스로 부른 호출은 건너뛰어요.
let fixing = false;
let previous: (string | number)[] = [];
let expected: string | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const style = document.createElement('style');
style.textContent = '.scr-locked { opacity: 0.55; }';
document.head.append(style);
fixing = false;
previous = [];
const lockedKeys: (string | number)[] = api
.getRows()
.filter(isLocked)
.map((row) => row.id);
const selectable = api.getRows().filter((row) => !isLocked(row));
const off = api.on('selectionChanged', ({ selectedKeys }) => {
if (fixing) return;
// 우리가 다시 정한 선택이 되돌아와서 오는 이벤트는 한 번 더 기록하지 않아요.
if (expected !== null && JSON.stringify(selectedKeys) === expected) {
expected = null;
return;
}
expected = null;
const allowed = selectedKeys.filter((key) => {
const row = api.getRowByKey(key);
return row !== undefined && !isLocked(row);
});
// 머리글 체크박스는 '모든 행'을 켜고 끄기 때문에, 고를 수 있는 행이 이미 모두 골라진 상태에서 누르면
// 잠긴 행들이 한꺼번에 더해져서 와요. 그때는 '전체 해제'를 누른 것으로 보고 모두 풀어 줘요.
const addedLocked = selectedKeys.filter(
(key) => lockedKeys.includes(key) && !previous.includes(key),
);
const wasAll = selectable.length > 0 && selectable.every((row) => previous.includes(row.id));
const clearing = wasAll && lockedKeys.length > 1 && addedLocked.length === lockedKeys.length;
const next = clearing ? [] : allowed;
previous = next;
if (!clearing && allowed.length === selectedKeys.length)
return log({ ko: `${allowed.length}행 선택`, en: `${allowed.length} rows selected` });
fixing = true;
expected = JSON.stringify(next);
try {
api.setSelectedKeys(next);
} finally {
fixing = false;
}
log({
ko: clearing
? '전체 해제: 선택을 모두 풀었어요'
: `결제 완료 행 ${selectedKeys.length - allowed.length}개는 고를 수 없어서 뺐어요 → ${allowed.length}행 선택`,
en: clearing
? 'Clear all: selection removed'
: `${selectedKeys.length - allowed.length} paid rows cannot be selected and were left out → ${allowed.length} rows selected`,
});
});
return () => {
off();
style.remove();
};
}
export const actions = {
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
clear: (api: GridApi<Row>) => api.clearSelection(),
};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="selectAll">Select all</button>
<button type="button" id="clear">Clear selection</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('selectAll').addEventListener('click', () => actions.selectAll(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const customers = [
'Bright Logistics',
'Blue Sky Foods',
'Polaris Trading',
'Dawn Corp',
'Sunrise Farm',
'Moa Fashion',
'Ocean Retail',
'Haeden Electronics',
];
const statuses = ['Paid', 'Pending', 'Overdue'];
// Paid rows are locked so they cannot be selected. Locked rows are dimmed with rowClass.
const isLocked = (row) => row.status === 'Paid';
export const options = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{ id: 'status', title: 'Status', width: 110 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: customers.map((customer, i) => ({
id: i + 1,
customer,
status: statuses[(i * 2) % 3],
amount: 430 + ((i * 613) % 2900),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
rowClass: (row) => (isLocked(row) ? 'scr-locked' : undefined),
};
// There is no separate "unselectable rows" option, so after the selection changes we drop locked rows and set it again.
// Calling setSelectedKeys in here fires selectionChanged again, so calls we made ourselves are skipped.
let fixing = false;
let previous = [];
let expected = null;
export function setup(api, log) {
const style = document.createElement('style');
style.textContent = '.scr-locked { opacity: 0.55; }';
document.head.append(style);
fixing = false;
previous = [];
const lockedKeys = api
.getRows()
.filter(isLocked)
.map((row) => row.id);
const selectable = api.getRows().filter((row) => !isLocked(row));
const off = api.on('selectionChanged', ({ selectedKeys }) => {
if (fixing)
return;
// The event that comes back from the selection we just set is not logged a second time.
if (expected !== null && JSON.stringify(selectedKeys) === expected) {
expected = null;
return;
}
expected = null;
const allowed = selectedKeys.filter((key) => {
const row = api.getRowByKey(key);
return row !== undefined && !isLocked(row);
});
// The header checkbox toggles "all rows", so pressing it when every selectable row is already selected
// adds all locked rows at once. Treat that as "clear all" and deselect everything.
const addedLocked = selectedKeys.filter((key) => lockedKeys.includes(key) && !previous.includes(key));
const wasAll = selectable.length > 0 && selectable.every((row) => previous.includes(row.id));
const clearing = wasAll && lockedKeys.length > 1 && addedLocked.length === lockedKeys.length;
const next = clearing ? [] : allowed;
previous = next;
if (!clearing && allowed.length === selectedKeys.length)
return log(`${allowed.length} rows selected`);
fixing = true;
expected = JSON.stringify(next);
try {
api.setSelectedKeys(next);
}
finally {
fixing = false;
}
log(clearing
? 'Clear all: selection removed'
: `${selectedKeys.length - allowed.length} paid rows cannot be selected and were left out → ${allowed.length} rows selected`);
});
return () => {
off();
style.remove();
};
}
export const actions = {
selectAll: (api) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
clear: (api) => api.clearSelection(),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Let users select only matching rows</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="selectAll">Select all</button>
<button type="button" id="clear">Clear selection</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 = [
'Bright Logistics',
'Blue Sky Foods',
'Polaris Trading',
'Dawn Corp',
'Sunrise Farm',
'Moa Fashion',
'Ocean Retail',
'Haeden Electronics',
];
const statuses = ['Paid', 'Pending', 'Overdue'];
// Paid rows are locked so they cannot be selected. Locked rows are dimmed with rowClass.
const isLocked = (row) => row.status === 'Paid';
const options = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{ id: 'status', title: 'Status', width: 110 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: customers.map((customer, i) => ({
id: i + 1,
customer,
status: statuses[(i * 2) % 3],
amount: 430 + ((i * 613) % 2900),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
rowClass: (row) => (isLocked(row) ? 'scr-locked' : undefined),
};
// There is no separate "unselectable rows" option, so after the selection changes we drop locked rows and set it again.
// Calling setSelectedKeys in here fires selectionChanged again, so calls we made ourselves are skipped.
let fixing = false;
let previous = [];
let expected = null;
function setup(api, log) {
const style = document.createElement('style');
style.textContent = '.scr-locked { opacity: 0.55; }';
document.head.append(style);
fixing = false;
previous = [];
const lockedKeys = api
.getRows()
.filter(isLocked)
.map((row) => row.id);
const selectable = api.getRows().filter((row) => !isLocked(row));
const off = api.on('selectionChanged', ({ selectedKeys }) => {
if (fixing)
return;
// The event that comes back from the selection we just set is not logged a second time.
if (expected !== null && JSON.stringify(selectedKeys) === expected) {
expected = null;
return;
}
expected = null;
const allowed = selectedKeys.filter((key) => {
const row = api.getRowByKey(key);
return row !== undefined && !isLocked(row);
});
// The header checkbox toggles "all rows", so pressing it when every selectable row is already selected
// adds all locked rows at once. Treat that as "clear all" and deselect everything.
const addedLocked = selectedKeys.filter((key) => lockedKeys.includes(key) && !previous.includes(key));
const wasAll = selectable.length > 0 && selectable.every((row) => previous.includes(row.id));
const clearing = wasAll && lockedKeys.length > 1 && addedLocked.length === lockedKeys.length;
const next = clearing ? [] : allowed;
previous = next;
if (!clearing && allowed.length === selectedKeys.length)
return log(`${allowed.length} rows selected`);
fixing = true;
expected = JSON.stringify(next);
try {
api.setSelectedKeys(next);
}
finally {
fixing = false;
}
log(clearing
? 'Clear all: selection removed'
: `${selectedKeys.length - allowed.length} paid rows cannot be selected and were left out → ${allowed.length} rows selected`);
});
return () => {
off();
style.remove();
};
}
const actions = {
selectAll: (api) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
clear: (api) => api.clearSelection(),
};
options.ariaLabel = "Let users select only matching rows";
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('selectAll').addEventListener('click', () => actions.selectAll(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.selectAll(api)}
>Select all</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear selection</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;
status: string;
amount: number;
}
const customers = [
'Bright Logistics',
'Blue Sky Foods',
'Polaris Trading',
'Dawn Corp',
'Sunrise Farm',
'Moa Fashion',
'Ocean Retail',
'Haeden Electronics',
];
const statuses = ['Paid', 'Pending', 'Overdue'];
// Paid rows are locked so they cannot be selected. Locked rows are dimmed with rowClass.
const isLocked = (row: Row): boolean => row.status === 'Paid';
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{ id: 'status', title: 'Status', width: 110 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: customers.map((customer, i) => ({
id: i + 1,
customer,
status: statuses[(i * 2) % 3] as string,
amount: 430 + ((i * 613) % 2900),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
rowClass: (row) => (isLocked(row) ? 'scr-locked' : undefined),
};
// There is no separate "unselectable rows" option, so after the selection changes we drop locked rows and set it again.
// Calling setSelectedKeys in here fires selectionChanged again, so calls we made ourselves are skipped.
let fixing = false;
let previous: (string | number)[] = [];
let expected: string | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const style = document.createElement('style');
style.textContent = '.scr-locked { opacity: 0.55; }';
document.head.append(style);
fixing = false;
previous = [];
const lockedKeys: (string | number)[] = api
.getRows()
.filter(isLocked)
.map((row) => row.id);
const selectable = api.getRows().filter((row) => !isLocked(row));
const off = api.on('selectionChanged', ({ selectedKeys }) => {
if (fixing) return;
// The event that comes back from the selection we just set is not logged a second time.
if (expected !== null && JSON.stringify(selectedKeys) === expected) {
expected = null;
return;
}
expected = null;
const allowed = selectedKeys.filter((key) => {
const row = api.getRowByKey(key);
return row !== undefined && !isLocked(row);
});
// The header checkbox toggles "all rows", so pressing it when every selectable row is already selected
// adds all locked rows at once. Treat that as "clear all" and deselect everything.
const addedLocked = selectedKeys.filter(
(key) => lockedKeys.includes(key) && !previous.includes(key),
);
const wasAll = selectable.length > 0 && selectable.every((row) => previous.includes(row.id));
const clearing = wasAll && lockedKeys.length > 1 && addedLocked.length === lockedKeys.length;
const next = clearing ? [] : allowed;
previous = next;
if (!clearing && allowed.length === selectedKeys.length)
return log(`${allowed.length} rows selected`);
fixing = true;
expected = JSON.stringify(next);
try {
api.setSelectedKeys(next);
} finally {
fixing = false;
}
log(
clearing
? 'Clear all: selection removed'
: `${selectedKeys.length - allowed.length} paid rows cannot be selected and were left out → ${allowed.length} rows selected`,
);
});
return () => {
off();
style.remove();
};
}
export const actions = {
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
clear: (api: GridApi<Row>) => api.clearSelection(),
};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.selectAll(api)"
>Select all</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear selection</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;
status: string;
amount: number;
}
const customers = [
'Bright Logistics',
'Blue Sky Foods',
'Polaris Trading',
'Dawn Corp',
'Sunrise Farm',
'Moa Fashion',
'Ocean Retail',
'Haeden Electronics',
];
const statuses = ['Paid', 'Pending', 'Overdue'];
// Paid rows are locked so they cannot be selected. Locked rows are dimmed with rowClass.
const isLocked = (row: Row): boolean => row.status === 'Paid';
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{ id: 'status', title: 'Status', width: 110 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: customers.map((customer, i) => ({
id: i + 1,
customer,
status: statuses[(i * 2) % 3] as string,
amount: 430 + ((i * 613) % 2900),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
rowClass: (row) => (isLocked(row) ? 'scr-locked' : undefined),
};
// There is no separate "unselectable rows" option, so after the selection changes we drop locked rows and set it again.
// Calling setSelectedKeys in here fires selectionChanged again, so calls we made ourselves are skipped.
let fixing = false;
let previous: (string | number)[] = [];
let expected: string | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const style = document.createElement('style');
style.textContent = '.scr-locked { opacity: 0.55; }';
document.head.append(style);
fixing = false;
previous = [];
const lockedKeys: (string | number)[] = api
.getRows()
.filter(isLocked)
.map((row) => row.id);
const selectable = api.getRows().filter((row) => !isLocked(row));
const off = api.on('selectionChanged', ({ selectedKeys }) => {
if (fixing) return;
// The event that comes back from the selection we just set is not logged a second time.
if (expected !== null && JSON.stringify(selectedKeys) === expected) {
expected = null;
return;
}
expected = null;
const allowed = selectedKeys.filter((key) => {
const row = api.getRowByKey(key);
return row !== undefined && !isLocked(row);
});
// The header checkbox toggles "all rows", so pressing it when every selectable row is already selected
// adds all locked rows at once. Treat that as "clear all" and deselect everything.
const addedLocked = selectedKeys.filter(
(key) => lockedKeys.includes(key) && !previous.includes(key),
);
const wasAll = selectable.length > 0 && selectable.every((row) => previous.includes(row.id));
const clearing = wasAll && lockedKeys.length > 1 && addedLocked.length === lockedKeys.length;
const next = clearing ? [] : allowed;
previous = next;
if (!clearing && allowed.length === selectedKeys.length)
return log(`${allowed.length} rows selected`);
fixing = true;
expected = JSON.stringify(next);
try {
api.setSelectedKeys(next);
} finally {
fixing = false;
}
log(
clearing
? 'Clear all: selection removed'
: `${selectedKeys.length - allowed.length} paid rows cannot be selected and were left out → ${allowed.length} rows selected`,
);
});
return () => {
off();
style.remove();
};
}
export const actions = {
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
clear: (api: GridApi<Row>) => api.clearSelection(),
};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.selectAll(api)"
>Select all</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear selection</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;
status: string;
amount: number;
}
const customers = [
'Bright Logistics',
'Blue Sky Foods',
'Polaris Trading',
'Dawn Corp',
'Sunrise Farm',
'Moa Fashion',
'Ocean Retail',
'Haeden Electronics',
];
const statuses = ['Paid', 'Pending', 'Overdue'];
// Paid rows are locked so they cannot be selected. Locked rows are dimmed with rowClass.
const isLocked = (row: Row): boolean => row.status === 'Paid';
export const options: GridOptions<Row> = {
columns: [
{ id: 'customer', title: 'Customer', width: 170 },
{ id: 'status', title: 'Status', width: 110 },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: customers.map((customer, i) => ({
id: i + 1,
customer,
status: statuses[(i * 2) % 3] as string,
amount: 430 + ((i * 613) % 2900),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
rowClass: (row) => (isLocked(row) ? 'scr-locked' : undefined),
};
// There is no separate "unselectable rows" option, so after the selection changes we drop locked rows and set it again.
// Calling setSelectedKeys in here fires selectionChanged again, so calls we made ourselves are skipped.
let fixing = false;
let previous: (string | number)[] = [];
let expected: string | null = null;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const style = document.createElement('style');
style.textContent = '.scr-locked { opacity: 0.55; }';
document.head.append(style);
fixing = false;
previous = [];
const lockedKeys: (string | number)[] = api
.getRows()
.filter(isLocked)
.map((row) => row.id);
const selectable = api.getRows().filter((row) => !isLocked(row));
const off = api.on('selectionChanged', ({ selectedKeys }) => {
if (fixing) return;
// The event that comes back from the selection we just set is not logged a second time.
if (expected !== null && JSON.stringify(selectedKeys) === expected) {
expected = null;
return;
}
expected = null;
const allowed = selectedKeys.filter((key) => {
const row = api.getRowByKey(key);
return row !== undefined && !isLocked(row);
});
// The header checkbox toggles "all rows", so pressing it when every selectable row is already selected
// adds all locked rows at once. Treat that as "clear all" and deselect everything.
const addedLocked = selectedKeys.filter(
(key) => lockedKeys.includes(key) && !previous.includes(key),
);
const wasAll = selectable.length > 0 && selectable.every((row) => previous.includes(row.id));
const clearing = wasAll && lockedKeys.length > 1 && addedLocked.length === lockedKeys.length;
const next = clearing ? [] : allowed;
previous = next;
if (!clearing && allowed.length === selectedKeys.length)
return log(`${allowed.length} rows selected`);
fixing = true;
expected = JSON.stringify(next);
try {
api.setSelectedKeys(next);
} finally {
fixing = false;
}
log(
clearing
? 'Clear all: selection removed'
: `${selectedKeys.length - allowed.length} paid rows cannot be selected and were left out → ${allowed.length} rows selected`,
);
});
return () => {
off();
style.remove();
};
}
export const actions = {
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((row) => row.id)),
clear: (api: GridApi<Row>) => api.clearSelection(),
};