선택·포커스·클릭 이벤트 한눈에 보기Selection, focus and click events at a glance
한 번의 클릭도 선택 변경, 포커스 이동, 행 클릭, 칸 클릭 이벤트로 나뉘어 와요. 어떤 동작에 어떤 이벤트가 오는지 기록 창으로 직접 확인하고, 필요한 것만 골라 받을 수 있어요.One click raises several events: selection changed, focus moved, row clicked, cell clicked. See which action raises which in the log and subscribe to only what you need.
코드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="selectTwo">2·3번째 행 고르기 (코드)</button>
<button type="button" id="sameAgain">같은 선택 다시 정하기</button>
<button type="button" id="clear">선택 지우기</button>
</div>
<div id="grid" style="height: 330px"></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('selectTwo').addEventListener('click', () => actions.selectTwo(api));
document.getElementById('sameAgain').addEventListener('click', () => actions.sameAgain(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
const statuses = ['결제 완료', '대기', '연체'];
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 },
};
const TITLE = { customer: '고객사', status: '상태', amount: '금액' };
const col = (id) => (id ? (TITLE[id] ?? id) : '-');
// 같은 클릭도 여러 이벤트를 내요. 선택이 바뀌었는지(selectionChanged), 포커스가 옮겨 갔는지(focusChanged),
// 행을 눌렀는지(rowClicked)·칸을 눌렀는지(cellClicked)를 따로 받을 수 있어요.
export function setup(api, log) {
const name = (key) => api.getRowByKey(key)?.customer ?? String(key);
const offs = [
api.on('selectionChanged', (e) => log({
ko: `선택 바뀜: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : '없음'}`,
en: `Selection changed: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : 'none'}`,
})),
api.on('focusChanged', (e) => log({
ko: `포커스: ${name(e.rowKey)} / ${col(e.columnId)}`,
en: `Focus: ${name(e.rowKey)} / ${col(e.columnId)}`,
})),
api.on('rowClicked', (e) => log({
ko: `행 클릭: ${name(e.rowKey)} (화면 ${e.rowIndex + 1}번째 줄)`,
en: `Row click: ${name(e.rowKey)} (line ${e.rowIndex + 1} on screen)`,
})),
api.on('cellClicked', (e) => log({
ko: `칸 클릭: ${col(e.columnId)} = ${String(e.value)}`,
en: `Cell click: ${col(e.columnId)} = ${String(e.value)}`,
})),
api.on('rowDoubleClicked', (e) => log({ ko: `행 더블클릭: ${name(e.rowKey)}`, en: `Row double-click: ${name(e.rowKey)}` })),
api.on('headerClicked', (e) => log({ ko: `헤더 클릭: ${col(e.columnId)}`, en: `Header click: ${col(e.columnId)}` })),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectTwo: (api) => api.setSelectedKeys([2, 3]),
// 지금과 같은 선택을 다시 정해도 바뀐 게 없으면 selectionChanged는 오지 않아요.
sameAgain: (api) => api.setSelectedKeys(api.getSelectedKeys()),
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="selectTwo">2·3번째 행 고르기 (코드)</button>
<button type="button" id="sameAgain">같은 선택 다시 정하기</button>
<button type="button" id="clear">선택 지우기</button>
</div>
<div id="grid" style="height: 330px"></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 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 },
};
const TITLE = { customer: '고객사', status: '상태', amount: '금액' };
const col = (id) => (id ? (TITLE[id] ?? id) : '-');
// 같은 클릭도 여러 이벤트를 내요. 선택이 바뀌었는지(selectionChanged), 포커스가 옮겨 갔는지(focusChanged),
// 행을 눌렀는지(rowClicked)·칸을 눌렀는지(cellClicked)를 따로 받을 수 있어요.
function setup(api, log) {
const name = (key) => api.getRowByKey(key)?.customer ?? String(key);
const offs = [
api.on('selectionChanged', (e) => log({
ko: `선택 바뀜: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : '없음'}`,
en: `Selection changed: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : 'none'}`,
})),
api.on('focusChanged', (e) => log({
ko: `포커스: ${name(e.rowKey)} / ${col(e.columnId)}`,
en: `Focus: ${name(e.rowKey)} / ${col(e.columnId)}`,
})),
api.on('rowClicked', (e) => log({
ko: `행 클릭: ${name(e.rowKey)} (화면 ${e.rowIndex + 1}번째 줄)`,
en: `Row click: ${name(e.rowKey)} (line ${e.rowIndex + 1} on screen)`,
})),
api.on('cellClicked', (e) => log({
ko: `칸 클릭: ${col(e.columnId)} = ${String(e.value)}`,
en: `Cell click: ${col(e.columnId)} = ${String(e.value)}`,
})),
api.on('rowDoubleClicked', (e) => log({ ko: `행 더블클릭: ${name(e.rowKey)}`, en: `Row double-click: ${name(e.rowKey)}` })),
api.on('headerClicked', (e) => log({ ko: `헤더 클릭: ${col(e.columnId)}`, en: `Header click: ${col(e.columnId)}` })),
];
return () => offs.forEach((off) => off());
}
const actions = {
selectTwo: (api) => api.setSelectedKeys([2, 3]),
// 지금과 같은 선택을 다시 정해도 바뀐 게 없으면 selectionChanged는 오지 않아요.
sameAgain: (api) => api.setSelectedKeys(api.getSelectedKeys()),
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('selectTwo').addEventListener('click', () => actions.selectTwo(api));
document.getElementById('sameAgain').addEventListener('click', () => actions.sameAgain(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.selectTwo(api)}
>2·3번째 행 고르기 (코드)</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.sameAgain(api)}
>같은 선택 다시 정하기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>선택 지우기</button>
</div>
<Grid style={{ height: 330 }} 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 = ['결제 완료', '대기', '연체'];
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 },
};
const TITLE: Record<string, string> = { customer: '고객사', status: '상태', amount: '금액' };
const col = (id: string | null | undefined): string => (id ? (TITLE[id] ?? id) : '-');
// 같은 클릭도 여러 이벤트를 내요. 선택이 바뀌었는지(selectionChanged), 포커스가 옮겨 갔는지(focusChanged),
// 행을 눌렀는지(rowClicked)·칸을 눌렀는지(cellClicked)를 따로 받을 수 있어요.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const name = (key: unknown): string => api.getRowByKey(key as number)?.customer ?? String(key);
const offs = [
api.on('selectionChanged', (e) =>
log({
ko: `선택 바뀜: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : '없음'}`,
en: `Selection changed: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : 'none'}`,
}),
),
api.on('focusChanged', (e) =>
log({
ko: `포커스: ${name(e.rowKey)} / ${col(e.columnId)}`,
en: `Focus: ${name(e.rowKey)} / ${col(e.columnId)}`,
}),
),
api.on('rowClicked', (e) =>
log({
ko: `행 클릭: ${name(e.rowKey)} (화면 ${e.rowIndex + 1}번째 줄)`,
en: `Row click: ${name(e.rowKey)} (line ${e.rowIndex + 1} on screen)`,
}),
),
api.on('cellClicked', (e) =>
log({
ko: `칸 클릭: ${col(e.columnId)} = ${String(e.value)}`,
en: `Cell click: ${col(e.columnId)} = ${String(e.value)}`,
}),
),
api.on('rowDoubleClicked', (e) =>
log({ ko: `행 더블클릭: ${name(e.rowKey)}`, en: `Row double-click: ${name(e.rowKey)}` }),
),
api.on('headerClicked', (e) =>
log({ ko: `헤더 클릭: ${col(e.columnId)}`, en: `Header click: ${col(e.columnId)}` }),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectTwo: (api: GridApi<Row>) => api.setSelectedKeys([2, 3]),
// 지금과 같은 선택을 다시 정해도 바뀐 게 없으면 selectionChanged는 오지 않아요.
sameAgain: (api: GridApi<Row>) => api.setSelectedKeys(api.getSelectedKeys()),
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.selectTwo(api)"
>2·3번째 행 고르기 (코드)</button>
<button
type="button"
:disabled="!api"
@click="api && actions.sameAgain(api)"
>같은 선택 다시 정하기</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">선택 지우기</button>
</div>
<Grid style="height: 330px" :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 = ['결제 완료', '대기', '연체'];
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 },
};
const TITLE: Record<string, string> = { customer: '고객사', status: '상태', amount: '금액' };
const col = (id: string | null | undefined): string => (id ? (TITLE[id] ?? id) : '-');
// 같은 클릭도 여러 이벤트를 내요. 선택이 바뀌었는지(selectionChanged), 포커스가 옮겨 갔는지(focusChanged),
// 행을 눌렀는지(rowClicked)·칸을 눌렀는지(cellClicked)를 따로 받을 수 있어요.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const name = (key: unknown): string => api.getRowByKey(key as number)?.customer ?? String(key);
const offs = [
api.on('selectionChanged', (e) =>
log({
ko: `선택 바뀜: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : '없음'}`,
en: `Selection changed: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : 'none'}`,
}),
),
api.on('focusChanged', (e) =>
log({
ko: `포커스: ${name(e.rowKey)} / ${col(e.columnId)}`,
en: `Focus: ${name(e.rowKey)} / ${col(e.columnId)}`,
}),
),
api.on('rowClicked', (e) =>
log({
ko: `행 클릭: ${name(e.rowKey)} (화면 ${e.rowIndex + 1}번째 줄)`,
en: `Row click: ${name(e.rowKey)} (line ${e.rowIndex + 1} on screen)`,
}),
),
api.on('cellClicked', (e) =>
log({
ko: `칸 클릭: ${col(e.columnId)} = ${String(e.value)}`,
en: `Cell click: ${col(e.columnId)} = ${String(e.value)}`,
}),
),
api.on('rowDoubleClicked', (e) =>
log({ ko: `행 더블클릭: ${name(e.rowKey)}`, en: `Row double-click: ${name(e.rowKey)}` }),
),
api.on('headerClicked', (e) =>
log({ ko: `헤더 클릭: ${col(e.columnId)}`, en: `Header click: ${col(e.columnId)}` }),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectTwo: (api: GridApi<Row>) => api.setSelectedKeys([2, 3]),
// 지금과 같은 선택을 다시 정해도 바뀐 게 없으면 selectionChanged는 오지 않아요.
sameAgain: (api: GridApi<Row>) => api.setSelectedKeys(api.getSelectedKeys()),
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.selectTwo(api)"
>2·3번째 행 고르기 (코드)</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.sameAgain(api)"
>같은 선택 다시 정하기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>선택 지우기</button>
</div>
<mx-grid style="height: 330px" [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 = ['결제 완료', '대기', '연체'];
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 },
};
const TITLE: Record<string, string> = { customer: '고객사', status: '상태', amount: '금액' };
const col = (id: string | null | undefined): string => (id ? (TITLE[id] ?? id) : '-');
// 같은 클릭도 여러 이벤트를 내요. 선택이 바뀌었는지(selectionChanged), 포커스가 옮겨 갔는지(focusChanged),
// 행을 눌렀는지(rowClicked)·칸을 눌렀는지(cellClicked)를 따로 받을 수 있어요.
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const name = (key: unknown): string => api.getRowByKey(key as number)?.customer ?? String(key);
const offs = [
api.on('selectionChanged', (e) =>
log({
ko: `선택 바뀜: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : '없음'}`,
en: `Selection changed: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : 'none'}`,
}),
),
api.on('focusChanged', (e) =>
log({
ko: `포커스: ${name(e.rowKey)} / ${col(e.columnId)}`,
en: `Focus: ${name(e.rowKey)} / ${col(e.columnId)}`,
}),
),
api.on('rowClicked', (e) =>
log({
ko: `행 클릭: ${name(e.rowKey)} (화면 ${e.rowIndex + 1}번째 줄)`,
en: `Row click: ${name(e.rowKey)} (line ${e.rowIndex + 1} on screen)`,
}),
),
api.on('cellClicked', (e) =>
log({
ko: `칸 클릭: ${col(e.columnId)} = ${String(e.value)}`,
en: `Cell click: ${col(e.columnId)} = ${String(e.value)}`,
}),
),
api.on('rowDoubleClicked', (e) =>
log({ ko: `행 더블클릭: ${name(e.rowKey)}`, en: `Row double-click: ${name(e.rowKey)}` }),
),
api.on('headerClicked', (e) =>
log({ ko: `헤더 클릭: ${col(e.columnId)}`, en: `Header click: ${col(e.columnId)}` }),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectTwo: (api: GridApi<Row>) => api.setSelectedKeys([2, 3]),
// 지금과 같은 선택을 다시 정해도 바뀐 게 없으면 selectionChanged는 오지 않아요.
sameAgain: (api: GridApi<Row>) => api.setSelectedKeys(api.getSelectedKeys()),
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="selectTwo">Select rows 2 and 3 (code)</button>
<button type="button" id="sameAgain">Set the same selection again</button>
<button type="button" id="clear">Clear selection</button>
</div>
<div id="grid" style="height: 330px"></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('selectTwo').addEventListener('click', () => actions.selectTwo(api));
document.getElementById('sameAgain').addEventListener('click', () => actions.sameAgain(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harbor & Co.',
'Dawn Farms',
'Moda Fashion',
];
const statuses = ['Paid', 'Pending', 'Overdue'];
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: 430000 + ((i * 613000) % 2900000),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
const TITLE = { customer: 'Customer', status: 'Status', amount: 'Amount' };
const col = (id) => (id ? (TITLE[id] ?? id) : '-');
// One click emits several events. You can listen separately for whether the selection changed (selectionChanged),
// whether focus moved (focusChanged), and whether a row (rowClicked) or a cell (cellClicked) was clicked.
export function setup(api, log) {
const name = (key) => api.getRowByKey(key)?.customer ?? String(key);
const offs = [
api.on('selectionChanged', (e) => log(`Selection changed: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : 'none'}`)),
api.on('focusChanged', (e) => log(`Focus: ${name(e.rowKey)} / ${col(e.columnId)}`)),
api.on('rowClicked', (e) => log(`Row click: ${name(e.rowKey)} (line ${e.rowIndex + 1} on screen)`)),
api.on('cellClicked', (e) => log(`Cell click: ${col(e.columnId)} = ${String(e.value)}`)),
api.on('rowDoubleClicked', (e) => log(`Row double-click: ${name(e.rowKey)}`)),
api.on('headerClicked', (e) => log(`Header click: ${col(e.columnId)}`)),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectTwo: (api) => api.setSelectedKeys([2, 3]),
// Setting the same selection again sends no selectionChanged, because nothing changed.
sameAgain: (api) => api.setSelectedKeys(api.getSelectedKeys()),
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>Selection, focus and click events at a glance</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="selectTwo">Select rows 2 and 3 (code)</button>
<button type="button" id="sameAgain">Set the same selection again</button>
<button type="button" id="clear">Clear selection</button>
</div>
<div id="grid" style="height: 330px"></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',
'Moda Fashion',
];
const statuses = ['Paid', 'Pending', 'Overdue'];
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: 430000 + ((i * 613000) % 2900000),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
const TITLE = { customer: 'Customer', status: 'Status', amount: 'Amount' };
const col = (id) => (id ? (TITLE[id] ?? id) : '-');
// One click emits several events. You can listen separately for whether the selection changed (selectionChanged),
// whether focus moved (focusChanged), and whether a row (rowClicked) or a cell (cellClicked) was clicked.
function setup(api, log) {
const name = (key) => api.getRowByKey(key)?.customer ?? String(key);
const offs = [
api.on('selectionChanged', (e) => log(`Selection changed: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : 'none'}`)),
api.on('focusChanged', (e) => log(`Focus: ${name(e.rowKey)} / ${col(e.columnId)}`)),
api.on('rowClicked', (e) => log(`Row click: ${name(e.rowKey)} (line ${e.rowIndex + 1} on screen)`)),
api.on('cellClicked', (e) => log(`Cell click: ${col(e.columnId)} = ${String(e.value)}`)),
api.on('rowDoubleClicked', (e) => log(`Row double-click: ${name(e.rowKey)}`)),
api.on('headerClicked', (e) => log(`Header click: ${col(e.columnId)}`)),
];
return () => offs.forEach((off) => off());
}
const actions = {
selectTwo: (api) => api.setSelectedKeys([2, 3]),
// Setting the same selection again sends no selectionChanged, because nothing changed.
sameAgain: (api) => api.setSelectedKeys(api.getSelectedKeys()),
clear: (api) => api.clearSelection(),
};
options.ariaLabel = "Selection, focus and click events at a glance";
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('selectTwo').addEventListener('click', () => actions.selectTwo(api));
document.getElementById('sameAgain').addEventListener('click', () => actions.sameAgain(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.selectTwo(api)}
>Select rows 2 and 3 (code)</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.sameAgain(api)}
>Set the same selection again</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear selection</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
customer: string;
status: string;
amount: number;
}
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harbor & Co.',
'Dawn Farms',
'Moda Fashion',
];
const statuses = ['Paid', 'Pending', 'Overdue'];
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: 430000 + ((i * 613000) % 2900000),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
const TITLE: Record<string, string> = { customer: 'Customer', status: 'Status', amount: 'Amount' };
const col = (id: string | null | undefined): string => (id ? (TITLE[id] ?? id) : '-');
// One click emits several events. You can listen separately for whether the selection changed (selectionChanged),
// whether focus moved (focusChanged), and whether a row (rowClicked) or a cell (cellClicked) was clicked.
export function setup(api: GridApi<Row>, log: (message: string) => void) {
const name = (key: unknown): string => api.getRowByKey(key as number)?.customer ?? String(key);
const offs = [
api.on('selectionChanged', (e) =>
log(
`Selection changed: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : 'none'}`,
),
),
api.on('focusChanged', (e) => log(`Focus: ${name(e.rowKey)} / ${col(e.columnId)}`)),
api.on('rowClicked', (e) =>
log(`Row click: ${name(e.rowKey)} (line ${e.rowIndex + 1} on screen)`),
),
api.on('cellClicked', (e) => log(`Cell click: ${col(e.columnId)} = ${String(e.value)}`)),
api.on('rowDoubleClicked', (e) => log(`Row double-click: ${name(e.rowKey)}`)),
api.on('headerClicked', (e) => log(`Header click: ${col(e.columnId)}`)),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectTwo: (api: GridApi<Row>) => api.setSelectedKeys([2, 3]),
// Setting the same selection again sends no selectionChanged, because nothing changed.
sameAgain: (api: GridApi<Row>) => api.setSelectedKeys(api.getSelectedKeys()),
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.selectTwo(api)"
>Select rows 2 and 3 (code)</button>
<button
type="button"
:disabled="!api"
@click="api && actions.sameAgain(api)"
>Set the same selection again</button>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear selection</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
customer: string;
status: string;
amount: number;
}
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harbor & Co.',
'Dawn Farms',
'Moda Fashion',
];
const statuses = ['Paid', 'Pending', 'Overdue'];
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: 430000 + ((i * 613000) % 2900000),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
const TITLE: Record<string, string> = { customer: 'Customer', status: 'Status', amount: 'Amount' };
const col = (id: string | null | undefined): string => (id ? (TITLE[id] ?? id) : '-');
// One click emits several events. You can listen separately for whether the selection changed (selectionChanged),
// whether focus moved (focusChanged), and whether a row (rowClicked) or a cell (cellClicked) was clicked.
export function setup(api: GridApi<Row>, log: (message: string) => void) {
const name = (key: unknown): string => api.getRowByKey(key as number)?.customer ?? String(key);
const offs = [
api.on('selectionChanged', (e) =>
log(
`Selection changed: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : 'none'}`,
),
),
api.on('focusChanged', (e) => log(`Focus: ${name(e.rowKey)} / ${col(e.columnId)}`)),
api.on('rowClicked', (e) =>
log(`Row click: ${name(e.rowKey)} (line ${e.rowIndex + 1} on screen)`),
),
api.on('cellClicked', (e) => log(`Cell click: ${col(e.columnId)} = ${String(e.value)}`)),
api.on('rowDoubleClicked', (e) => log(`Row double-click: ${name(e.rowKey)}`)),
api.on('headerClicked', (e) => log(`Header click: ${col(e.columnId)}`)),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectTwo: (api: GridApi<Row>) => api.setSelectedKeys([2, 3]),
// Setting the same selection again sends no selectionChanged, because nothing changed.
sameAgain: (api: GridApi<Row>) => api.setSelectedKeys(api.getSelectedKeys()),
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.selectTwo(api)"
>Select rows 2 and 3 (code)</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.sameAgain(api)"
>Set the same selection again</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear selection</button>
</div>
<mx-grid style="height: 330px" [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;
export interface Row {
id: number;
customer: string;
status: string;
amount: number;
}
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harbor & Co.',
'Dawn Farms',
'Moda Fashion',
];
const statuses = ['Paid', 'Pending', 'Overdue'];
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: 430000 + ((i * 613000) % 2900000),
})),
rowKey: 'id',
selection: { mode: 'multiple', checkbox: true },
};
const TITLE: Record<string, string> = { customer: 'Customer', status: 'Status', amount: 'Amount' };
const col = (id: string | null | undefined): string => (id ? (TITLE[id] ?? id) : '-');
// One click emits several events. You can listen separately for whether the selection changed (selectionChanged),
// whether focus moved (focusChanged), and whether a row (rowClicked) or a cell (cellClicked) was clicked.
export function setup(api: GridApi<Row>, log: (message: string) => void) {
const name = (key: unknown): string => api.getRowByKey(key as number)?.customer ?? String(key);
const offs = [
api.on('selectionChanged', (e) =>
log(
`Selection changed: ${e.selectedKeys.length ? e.selectedKeys.map(name).join(', ') : 'none'}`,
),
),
api.on('focusChanged', (e) => log(`Focus: ${name(e.rowKey)} / ${col(e.columnId)}`)),
api.on('rowClicked', (e) =>
log(`Row click: ${name(e.rowKey)} (line ${e.rowIndex + 1} on screen)`),
),
api.on('cellClicked', (e) => log(`Cell click: ${col(e.columnId)} = ${String(e.value)}`)),
api.on('rowDoubleClicked', (e) => log(`Row double-click: ${name(e.rowKey)}`)),
api.on('headerClicked', (e) => log(`Header click: ${col(e.columnId)}`)),
];
return () => offs.forEach((off) => off());
}
export const actions = {
selectTwo: (api: GridApi<Row>) => api.setSelectedKeys([2, 3]),
// Setting the same selection again sends no selectionChanged, because nothing changed.
sameAgain: (api: GridApi<Row>) => api.setSelectedKeys(api.getSelectedKeys()),
clear: (api: GridApi<Row>) => api.clearSelection(),
};