입력한 글자를 값으로 바꾸는 parseTurn typed text into a value with parse
컬럼의 parse(raw, row)가 직접 입력과 붙여넣기의 글자를 값으로 바꿔요. 값을 돌려주면 쓰이고, 예외를 던지거나 값을 돌려주지 않으면 값이 올바르지 않다고 막혀요.The column parse(raw, row) turns typed and pasted text into a value. A returned value is used; throwing or returning nothing refuses the input as invalid.
코드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="edit">가격 편집</button>
<button type="button" id="paste">가격 붙여넣기</button>
</div>
<div id="grid" style="height: 210px"></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('edit').addEventListener('click', () => actions.edit(api));
document.getElementById('paste').addEventListener('click', () => actions.paste(api));const rows = [
{ id: 1, item: '커피', price: 4500 },
{ id: 2, item: '샌드위치', price: 6800 },
{ id: 3, item: '주스', price: 5200 },
];
// parse는 입력한 글자를 값으로 바꿔요. '4,500원'이나 '5천'을 숫자로 읽고, 읽을 수 없으면 값을 돌려주지 않아 거절해요.
const readWon = (raw) => {
const text = raw.replace(/[,\s원]/g, '');
const thousand = /^(\d+(?:\.\d+)?)천$/.exec(text);
const value = thousand ? Number(thousand[1]) * 1000 : Number(text);
return Number.isFinite(value) ? value : undefined;
};
export const options = {
columns: [
{ id: 'id', title: '번호', kind: 'number', width: 70 },
{ id: 'item', title: '품목', width: 120 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 140,
editable: true,
parse: readWon,
format: { number: { grouping: true, suffix: '원' } },
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
};
export function setup(api, log) {
const off = [
api.on('editCommitted', (e) => log({ ko: `확정: ${String(e.newValue)}`, en: `Committed: ${String(e.newValue)}` })),
api.on('validationFailed', (e) => log(`${e.columnId}: ${e.message}`)),
];
return () => off.forEach((fn) => fn());
}
export const actions = {
edit: (api) => api.startEdit(1, 'price'),
paste: (api) => {
api.selectCells({ rowKey: 2, columnId: 'price' });
api.pasteCells('7,300원\n5천\n한글');
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>입력한 글자를 값으로 바꾸는 parse</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="edit">가격 편집</button>
<button type="button" id="paste">가격 붙여넣기</button>
</div>
<div id="grid" style="height: 210px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, item: '커피', price: 4500 },
{ id: 2, item: '샌드위치', price: 6800 },
{ id: 3, item: '주스', price: 5200 },
];
// parse는 입력한 글자를 값으로 바꿔요. '4,500원'이나 '5천'을 숫자로 읽고, 읽을 수 없으면 값을 돌려주지 않아 거절해요.
const readWon = (raw) => {
const text = raw.replace(/[,\s원]/g, '');
const thousand = /^(\d+(?:\.\d+)?)천$/.exec(text);
const value = thousand ? Number(thousand[1]) * 1000 : Number(text);
return Number.isFinite(value) ? value : undefined;
};
const options = {
columns: [
{ id: 'id', title: '번호', kind: 'number', width: 70 },
{ id: 'item', title: '품목', width: 120 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 140,
editable: true,
parse: readWon,
format: { number: { grouping: true, suffix: '원' } },
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
};
function setup(api, log) {
const off = [
api.on('editCommitted', (e) => log({ ko: `확정: ${String(e.newValue)}`, en: `Committed: ${String(e.newValue)}` })),
api.on('validationFailed', (e) => log(`${e.columnId}: ${e.message}`)),
];
return () => off.forEach((fn) => fn());
}
const actions = {
edit: (api) => api.startEdit(1, 'price'),
paste: (api) => {
api.selectCells({ rowKey: 2, columnId: 'price' });
api.pasteCells('7,300원\n5천\n한글');
},
};
options.ariaLabel = "입력한 글자를 값으로 바꾸는 parse";
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('edit').addEventListener('click', () => actions.edit(api));
document.getElementById('paste').addEventListener('click', () => actions.paste(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.edit(api)}
>가격 편집</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.paste(api)}
>가격 붙여넣기</button>
</div>
<Grid style={{ height: 210 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
item: string;
price: number | null;
}
const rows: Row[] = [
{ id: 1, item: '커피', price: 4500 },
{ id: 2, item: '샌드위치', price: 6800 },
{ id: 3, item: '주스', price: 5200 },
];
// parse는 입력한 글자를 값으로 바꿔요. '4,500원'이나 '5천'을 숫자로 읽고, 읽을 수 없으면 값을 돌려주지 않아 거절해요.
const readWon = (raw: string): number | undefined => {
const text = raw.replace(/[,\s원]/g, '');
const thousand = /^(\d+(?:\.\d+)?)천$/.exec(text);
const value = thousand ? Number(thousand[1]) * 1000 : Number(text);
return Number.isFinite(value) ? value : undefined;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '번호', kind: 'number', width: 70 },
{ id: 'item', title: '품목', width: 120 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 140,
editable: true,
parse: readWon,
format: { number: { grouping: true, suffix: '원' } },
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = [
api.on('editCommitted', (e) =>
log({ ko: `확정: ${String(e.newValue)}`, en: `Committed: ${String(e.newValue)}` }),
),
api.on('validationFailed', (e) => log(`${e.columnId}: ${e.message}`)),
];
return () => off.forEach((fn) => fn());
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'price'),
paste: (api: GridApi<Row>) => {
api.selectCells({ rowKey: 2, columnId: 'price' });
api.pasteCells('7,300원\n5천\n한글');
},
};버튼을 누르면 이 예제의 코드가 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.edit(api)">가격 편집</button>
<button type="button" :disabled="!api" @click="api && actions.paste(api)">가격 붙여넣기</button>
</div>
<Grid style="height: 210px" :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;
item: string;
price: number | null;
}
const rows: Row[] = [
{ id: 1, item: '커피', price: 4500 },
{ id: 2, item: '샌드위치', price: 6800 },
{ id: 3, item: '주스', price: 5200 },
];
// parse는 입력한 글자를 값으로 바꿔요. '4,500원'이나 '5천'을 숫자로 읽고, 읽을 수 없으면 값을 돌려주지 않아 거절해요.
const readWon = (raw: string): number | undefined => {
const text = raw.replace(/[,\s원]/g, '');
const thousand = /^(\d+(?:\.\d+)?)천$/.exec(text);
const value = thousand ? Number(thousand[1]) * 1000 : Number(text);
return Number.isFinite(value) ? value : undefined;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '번호', kind: 'number', width: 70 },
{ id: 'item', title: '품목', width: 120 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 140,
editable: true,
parse: readWon,
format: { number: { grouping: true, suffix: '원' } },
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = [
api.on('editCommitted', (e) =>
log({ ko: `확정: ${String(e.newValue)}`, en: `Committed: ${String(e.newValue)}` }),
),
api.on('validationFailed', (e) => log(`${e.columnId}: ${e.message}`)),
];
return () => off.forEach((fn) => fn());
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'price'),
paste: (api: GridApi<Row>) => {
api.selectCells({ rowKey: 2, columnId: 'price' });
api.pasteCells('7,300원\n5천\n한글');
},
};버튼을 누르면 이 예제의 코드가 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.edit(api)"
>가격 편집</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.paste(api)"
>가격 붙여넣기</button>
</div>
<mx-grid style="height: 210px" [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;
item: string;
price: number | null;
}
const rows: Row[] = [
{ id: 1, item: '커피', price: 4500 },
{ id: 2, item: '샌드위치', price: 6800 },
{ id: 3, item: '주스', price: 5200 },
];
// parse는 입력한 글자를 값으로 바꿔요. '4,500원'이나 '5천'을 숫자로 읽고, 읽을 수 없으면 값을 돌려주지 않아 거절해요.
const readWon = (raw: string): number | undefined => {
const text = raw.replace(/[,\s원]/g, '');
const thousand = /^(\d+(?:\.\d+)?)천$/.exec(text);
const value = thousand ? Number(thousand[1]) * 1000 : Number(text);
return Number.isFinite(value) ? value : undefined;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: '번호', kind: 'number', width: 70 },
{ id: 'item', title: '품목', width: 120 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 140,
editable: true,
parse: readWon,
format: { number: { grouping: true, suffix: '원' } },
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = [
api.on('editCommitted', (e) =>
log({ ko: `확정: ${String(e.newValue)}`, en: `Committed: ${String(e.newValue)}` }),
),
api.on('validationFailed', (e) => log(`${e.columnId}: ${e.message}`)),
];
return () => off.forEach((fn) => fn());
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'price'),
paste: (api: GridApi<Row>) => {
api.selectCells({ rowKey: 2, columnId: 'price' });
api.pasteCells('7,300원\n5천\n한글');
},
};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="edit">Edit price</button>
<button type="button" id="paste">Paste prices</button>
</div>
<div id="grid" style="height: 210px"></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('edit').addEventListener('click', () => actions.edit(api));
document.getElementById('paste').addEventListener('click', () => actions.paste(api));const rows = [
{ id: 1, item: 'Coffee', price: 4.5 },
{ id: 2, item: 'Sandwich', price: 6.8 },
{ id: 3, item: 'Juice', price: 5.2 },
];
// parse turns typed text into a value. It reads '$4.50' or '7.3' as numbers, and refuses by returning nothing when the text cannot be read.
const readPrice = (raw) => {
const text = raw.replace(/[,\s$]/g, '');
const value = Number(text);
return Number.isFinite(value) ? value : undefined;
};
export const options = {
columns: [
{ id: 'id', title: 'No.', kind: 'number', width: 70 },
{ id: 'item', title: 'Item', width: 120 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 140,
editable: true,
parse: readPrice,
format: { number: { grouping: true, prefix: '$', decimals: 2 } },
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
};
export function setup(api, log) {
const off = [
api.on('editCommitted', (e) => log(`Committed: ${String(e.newValue)}`)),
api.on('validationFailed', (e) => log(`${e.columnId}: ${e.message}`)),
];
return () => off.forEach((fn) => fn());
}
export const actions = {
edit: (api) => api.startEdit(1, 'price'),
paste: (api) => {
api.selectCells({ rowKey: 2, columnId: 'price' });
api.pasteCells('$7.30\n5\nabc');
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Turn typed text into a value with parse</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="edit">Edit price</button>
<button type="button" id="paste">Paste prices</button>
</div>
<div id="grid" style="height: 210px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, item: 'Coffee', price: 4.5 },
{ id: 2, item: 'Sandwich', price: 6.8 },
{ id: 3, item: 'Juice', price: 5.2 },
];
// parse turns typed text into a value. It reads '$4.50' or '7.3' as numbers, and refuses by returning nothing when the text cannot be read.
const readPrice = (raw) => {
const text = raw.replace(/[,\s$]/g, '');
const value = Number(text);
return Number.isFinite(value) ? value : undefined;
};
const options = {
columns: [
{ id: 'id', title: 'No.', kind: 'number', width: 70 },
{ id: 'item', title: 'Item', width: 120 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 140,
editable: true,
parse: readPrice,
format: { number: { grouping: true, prefix: '$', decimals: 2 } },
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
};
function setup(api, log) {
const off = [
api.on('editCommitted', (e) => log(`Committed: ${String(e.newValue)}`)),
api.on('validationFailed', (e) => log(`${e.columnId}: ${e.message}`)),
];
return () => off.forEach((fn) => fn());
}
const actions = {
edit: (api) => api.startEdit(1, 'price'),
paste: (api) => {
api.selectCells({ rowKey: 2, columnId: 'price' });
api.pasteCells('$7.30\n5\nabc');
},
};
options.ariaLabel = "Turn typed text into a value with parse";
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('edit').addEventListener('click', () => actions.edit(api));
document.getElementById('paste').addEventListener('click', () => actions.paste(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.edit(api)}
>Edit price</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.paste(api)}
>Paste prices</button>
</div>
<Grid style={{ height: 210 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
item: string;
price: number | null;
}
const rows: Row[] = [
{ id: 1, item: 'Coffee', price: 4.5 },
{ id: 2, item: 'Sandwich', price: 6.8 },
{ id: 3, item: 'Juice', price: 5.2 },
];
// parse turns typed text into a value. It reads '$4.50' or '7.3' as numbers, and refuses by returning nothing when the text cannot be read.
const readPrice = (raw: string): number | undefined => {
const text = raw.replace(/[,\s$]/g, '');
const value = Number(text);
return Number.isFinite(value) ? value : undefined;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'No.', kind: 'number', width: 70 },
{ id: 'item', title: 'Item', width: 120 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 140,
editable: true,
parse: readPrice,
format: { number: { grouping: true, prefix: '$', decimals: 2 } },
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = [
api.on('editCommitted', (e) => log(`Committed: ${String(e.newValue)}`)),
api.on('validationFailed', (e) => log(`${e.columnId}: ${e.message}`)),
];
return () => off.forEach((fn) => fn());
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'price'),
paste: (api: GridApi<Row>) => {
api.selectCells({ rowKey: 2, columnId: 'price' });
api.pasteCells('$7.30\n5\nabc');
},
};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.edit(api)">Edit price</button>
<button type="button" :disabled="!api" @click="api && actions.paste(api)">Paste prices</button>
</div>
<Grid style="height: 210px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
item: string;
price: number | null;
}
const rows: Row[] = [
{ id: 1, item: 'Coffee', price: 4.5 },
{ id: 2, item: 'Sandwich', price: 6.8 },
{ id: 3, item: 'Juice', price: 5.2 },
];
// parse turns typed text into a value. It reads '$4.50' or '7.3' as numbers, and refuses by returning nothing when the text cannot be read.
const readPrice = (raw: string): number | undefined => {
const text = raw.replace(/[,\s$]/g, '');
const value = Number(text);
return Number.isFinite(value) ? value : undefined;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'No.', kind: 'number', width: 70 },
{ id: 'item', title: 'Item', width: 120 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 140,
editable: true,
parse: readPrice,
format: { number: { grouping: true, prefix: '$', decimals: 2 } },
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = [
api.on('editCommitted', (e) => log(`Committed: ${String(e.newValue)}`)),
api.on('validationFailed', (e) => log(`${e.columnId}: ${e.message}`)),
];
return () => off.forEach((fn) => fn());
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'price'),
paste: (api: GridApi<Row>) => {
api.selectCells({ rowKey: 2, columnId: 'price' });
api.pasteCells('$7.30\n5\nabc');
},
};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.edit(api)"
>Edit price</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.paste(api)"
>Paste prices</button>
</div>
<mx-grid style="height: 210px" [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;
item: string;
price: number | null;
}
const rows: Row[] = [
{ id: 1, item: 'Coffee', price: 4.5 },
{ id: 2, item: 'Sandwich', price: 6.8 },
{ id: 3, item: 'Juice', price: 5.2 },
];
// parse turns typed text into a value. It reads '$4.50' or '7.3' as numbers, and refuses by returning nothing when the text cannot be read.
const readPrice = (raw: string): number | undefined => {
const text = raw.replace(/[,\s$]/g, '');
const value = Number(text);
return Number.isFinite(value) ? value : undefined;
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'id', title: 'No.', kind: 'number', width: 70 },
{ id: 'item', title: 'Item', width: 120 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 140,
editable: true,
parse: readPrice,
format: { number: { grouping: true, prefix: '$', decimals: 2 } },
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
const off = [
api.on('editCommitted', (e) => log(`Committed: ${String(e.newValue)}`)),
api.on('validationFailed', (e) => log(`${e.columnId}: ${e.message}`)),
];
return () => off.forEach((fn) => fn());
}
export const actions = {
edit: (api: GridApi<Row>) => api.startEdit(1, 'price'),
paste: (api: GridApi<Row>) => {
api.selectCells({ rowKey: 2, columnId: 'price' });
api.pasteCells('$7.30\n5\nabc');
},
};