키보드로 행 넣고 지우기Add and remove rows with the keyboard
keyboardRows: true로 Insert는 새 행, Ctrl+Delete는 선택 행 삭제를 켜요. 새 행은 컬럼 기본값으로 채우고, 훅에는 source: 'keyboard'로 알려서 막거나 되물을 수 있어요.keyboardRows: true turns on Insert for a new row and Ctrl+Delete for removing the selected rows. The new row gets the column defaults, and hooks see source: 'keyboard' so you can veto or confirm.
코드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="focusFirst">첫 칸 포커스</button>
<button type="button" id="selectAll">모두 선택</button>
</div>
<div id="grid" style="height: 320px"></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('focusFirst').addEventListener('click', () => actions.focusFirst(api));
document.getElementById('selectAll').addEventListener('click', () => actions.selectAll(api));const en = document.documentElement.dataset.lang === 'en';
export const options = {
columns: [
{
id: 'task',
title: en ? 'Task' : '업무',
width: 200,
editable: true,
defaultValue: en ? 'New task' : '새 업무',
},
{
id: 'owner',
title: en ? 'Owner' : '담당',
width: 130,
editable: true,
defaultValue: en ? 'TBD' : '미정',
},
],
rows: [
{ id: 1, task: en ? 'Improve login' : '로그인 개선', owner: en ? 'Minjun Kim' : '김민준' },
{ id: 2, task: en ? 'Check export' : '내보내기 점검', owner: en ? 'Seoyeon Lee' : '이서연' },
{ id: 3, task: en ? 'Dark mode' : '다크 모드', owner: en ? 'Jiho Park' : '박지호' },
],
rowKey: 'id',
selection: 'multiple',
// keyboardRows: true는 Insert(또는 Ctrl+더하기)로 행 넣기, Ctrl+Delete(Mac은 ⌘+Backspace)로 지우기를 켜요.
keyboardRows: true,
hooks: {
// source: 'keyboard'면 키보드에서 온 요청이에요. 3행 이상 한꺼번에 지우는 것만 막아 봤어요.
beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
},
ariaLabel: en ? 'Add and remove rows with the keyboard' : '키보드로 행 넣고 지우기',
};
export function setup(api, log) {
log({
ko: '칸을 하나 누른 뒤 Insert를 눌러 보세요. 그 행 뒤에 새 행이 생기고 첫 칸 편집이 시작돼요. Ctrl+Delete는 고른 행(없으면 포커스 행)을 지워요.',
en: 'Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).',
});
const offs = [
api.on('rowsChanged', (e) => log({
ko: `행 ${e.reason === 'add' ? '추가' : e.reason === 'remove' ? '삭제' : e.reason} ${e.count}개 → 전체 ${api.getRowCount()}행`,
en: `Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`,
})),
];
return () => offs.forEach((off) => off());
}
export const actions = {
focusFirst: (api) => {
api.focusCell(1, 'task');
// 버튼이 DOM 포커스를 쥐고 있으면 Insert 키가 그리드에 닿지 않아요. 그리드로 DOM 포커스도 옮겨요.
document.querySelector('.mxg')?.focus({ preventScroll: true });
},
selectAll: (api) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};<!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="focusFirst">첫 칸 포커스</button>
<button type="button" id="selectAll">모두 선택</button>
</div>
<div id="grid" style="height: 320px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const en = document.documentElement.dataset.lang === 'en';
const options = {
columns: [
{
id: 'task',
title: en ? 'Task' : '업무',
width: 200,
editable: true,
defaultValue: en ? 'New task' : '새 업무',
},
{
id: 'owner',
title: en ? 'Owner' : '담당',
width: 130,
editable: true,
defaultValue: en ? 'TBD' : '미정',
},
],
rows: [
{ id: 1, task: en ? 'Improve login' : '로그인 개선', owner: en ? 'Minjun Kim' : '김민준' },
{ id: 2, task: en ? 'Check export' : '내보내기 점검', owner: en ? 'Seoyeon Lee' : '이서연' },
{ id: 3, task: en ? 'Dark mode' : '다크 모드', owner: en ? 'Jiho Park' : '박지호' },
],
rowKey: 'id',
selection: 'multiple',
// keyboardRows: true는 Insert(또는 Ctrl+더하기)로 행 넣기, Ctrl+Delete(Mac은 ⌘+Backspace)로 지우기를 켜요.
keyboardRows: true,
hooks: {
// source: 'keyboard'면 키보드에서 온 요청이에요. 3행 이상 한꺼번에 지우는 것만 막아 봤어요.
beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
},
ariaLabel: en ? 'Add and remove rows with the keyboard' : '키보드로 행 넣고 지우기',
};
function setup(api, log) {
log({
ko: '칸을 하나 누른 뒤 Insert를 눌러 보세요. 그 행 뒤에 새 행이 생기고 첫 칸 편집이 시작돼요. Ctrl+Delete는 고른 행(없으면 포커스 행)을 지워요.',
en: 'Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).',
});
const offs = [
api.on('rowsChanged', (e) => log({
ko: `행 ${e.reason === 'add' ? '추가' : e.reason === 'remove' ? '삭제' : e.reason} ${e.count}개 → 전체 ${api.getRowCount()}행`,
en: `Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`,
})),
];
return () => offs.forEach((off) => off());
}
const actions = {
focusFirst: (api) => {
api.focusCell(1, 'task');
// 버튼이 DOM 포커스를 쥐고 있으면 Insert 키가 그리드에 닿지 않아요. 그리드로 DOM 포커스도 옮겨요.
document.querySelector('.mxg')?.focus({ preventScroll: true });
},
selectAll: (api) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};
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('focusFirst').addEventListener('click', () => actions.focusFirst(api));
document.getElementById('selectAll').addEventListener('click', () => actions.selectAll(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.focusFirst(api)}
>첫 칸 포커스</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.selectAll(api)}
>모두 선택</button>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
const en = document.documentElement.dataset.lang === 'en';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
task: string;
owner: string;
}
export const options: GridOptions<Row> = {
columns: [
{
id: 'task',
title: en ? 'Task' : '업무',
width: 200,
editable: true,
defaultValue: en ? 'New task' : '새 업무',
},
{
id: 'owner',
title: en ? 'Owner' : '담당',
width: 130,
editable: true,
defaultValue: en ? 'TBD' : '미정',
},
],
rows: [
{ id: 1, task: en ? 'Improve login' : '로그인 개선', owner: en ? 'Minjun Kim' : '김민준' },
{ id: 2, task: en ? 'Check export' : '내보내기 점검', owner: en ? 'Seoyeon Lee' : '이서연' },
{ id: 3, task: en ? 'Dark mode' : '다크 모드', owner: en ? 'Jiho Park' : '박지호' },
],
rowKey: 'id',
selection: 'multiple',
// keyboardRows: true는 Insert(또는 Ctrl+더하기)로 행 넣기, Ctrl+Delete(Mac은 ⌘+Backspace)로 지우기를 켜요.
keyboardRows: true,
hooks: {
// source: 'keyboard'면 키보드에서 온 요청이에요. 3행 이상 한꺼번에 지우는 것만 막아 봤어요.
beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
},
ariaLabel: en ? 'Add and remove rows with the keyboard' : '키보드로 행 넣고 지우기',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '칸을 하나 누른 뒤 Insert를 눌러 보세요. 그 행 뒤에 새 행이 생기고 첫 칸 편집이 시작돼요. Ctrl+Delete는 고른 행(없으면 포커스 행)을 지워요.',
en: 'Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).',
});
const offs = [
api.on('rowsChanged', (e) =>
log({
ko: `행 ${e.reason === 'add' ? '추가' : e.reason === 'remove' ? '삭제' : e.reason} ${e.count}개 → 전체 ${api.getRowCount()}행`,
en: `Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`,
}),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
focusFirst: (api: GridApi<Row>) => {
api.focusCell(1, 'task');
// 버튼이 DOM 포커스를 쥐고 있으면 Insert 키가 그리드에 닿지 않아요. 그리드로 DOM 포커스도 옮겨요.
document.querySelector<HTMLElement>('.mxg')?.focus({ preventScroll: true });
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};버튼을 누르면 이 예제의 코드가 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.focusFirst(api)"
>첫 칸 포커스</button>
<button
type="button"
:disabled="!api"
@click="api && actions.selectAll(api)"
>모두 선택</button>
</div>
<Grid style="height: 320px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
const en = document.documentElement.dataset.lang === 'en';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
task: string;
owner: string;
}
export const options: GridOptions<Row> = {
columns: [
{
id: 'task',
title: en ? 'Task' : '업무',
width: 200,
editable: true,
defaultValue: en ? 'New task' : '새 업무',
},
{
id: 'owner',
title: en ? 'Owner' : '담당',
width: 130,
editable: true,
defaultValue: en ? 'TBD' : '미정',
},
],
rows: [
{ id: 1, task: en ? 'Improve login' : '로그인 개선', owner: en ? 'Minjun Kim' : '김민준' },
{ id: 2, task: en ? 'Check export' : '내보내기 점검', owner: en ? 'Seoyeon Lee' : '이서연' },
{ id: 3, task: en ? 'Dark mode' : '다크 모드', owner: en ? 'Jiho Park' : '박지호' },
],
rowKey: 'id',
selection: 'multiple',
// keyboardRows: true는 Insert(또는 Ctrl+더하기)로 행 넣기, Ctrl+Delete(Mac은 ⌘+Backspace)로 지우기를 켜요.
keyboardRows: true,
hooks: {
// source: 'keyboard'면 키보드에서 온 요청이에요. 3행 이상 한꺼번에 지우는 것만 막아 봤어요.
beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
},
ariaLabel: en ? 'Add and remove rows with the keyboard' : '키보드로 행 넣고 지우기',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '칸을 하나 누른 뒤 Insert를 눌러 보세요. 그 행 뒤에 새 행이 생기고 첫 칸 편집이 시작돼요. Ctrl+Delete는 고른 행(없으면 포커스 행)을 지워요.',
en: 'Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).',
});
const offs = [
api.on('rowsChanged', (e) =>
log({
ko: `행 ${e.reason === 'add' ? '추가' : e.reason === 'remove' ? '삭제' : e.reason} ${e.count}개 → 전체 ${api.getRowCount()}행`,
en: `Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`,
}),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
focusFirst: (api: GridApi<Row>) => {
api.focusCell(1, 'task');
// 버튼이 DOM 포커스를 쥐고 있으면 Insert 키가 그리드에 닿지 않아요. 그리드로 DOM 포커스도 옮겨요.
document.querySelector<HTMLElement>('.mxg')?.focus({ preventScroll: true });
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};버튼을 누르면 이 예제의 코드가 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.focusFirst(api)"
>첫 칸 포커스</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.selectAll(api)"
>모두 선택</button>
</div>
<mx-grid style="height: 320px" [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';
const en = document.documentElement.dataset.lang === 'en';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
task: string;
owner: string;
}
export const options: GridOptions<Row> = {
columns: [
{
id: 'task',
title: en ? 'Task' : '업무',
width: 200,
editable: true,
defaultValue: en ? 'New task' : '새 업무',
},
{
id: 'owner',
title: en ? 'Owner' : '담당',
width: 130,
editable: true,
defaultValue: en ? 'TBD' : '미정',
},
],
rows: [
{ id: 1, task: en ? 'Improve login' : '로그인 개선', owner: en ? 'Minjun Kim' : '김민준' },
{ id: 2, task: en ? 'Check export' : '내보내기 점검', owner: en ? 'Seoyeon Lee' : '이서연' },
{ id: 3, task: en ? 'Dark mode' : '다크 모드', owner: en ? 'Jiho Park' : '박지호' },
],
rowKey: 'id',
selection: 'multiple',
// keyboardRows: true는 Insert(또는 Ctrl+더하기)로 행 넣기, Ctrl+Delete(Mac은 ⌘+Backspace)로 지우기를 켜요.
keyboardRows: true,
hooks: {
// source: 'keyboard'면 키보드에서 온 요청이에요. 3행 이상 한꺼번에 지우는 것만 막아 봤어요.
beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
},
ariaLabel: en ? 'Add and remove rows with the keyboard' : '키보드로 행 넣고 지우기',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '칸을 하나 누른 뒤 Insert를 눌러 보세요. 그 행 뒤에 새 행이 생기고 첫 칸 편집이 시작돼요. Ctrl+Delete는 고른 행(없으면 포커스 행)을 지워요.',
en: 'Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).',
});
const offs = [
api.on('rowsChanged', (e) =>
log({
ko: `행 ${e.reason === 'add' ? '추가' : e.reason === 'remove' ? '삭제' : e.reason} ${e.count}개 → 전체 ${api.getRowCount()}행`,
en: `Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`,
}),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
focusFirst: (api: GridApi<Row>) => {
api.focusCell(1, 'task');
// 버튼이 DOM 포커스를 쥐고 있으면 Insert 키가 그리드에 닿지 않아요. 그리드로 DOM 포커스도 옮겨요.
document.querySelector<HTMLElement>('.mxg')?.focus({ preventScroll: true });
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};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="focusFirst">Focus first cell</button>
<button type="button" id="selectAll">Select all</button>
</div>
<div id="grid" style="height: 320px"></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('focusFirst').addEventListener('click', () => actions.focusFirst(api));
document.getElementById('selectAll').addEventListener('click', () => actions.selectAll(api));export const options = {
columns: [
{
id: 'task',
title: 'Task',
width: 200,
editable: true,
defaultValue: 'New task',
},
{
id: 'owner',
title: 'Owner',
width: 130,
editable: true,
defaultValue: 'TBD',
},
],
rows: [
{ id: 1, task: 'Improve login', owner: 'Liam Carter' },
{ id: 2, task: 'Check export', owner: 'Emma Stone' },
{ id: 3, task: 'Dark mode', owner: 'Noah Kim' },
],
rowKey: 'id',
selection: 'multiple',
// keyboardRows: true turns on inserting a row with Insert (or Ctrl+Plus) and removing with Ctrl+Delete (⌘+Backspace on Mac).
keyboardRows: true,
hooks: {
// source: 'keyboard' means the request came from the keyboard. Only removing 3 or more rows at once is blocked, as a trial.
beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
},
ariaLabel: 'Add and remove rows with the keyboard',
};
export function setup(api, log) {
log('Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).');
const offs = [
api.on('rowsChanged', (e) => log(`Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`)),
];
return () => offs.forEach((off) => off());
}
export const actions = {
focusFirst: (api) => {
api.focusCell(1, 'task');
// If a button holds the DOM focus, the Insert key does not reach the grid. Move the DOM focus to the grid as well.
document.querySelector('.mxg')?.focus({ preventScroll: true });
},
selectAll: (api) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Add and remove rows with the keyboard</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="focusFirst">Focus first cell</button>
<button type="button" id="selectAll">Select all</button>
</div>
<div id="grid" style="height: 320px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const options = {
columns: [
{
id: 'task',
title: 'Task',
width: 200,
editable: true,
defaultValue: 'New task',
},
{
id: 'owner',
title: 'Owner',
width: 130,
editable: true,
defaultValue: 'TBD',
},
],
rows: [
{ id: 1, task: 'Improve login', owner: 'Liam Carter' },
{ id: 2, task: 'Check export', owner: 'Emma Stone' },
{ id: 3, task: 'Dark mode', owner: 'Noah Kim' },
],
rowKey: 'id',
selection: 'multiple',
// keyboardRows: true turns on inserting a row with Insert (or Ctrl+Plus) and removing with Ctrl+Delete (⌘+Backspace on Mac).
keyboardRows: true,
hooks: {
// source: 'keyboard' means the request came from the keyboard. Only removing 3 or more rows at once is blocked, as a trial.
beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
},
ariaLabel: 'Add and remove rows with the keyboard',
};
function setup(api, log) {
log('Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).');
const offs = [
api.on('rowsChanged', (e) => log(`Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`)),
];
return () => offs.forEach((off) => off());
}
const actions = {
focusFirst: (api) => {
api.focusCell(1, 'task');
// If a button holds the DOM focus, the Insert key does not reach the grid. Move the DOM focus to the grid as well.
document.querySelector('.mxg')?.focus({ preventScroll: true });
},
selectAll: (api) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};
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('focusFirst').addEventListener('click', () => actions.focusFirst(api));
document.getElementById('selectAll').addEventListener('click', () => actions.selectAll(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.focusFirst(api)}
>Focus first cell</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.selectAll(api)}
>Select all</button>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
task: string;
owner: string;
}
export const options: GridOptions<Row> = {
columns: [
{
id: 'task',
title: 'Task',
width: 200,
editable: true,
defaultValue: 'New task',
},
{
id: 'owner',
title: 'Owner',
width: 130,
editable: true,
defaultValue: 'TBD',
},
],
rows: [
{ id: 1, task: 'Improve login', owner: 'Liam Carter' },
{ id: 2, task: 'Check export', owner: 'Emma Stone' },
{ id: 3, task: 'Dark mode', owner: 'Noah Kim' },
],
rowKey: 'id',
selection: 'multiple',
// keyboardRows: true turns on inserting a row with Insert (or Ctrl+Plus) and removing with Ctrl+Delete (⌘+Backspace on Mac).
keyboardRows: true,
hooks: {
// source: 'keyboard' means the request came from the keyboard. Only removing 3 or more rows at once is blocked, as a trial.
beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
},
ariaLabel: 'Add and remove rows with the keyboard',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).',
);
const offs = [
api.on('rowsChanged', (e) =>
log(`Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
focusFirst: (api: GridApi<Row>) => {
api.focusCell(1, 'task');
// If a button holds the DOM focus, the Insert key does not reach the grid. Move the DOM focus to the grid as well.
document.querySelector<HTMLElement>('.mxg')?.focus({ preventScroll: true });
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};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.focusFirst(api)"
>Focus first cell</button>
<button
type="button"
:disabled="!api"
@click="api && actions.selectAll(api)"
>Select all</button>
</div>
<Grid style="height: 320px" :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;
task: string;
owner: string;
}
export const options: GridOptions<Row> = {
columns: [
{
id: 'task',
title: 'Task',
width: 200,
editable: true,
defaultValue: 'New task',
},
{
id: 'owner',
title: 'Owner',
width: 130,
editable: true,
defaultValue: 'TBD',
},
],
rows: [
{ id: 1, task: 'Improve login', owner: 'Liam Carter' },
{ id: 2, task: 'Check export', owner: 'Emma Stone' },
{ id: 3, task: 'Dark mode', owner: 'Noah Kim' },
],
rowKey: 'id',
selection: 'multiple',
// keyboardRows: true turns on inserting a row with Insert (or Ctrl+Plus) and removing with Ctrl+Delete (⌘+Backspace on Mac).
keyboardRows: true,
hooks: {
// source: 'keyboard' means the request came from the keyboard. Only removing 3 or more rows at once is blocked, as a trial.
beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
},
ariaLabel: 'Add and remove rows with the keyboard',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).',
);
const offs = [
api.on('rowsChanged', (e) =>
log(`Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
focusFirst: (api: GridApi<Row>) => {
api.focusCell(1, 'task');
// If a button holds the DOM focus, the Insert key does not reach the grid. Move the DOM focus to the grid as well.
document.querySelector<HTMLElement>('.mxg')?.focus({ preventScroll: true });
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};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.focusFirst(api)"
>Focus first cell</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.selectAll(api)"
>Select all</button>
</div>
<mx-grid style="height: 320px" [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;
task: string;
owner: string;
}
export const options: GridOptions<Row> = {
columns: [
{
id: 'task',
title: 'Task',
width: 200,
editable: true,
defaultValue: 'New task',
},
{
id: 'owner',
title: 'Owner',
width: 130,
editable: true,
defaultValue: 'TBD',
},
],
rows: [
{ id: 1, task: 'Improve login', owner: 'Liam Carter' },
{ id: 2, task: 'Check export', owner: 'Emma Stone' },
{ id: 3, task: 'Dark mode', owner: 'Noah Kim' },
],
rowKey: 'id',
selection: 'multiple',
// keyboardRows: true turns on inserting a row with Insert (or Ctrl+Plus) and removing with Ctrl+Delete (⌘+Backspace on Mac).
keyboardRows: true,
hooks: {
// source: 'keyboard' means the request came from the keyboard. Only removing 3 or more rows at once is blocked, as a trial.
beforeRemoveRows: ({ source, keys }) => !(source === 'keyboard' && keys.length >= 3),
},
ariaLabel: 'Add and remove rows with the keyboard',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Click a cell and press Insert. A new row appears after it and its first cell starts editing. Ctrl+Delete removes the selected rows (or the focused row).',
);
const offs = [
api.on('rowsChanged', (e) =>
log(`Rows ${e.reason} ${e.count} → ${api.getRowCount()} in total`),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
focusFirst: (api: GridApi<Row>) => {
api.focusCell(1, 'task');
// If a button holds the DOM focus, the Insert key does not reach the grid. Move the DOM focus to the grid as well.
document.querySelector<HTMLElement>('.mxg')?.focus({ preventScroll: true });
},
selectAll: (api: GridApi<Row>) => api.setSelectedKeys(api.getRows().map((r) => r.id)),
};