클릭한 칸 찾기와 그려진 줄 범위Find the clicked cell and the rendered line range
어디를 눌러도 locateCell(event)로 칸을 찾고 getCellText로 화면 글자를 읽어요. getVisibleRange, getTopVisibleIndex로 지금 그려진 줄을 알고, 창 밖 칸은 getCellElement가 null이에요.Click anywhere and find the cell with locateCell(event), then read its displayed text with getCellText. getVisibleRange and getTopVisibleIndex tell which lines are rendered, and getCellElement returns null for a cell outside the window.
코드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="probe">그려진 칸 확인</button>
<button type="button" id="end">맨 끝으로 가기</button>
</div>
<div id="grid" style="height: 400px"></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('probe').addEventListener('click', () => actions.probe(api));
document.getElementById('end').addEventListener('click', () => actions.end(api));// 이벤트가 없는 곳을 눌러도 locateCell(event)로 어느 칸인지 알 수 있어요. 그리드 밖이나 헤더면 null이에요.
export const options = {
columns: [
{ id: 'name', title: '상품', width: 180 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `${Number(value).toLocaleString('ko-KR')}원`,
},
],
rows: Array.from({ length: 300 }, (_, i) => ({
id: i + 1,
name: `상품 ${i + 1}`,
price: 1000 + ((i * 731) % 90) * 100,
})),
rowKey: 'id',
};
let say = () => { };
export function setup(api, log) {
say = log;
const onClick = (event) => {
const cell = api.locateCell(event);
if (cell === null) {
log({
ko: '칸이 아닌 곳을 눌렀어요(헤더나 빈 곳).',
en: 'Clicked outside a cell (header or empty area).',
});
return;
}
const text = api.getCellText(cell.rowKey, cell.columnId);
log({
ko: `${cell.rowKey}번 행 ${cell.columnId}: "${text}"`,
en: `Row ${cell.rowKey} ${cell.columnId}: "${text}"`,
});
};
const element = api.getGridElement();
element.addEventListener('click', onClick);
const offScroll = api.on('scrolled', () => {
const { first, last } = api.getVisibleRange();
log({
ko: `그려진 줄 ${first}~${last}, 맨 위에 보이는 줄 ${api.getTopVisibleIndex()}`,
en: `Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`,
});
});
log({
ko: '아무 칸이나 눌러 보고, 스크롤해 보세요. 가려진 줄의 칸은 getCellElement가 null이에요.',
en: 'Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.',
});
return () => {
element.removeEventListener('click', onClick);
offScroll();
};
}
export const actions = {
probe: (api) => {
const word = (key) => api.getCellElement(key, 'name') === null ? '그려져 있지 않아요(null)' : '그려져 있어요';
const wordEn = (key) => api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
say({
ko: `1번 행 칸: ${word(1)} / 300번 행 칸: ${word(300)}`,
en: `Row 1 cell: ${wordEn(1)} / row 300 cell: ${wordEn(300)}`,
});
},
end: (api) => api.scrollToIndex(299),
};<!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="probe">그려진 칸 확인</button>
<button type="button" id="end">맨 끝으로 가기</button>
</div>
<div id="grid" style="height: 400px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 이벤트가 없는 곳을 눌러도 locateCell(event)로 어느 칸인지 알 수 있어요. 그리드 밖이나 헤더면 null이에요.
const options = {
columns: [
{ id: 'name', title: '상품', width: 180 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `${Number(value).toLocaleString('ko-KR')}원`,
},
],
rows: Array.from({ length: 300 }, (_, i) => ({
id: i + 1,
name: `상품 ${i + 1}`,
price: 1000 + ((i * 731) % 90) * 100,
})),
rowKey: 'id',
};
let say = () => { };
function setup(api, log) {
say = log;
const onClick = (event) => {
const cell = api.locateCell(event);
if (cell === null) {
log({
ko: '칸이 아닌 곳을 눌렀어요(헤더나 빈 곳).',
en: 'Clicked outside a cell (header or empty area).',
});
return;
}
const text = api.getCellText(cell.rowKey, cell.columnId);
log({
ko: `${cell.rowKey}번 행 ${cell.columnId}: "${text}"`,
en: `Row ${cell.rowKey} ${cell.columnId}: "${text}"`,
});
};
const element = api.getGridElement();
element.addEventListener('click', onClick);
const offScroll = api.on('scrolled', () => {
const { first, last } = api.getVisibleRange();
log({
ko: `그려진 줄 ${first}~${last}, 맨 위에 보이는 줄 ${api.getTopVisibleIndex()}`,
en: `Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`,
});
});
log({
ko: '아무 칸이나 눌러 보고, 스크롤해 보세요. 가려진 줄의 칸은 getCellElement가 null이에요.',
en: 'Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.',
});
return () => {
element.removeEventListener('click', onClick);
offScroll();
};
}
const actions = {
probe: (api) => {
const word = (key) => api.getCellElement(key, 'name') === null ? '그려져 있지 않아요(null)' : '그려져 있어요';
const wordEn = (key) => api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
say({
ko: `1번 행 칸: ${word(1)} / 300번 행 칸: ${word(300)}`,
en: `Row 1 cell: ${wordEn(1)} / row 300 cell: ${wordEn(300)}`,
});
},
end: (api) => api.scrollToIndex(299),
};
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('probe').addEventListener('click', () => actions.probe(api));
document.getElementById('end').addEventListener('click', () => actions.end(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.probe(api)}
>그려진 칸 확인</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.end(api)}
>맨 끝으로 가기</button>
</div>
<Grid style={{ height: 400 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
price: number;
}
// 이벤트가 없는 곳을 눌러도 locateCell(event)로 어느 칸인지 알 수 있어요. 그리드 밖이나 헤더면 null이에요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '상품', width: 180 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `${Number(value).toLocaleString('ko-KR')}원`,
},
],
rows: Array.from({ length: 300 }, (_, i) => ({
id: i + 1,
name: `상품 ${i + 1}`,
price: 1000 + ((i * 731) % 90) * 100,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const onClick = (event: MouseEvent): void => {
const cell = api.locateCell(event);
if (cell === null) {
log({
ko: '칸이 아닌 곳을 눌렀어요(헤더나 빈 곳).',
en: 'Clicked outside a cell (header or empty area).',
});
return;
}
const text = api.getCellText(cell.rowKey, cell.columnId);
log({
ko: `${cell.rowKey}번 행 ${cell.columnId}: "${text}"`,
en: `Row ${cell.rowKey} ${cell.columnId}: "${text}"`,
});
};
const element = api.getGridElement();
element.addEventListener('click', onClick);
const offScroll = api.on('scrolled', () => {
const { first, last } = api.getVisibleRange();
log({
ko: `그려진 줄 ${first}~${last}, 맨 위에 보이는 줄 ${api.getTopVisibleIndex()}`,
en: `Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`,
});
});
log({
ko: '아무 칸이나 눌러 보고, 스크롤해 보세요. 가려진 줄의 칸은 getCellElement가 null이에요.',
en: 'Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.',
});
return () => {
element.removeEventListener('click', onClick);
offScroll();
};
}
export const actions = {
probe: (api: GridApi<Row>) => {
const word = (key: number): string =>
api.getCellElement(key, 'name') === null ? '그려져 있지 않아요(null)' : '그려져 있어요';
const wordEn = (key: number): string =>
api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
say({
ko: `1번 행 칸: ${word(1)} / 300번 행 칸: ${word(300)}`,
en: `Row 1 cell: ${wordEn(1)} / row 300 cell: ${wordEn(300)}`,
});
},
end: (api: GridApi<Row>) => api.scrollToIndex(299),
};버튼을 누르면 이 예제의 코드가 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.probe(api)">그려진 칸 확인</button>
<button type="button" :disabled="!api" @click="api && actions.end(api)">맨 끝으로 가기</button>
</div>
<Grid style="height: 400px" :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;
name: string;
price: number;
}
// 이벤트가 없는 곳을 눌러도 locateCell(event)로 어느 칸인지 알 수 있어요. 그리드 밖이나 헤더면 null이에요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '상품', width: 180 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `${Number(value).toLocaleString('ko-KR')}원`,
},
],
rows: Array.from({ length: 300 }, (_, i) => ({
id: i + 1,
name: `상품 ${i + 1}`,
price: 1000 + ((i * 731) % 90) * 100,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const onClick = (event: MouseEvent): void => {
const cell = api.locateCell(event);
if (cell === null) {
log({
ko: '칸이 아닌 곳을 눌렀어요(헤더나 빈 곳).',
en: 'Clicked outside a cell (header or empty area).',
});
return;
}
const text = api.getCellText(cell.rowKey, cell.columnId);
log({
ko: `${cell.rowKey}번 행 ${cell.columnId}: "${text}"`,
en: `Row ${cell.rowKey} ${cell.columnId}: "${text}"`,
});
};
const element = api.getGridElement();
element.addEventListener('click', onClick);
const offScroll = api.on('scrolled', () => {
const { first, last } = api.getVisibleRange();
log({
ko: `그려진 줄 ${first}~${last}, 맨 위에 보이는 줄 ${api.getTopVisibleIndex()}`,
en: `Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`,
});
});
log({
ko: '아무 칸이나 눌러 보고, 스크롤해 보세요. 가려진 줄의 칸은 getCellElement가 null이에요.',
en: 'Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.',
});
return () => {
element.removeEventListener('click', onClick);
offScroll();
};
}
export const actions = {
probe: (api: GridApi<Row>) => {
const word = (key: number): string =>
api.getCellElement(key, 'name') === null ? '그려져 있지 않아요(null)' : '그려져 있어요';
const wordEn = (key: number): string =>
api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
say({
ko: `1번 행 칸: ${word(1)} / 300번 행 칸: ${word(300)}`,
en: `Row 1 cell: ${wordEn(1)} / row 300 cell: ${wordEn(300)}`,
});
},
end: (api: GridApi<Row>) => api.scrollToIndex(299),
};버튼을 누르면 이 예제의 코드가 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.probe(api)"
>그려진 칸 확인</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.end(api)"
>맨 끝으로 가기</button>
</div>
<mx-grid style="height: 400px" [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;
name: string;
price: number;
}
// 이벤트가 없는 곳을 눌러도 locateCell(event)로 어느 칸인지 알 수 있어요. 그리드 밖이나 헤더면 null이에요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '상품', width: 180 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `${Number(value).toLocaleString('ko-KR')}원`,
},
],
rows: Array.from({ length: 300 }, (_, i) => ({
id: i + 1,
name: `상품 ${i + 1}`,
price: 1000 + ((i * 731) % 90) * 100,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const onClick = (event: MouseEvent): void => {
const cell = api.locateCell(event);
if (cell === null) {
log({
ko: '칸이 아닌 곳을 눌렀어요(헤더나 빈 곳).',
en: 'Clicked outside a cell (header or empty area).',
});
return;
}
const text = api.getCellText(cell.rowKey, cell.columnId);
log({
ko: `${cell.rowKey}번 행 ${cell.columnId}: "${text}"`,
en: `Row ${cell.rowKey} ${cell.columnId}: "${text}"`,
});
};
const element = api.getGridElement();
element.addEventListener('click', onClick);
const offScroll = api.on('scrolled', () => {
const { first, last } = api.getVisibleRange();
log({
ko: `그려진 줄 ${first}~${last}, 맨 위에 보이는 줄 ${api.getTopVisibleIndex()}`,
en: `Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`,
});
});
log({
ko: '아무 칸이나 눌러 보고, 스크롤해 보세요. 가려진 줄의 칸은 getCellElement가 null이에요.',
en: 'Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.',
});
return () => {
element.removeEventListener('click', onClick);
offScroll();
};
}
export const actions = {
probe: (api: GridApi<Row>) => {
const word = (key: number): string =>
api.getCellElement(key, 'name') === null ? '그려져 있지 않아요(null)' : '그려져 있어요';
const wordEn = (key: number): string =>
api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
say({
ko: `1번 행 칸: ${word(1)} / 300번 행 칸: ${word(300)}`,
en: `Row 1 cell: ${wordEn(1)} / row 300 cell: ${wordEn(300)}`,
});
},
end: (api: GridApi<Row>) => api.scrollToIndex(299),
};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="probe">Check rendered cells</button>
<button type="button" id="end">Go to the end</button>
</div>
<div id="grid" style="height: 400px"></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('probe').addEventListener('click', () => actions.probe(api));
document.getElementById('end').addEventListener('click', () => actions.end(api));// Even where there is no event, locateCell(event) tells which cell a click hit. It returns null outside the grid or on the header.
export const options = {
columns: [
{ id: 'name', title: 'Product', width: 180 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US', { maximumFractionDigits: 1 })}`,
},
],
rows: Array.from({ length: 300 }, (_, i) => ({
id: i + 1,
name: `Product ${i + 1}`,
price: 1 + ((i * 731) % 90) / 10,
})),
rowKey: 'id',
};
let say = () => { };
export function setup(api, log) {
say = log;
const onClick = (event) => {
const cell = api.locateCell(event);
if (cell === null) {
log('Clicked outside a cell (header or empty area).');
return;
}
const text = api.getCellText(cell.rowKey, cell.columnId);
log(`Row ${cell.rowKey} ${cell.columnId}: "${text}"`);
};
const element = api.getGridElement();
element.addEventListener('click', onClick);
const offScroll = api.on('scrolled', () => {
const { first, last } = api.getVisibleRange();
log(`Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`);
});
log('Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.');
return () => {
element.removeEventListener('click', onClick);
offScroll();
};
}
export const actions = {
probe: (api) => {
const word = (key) => api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
say(`Row 1 cell: ${word(1)} / row 300 cell: ${word(300)}`);
},
end: (api) => api.scrollToIndex(299),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Find the clicked cell and the rendered line range</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="probe">Check rendered cells</button>
<button type="button" id="end">Go to the end</button>
</div>
<div id="grid" style="height: 400px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// Even where there is no event, locateCell(event) tells which cell a click hit. It returns null outside the grid or on the header.
const options = {
columns: [
{ id: 'name', title: 'Product', width: 180 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => `$${Number(value).toLocaleString('en-US', { maximumFractionDigits: 1 })}`,
},
],
rows: Array.from({ length: 300 }, (_, i) => ({
id: i + 1,
name: `Product ${i + 1}`,
price: 1 + ((i * 731) % 90) / 10,
})),
rowKey: 'id',
};
let say = () => { };
function setup(api, log) {
say = log;
const onClick = (event) => {
const cell = api.locateCell(event);
if (cell === null) {
log('Clicked outside a cell (header or empty area).');
return;
}
const text = api.getCellText(cell.rowKey, cell.columnId);
log(`Row ${cell.rowKey} ${cell.columnId}: "${text}"`);
};
const element = api.getGridElement();
element.addEventListener('click', onClick);
const offScroll = api.on('scrolled', () => {
const { first, last } = api.getVisibleRange();
log(`Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`);
});
log('Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.');
return () => {
element.removeEventListener('click', onClick);
offScroll();
};
}
const actions = {
probe: (api) => {
const word = (key) => api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
say(`Row 1 cell: ${word(1)} / row 300 cell: ${word(300)}`);
},
end: (api) => api.scrollToIndex(299),
};
options.ariaLabel = "Find the clicked cell and the rendered line range";
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('probe').addEventListener('click', () => actions.probe(api));
document.getElementById('end').addEventListener('click', () => actions.end(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.probe(api)}
>Check rendered cells</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.end(api)}
>Go to the end</button>
</div>
<Grid style={{ height: 400 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
price: number;
}
// Even where there is no event, locateCell(event) tells which cell a click hit. It returns null outside the grid or on the header.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Product', width: 180 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) =>
`$${Number(value).toLocaleString('en-US', { maximumFractionDigits: 1 })}`,
},
],
rows: Array.from({ length: 300 }, (_, i) => ({
id: i + 1,
name: `Product ${i + 1}`,
price: 1 + ((i * 731) % 90) / 10,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const onClick = (event: MouseEvent): void => {
const cell = api.locateCell(event);
if (cell === null) {
log('Clicked outside a cell (header or empty area).');
return;
}
const text = api.getCellText(cell.rowKey, cell.columnId);
log(`Row ${cell.rowKey} ${cell.columnId}: "${text}"`);
};
const element = api.getGridElement();
element.addEventListener('click', onClick);
const offScroll = api.on('scrolled', () => {
const { first, last } = api.getVisibleRange();
log(`Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`);
});
log('Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.');
return () => {
element.removeEventListener('click', onClick);
offScroll();
};
}
export const actions = {
probe: (api: GridApi<Row>) => {
const word = (key: number): string =>
api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
say(`Row 1 cell: ${word(1)} / row 300 cell: ${word(300)}`);
},
end: (api: GridApi<Row>) => api.scrollToIndex(299),
};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.probe(api)">Check rendered cells</button>
<button type="button" :disabled="!api" @click="api && actions.end(api)">Go to the end</button>
</div>
<Grid style="height: 400px" :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;
name: string;
price: number;
}
// Even where there is no event, locateCell(event) tells which cell a click hit. It returns null outside the grid or on the header.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Product', width: 180 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) =>
`$${Number(value).toLocaleString('en-US', { maximumFractionDigits: 1 })}`,
},
],
rows: Array.from({ length: 300 }, (_, i) => ({
id: i + 1,
name: `Product ${i + 1}`,
price: 1 + ((i * 731) % 90) / 10,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const onClick = (event: MouseEvent): void => {
const cell = api.locateCell(event);
if (cell === null) {
log('Clicked outside a cell (header or empty area).');
return;
}
const text = api.getCellText(cell.rowKey, cell.columnId);
log(`Row ${cell.rowKey} ${cell.columnId}: "${text}"`);
};
const element = api.getGridElement();
element.addEventListener('click', onClick);
const offScroll = api.on('scrolled', () => {
const { first, last } = api.getVisibleRange();
log(`Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`);
});
log('Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.');
return () => {
element.removeEventListener('click', onClick);
offScroll();
};
}
export const actions = {
probe: (api: GridApi<Row>) => {
const word = (key: number): string =>
api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
say(`Row 1 cell: ${word(1)} / row 300 cell: ${word(300)}`);
},
end: (api: GridApi<Row>) => api.scrollToIndex(299),
};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.probe(api)"
>Check rendered cells</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.end(api)"
>Go to the end</button>
</div>
<mx-grid style="height: 400px" [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;
name: string;
price: number;
}
// Even where there is no event, locateCell(event) tells which cell a click hit. It returns null outside the grid or on the header.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Product', width: 180 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) =>
`$${Number(value).toLocaleString('en-US', { maximumFractionDigits: 1 })}`,
},
],
rows: Array.from({ length: 300 }, (_, i) => ({
id: i + 1,
name: `Product ${i + 1}`,
price: 1 + ((i * 731) % 90) / 10,
})),
rowKey: 'id',
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const onClick = (event: MouseEvent): void => {
const cell = api.locateCell(event);
if (cell === null) {
log('Clicked outside a cell (header or empty area).');
return;
}
const text = api.getCellText(cell.rowKey, cell.columnId);
log(`Row ${cell.rowKey} ${cell.columnId}: "${text}"`);
};
const element = api.getGridElement();
element.addEventListener('click', onClick);
const offScroll = api.on('scrolled', () => {
const { first, last } = api.getVisibleRange();
log(`Rendered lines ${first} to ${last}, top visible line ${api.getTopVisibleIndex()}`);
});
log('Click any cell and scroll. For a cell that is not rendered, getCellElement returns null.');
return () => {
element.removeEventListener('click', onClick);
offScroll();
};
}
export const actions = {
probe: (api: GridApi<Row>) => {
const word = (key: number): string =>
api.getCellElement(key, 'name') === null ? 'not rendered (null)' : 'rendered';
say(`Row 1 cell: ${word(1)} / row 300 cell: ${word(300)}`);
},
end: (api: GridApi<Row>) => api.scrollToIndex(299),
};