서버가 그린 HTML 표를 그리드로 바꾸기Turn a server-rendered HTML table into a grid
서버가 이미 그려 준 평범한 HTML 표를 읽어서 컬럼과 행으로 바꾸면, 정렬·필터 같은 기능을 그대로 쓸 수 있어요. 머리글 칸에 적어 둔 이름표로 항목 이름과 숫자 여부를 알려 줘요.Read a plain server-rendered HTML table into columns and rows and sorting and filtering work right away. Labels written on the header cells tell the field names and which are numbers.
코드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 id="grid" style="height: 520px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api);// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 서버가 이미 그려 주는 평범한 HTML 표예요. data-key는 필드 이름, data-kind는 숫자 표시고요.
// 실제 페이지에서는 이 글자 대신 document.querySelector('table')을 읽으면 돼요.
const TABLE_HTML = `
<table>
<thead>
<tr>
<th data-key="id" data-kind="number">번호</th>
<th data-key="product">품명</th>
<th data-key="stock" data-kind="number">재고</th>
<th data-key="price" data-kind="number">단가(원)</th>
<th data-key="supplier">공급사</th>
</tr>
</thead>
<tbody>
<tr><td>1</td><td>스탠드 조명</td><td>1,240</td><td>18,900</td><td>한빛물류</td></tr>
<tr><td>2</td><td>모니터 받침대</td><td>380</td><td>32,500</td><td>북극성무역</td></tr>
<tr><td>3</td><td>기계식 키보드</td><td>95</td><td>89,000</td><td>한빛물류</td></tr>
<tr><td>4</td><td>케이블 정리함</td><td>2,610</td><td>4,200</td><td>다온상사</td></tr>
</tbody>
</table>`;
function fromTable(html) {
const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
if (!table)
throw new Error('<table>을 찾지 못했어요');
const heads = Array.from(table.querySelectorAll('thead th'));
const columns = heads.map((th) => ({
id: th.dataset.key ?? '',
title: th.textContent?.trim() ?? '',
kind: th.dataset.kind === 'number' ? 'number' : 'text',
align: th.dataset.kind === 'number' ? 'end' : 'start',
...(th.dataset.kind === 'number'
? { formatValue: (value) => Number(value).toLocaleString('ko-KR') }
: {}),
}));
const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr) => {
const cells = Array.from(tr.querySelectorAll('td'));
return Object.fromEntries(columns.map((column, index) => {
const text = cells[index]?.textContent?.trim() ?? '';
return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
}));
});
return { columns, rows, rowKey: 'id' };
}
export const options = fromTable(TABLE_HTML);
// 변환하는 원본 HTML 표를 그리드 위에 그대로 보여 줘요(내가 위에 적어 둔 고정 글자라서 안전해요).
export function setup() {
const grid = document.querySelector('.mxg');
const wrap = document.createElement('div');
wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
const label = document.createElement('div');
label.textContent = L('서버가 보낸 HTML 표 (이 표를 아래 그리드로 바꿨어요)', 'HTML table sent by the server (turned into the grid below)');
label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
const holder = document.createElement('div');
holder.innerHTML = TABLE_HTML;
const table = holder.querySelector('table');
if (table)
table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
for (const cell of holder.querySelectorAll('th, td')) {
cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
}
wrap.append(label, holder);
grid?.insertAdjacentElement('beforebegin', wrap);
return () => wrap.remove();
}<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>서버가 그린 HTML 표를 그리드로 바꾸기</title>
</head>
<body>
<div id="grid" style="height: 520px"></div>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 서버가 이미 그려 주는 평범한 HTML 표예요. data-key는 필드 이름, data-kind는 숫자 표시고요.
// 실제 페이지에서는 이 글자 대신 document.querySelector('table')을 읽으면 돼요.
const TABLE_HTML = `
<table>
<thead>
<tr>
<th data-key="id" data-kind="number">번호</th>
<th data-key="product">품명</th>
<th data-key="stock" data-kind="number">재고</th>
<th data-key="price" data-kind="number">단가(원)</th>
<th data-key="supplier">공급사</th>
</tr>
</thead>
<tbody>
<tr><td>1</td><td>스탠드 조명</td><td>1,240</td><td>18,900</td><td>한빛물류</td></tr>
<tr><td>2</td><td>모니터 받침대</td><td>380</td><td>32,500</td><td>북극성무역</td></tr>
<tr><td>3</td><td>기계식 키보드</td><td>95</td><td>89,000</td><td>한빛물류</td></tr>
<tr><td>4</td><td>케이블 정리함</td><td>2,610</td><td>4,200</td><td>다온상사</td></tr>
</tbody>
</table>`;
function fromTable(html) {
const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
if (!table)
throw new Error('<table>을 찾지 못했어요');
const heads = Array.from(table.querySelectorAll('thead th'));
const columns = heads.map((th) => ({
id: th.dataset.key ?? '',
title: th.textContent?.trim() ?? '',
kind: th.dataset.kind === 'number' ? 'number' : 'text',
align: th.dataset.kind === 'number' ? 'end' : 'start',
...(th.dataset.kind === 'number'
? { formatValue: (value) => Number(value).toLocaleString('ko-KR') }
: {}),
}));
const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr) => {
const cells = Array.from(tr.querySelectorAll('td'));
return Object.fromEntries(columns.map((column, index) => {
const text = cells[index]?.textContent?.trim() ?? '';
return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
}));
});
return { columns, rows, rowKey: 'id' };
}
const options = fromTable(TABLE_HTML);
// 변환하는 원본 HTML 표를 그리드 위에 그대로 보여 줘요(내가 위에 적어 둔 고정 글자라서 안전해요).
function setup() {
const grid = document.querySelector('.mxg');
const wrap = document.createElement('div');
wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
const label = document.createElement('div');
label.textContent = L('서버가 보낸 HTML 표 (이 표를 아래 그리드로 바꿨어요)', 'HTML table sent by the server (turned into the grid below)');
label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
const holder = document.createElement('div');
holder.innerHTML = TABLE_HTML;
const table = holder.querySelector('table');
if (table)
table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
for (const cell of holder.querySelectorAll('th, td')) {
cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
}
wrap.append(label, holder);
grid?.insertAdjacentElement('beforebegin', wrap);
return () => wrap.remove();
}
options.ariaLabel = "서버가 그린 HTML 표를 그리드로 바꾸기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api);
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api) : undefined), [api]);
return (
<>
<Grid style={{ height: 520 }} ref={gridRef} options={options} />
</>
);
}import type { ColumnDef, GridOptions } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type Row = Record<string, string | number>;
// 서버가 이미 그려 주는 평범한 HTML 표예요. data-key는 필드 이름, data-kind는 숫자 표시고요.
// 실제 페이지에서는 이 글자 대신 document.querySelector('table')을 읽으면 돼요.
const TABLE_HTML = `
<table>
<thead>
<tr>
<th data-key="id" data-kind="number">번호</th>
<th data-key="product">품명</th>
<th data-key="stock" data-kind="number">재고</th>
<th data-key="price" data-kind="number">단가(원)</th>
<th data-key="supplier">공급사</th>
</tr>
</thead>
<tbody>
<tr><td>1</td><td>스탠드 조명</td><td>1,240</td><td>18,900</td><td>한빛물류</td></tr>
<tr><td>2</td><td>모니터 받침대</td><td>380</td><td>32,500</td><td>북극성무역</td></tr>
<tr><td>3</td><td>기계식 키보드</td><td>95</td><td>89,000</td><td>한빛물류</td></tr>
<tr><td>4</td><td>케이블 정리함</td><td>2,610</td><td>4,200</td><td>다온상사</td></tr>
</tbody>
</table>`;
function fromTable(html: string): GridOptions<Row> {
const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
if (!table) throw new Error('<table>을 찾지 못했어요');
const heads = Array.from(table.querySelectorAll<HTMLElement>('thead th'));
const columns = heads.map((th): ColumnDef<Row> => ({
id: th.dataset.key ?? '',
title: th.textContent?.trim() ?? '',
kind: th.dataset.kind === 'number' ? 'number' : 'text',
align: th.dataset.kind === 'number' ? 'end' : 'start',
...(th.dataset.kind === 'number'
? { formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR') }
: {}),
}));
const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr): Row => {
const cells = Array.from(tr.querySelectorAll('td'));
return Object.fromEntries(
columns.map((column, index) => {
const text = cells[index]?.textContent?.trim() ?? '';
return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
}),
);
});
return { columns, rows, rowKey: 'id' };
}
export const options: GridOptions<Row> = fromTable(TABLE_HTML);
// 변환하는 원본 HTML 표를 그리드 위에 그대로 보여 줘요(내가 위에 적어 둔 고정 글자라서 안전해요).
export function setup() {
const grid = document.querySelector('.mxg');
const wrap = document.createElement('div');
wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
const label = document.createElement('div');
label.textContent = L(
'서버가 보낸 HTML 표 (이 표를 아래 그리드로 바꿨어요)',
'HTML table sent by the server (turned into the grid below)',
);
label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
const holder = document.createElement('div');
holder.innerHTML = TABLE_HTML;
const table = holder.querySelector('table');
if (table) table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
for (const cell of holder.querySelectorAll<HTMLElement>('th, td')) {
cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
}
wrap.append(label, holder);
grid?.insertAdjacentElement('beforebegin', wrap);
return () => wrap.remove();
}버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { 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);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<Grid style="height: 520px" :options="options" @ready="onReady" />
</template>import type { ColumnDef, GridOptions } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type Row = Record<string, string | number>;
// 서버가 이미 그려 주는 평범한 HTML 표예요. data-key는 필드 이름, data-kind는 숫자 표시고요.
// 실제 페이지에서는 이 글자 대신 document.querySelector('table')을 읽으면 돼요.
const TABLE_HTML = `
<table>
<thead>
<tr>
<th data-key="id" data-kind="number">번호</th>
<th data-key="product">품명</th>
<th data-key="stock" data-kind="number">재고</th>
<th data-key="price" data-kind="number">단가(원)</th>
<th data-key="supplier">공급사</th>
</tr>
</thead>
<tbody>
<tr><td>1</td><td>스탠드 조명</td><td>1,240</td><td>18,900</td><td>한빛물류</td></tr>
<tr><td>2</td><td>모니터 받침대</td><td>380</td><td>32,500</td><td>북극성무역</td></tr>
<tr><td>3</td><td>기계식 키보드</td><td>95</td><td>89,000</td><td>한빛물류</td></tr>
<tr><td>4</td><td>케이블 정리함</td><td>2,610</td><td>4,200</td><td>다온상사</td></tr>
</tbody>
</table>`;
function fromTable(html: string): GridOptions<Row> {
const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
if (!table) throw new Error('<table>을 찾지 못했어요');
const heads = Array.from(table.querySelectorAll<HTMLElement>('thead th'));
const columns = heads.map((th): ColumnDef<Row> => ({
id: th.dataset.key ?? '',
title: th.textContent?.trim() ?? '',
kind: th.dataset.kind === 'number' ? 'number' : 'text',
align: th.dataset.kind === 'number' ? 'end' : 'start',
...(th.dataset.kind === 'number'
? { formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR') }
: {}),
}));
const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr): Row => {
const cells = Array.from(tr.querySelectorAll('td'));
return Object.fromEntries(
columns.map((column, index) => {
const text = cells[index]?.textContent?.trim() ?? '';
return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
}),
);
});
return { columns, rows, rowKey: 'id' };
}
export const options: GridOptions<Row> = fromTable(TABLE_HTML);
// 변환하는 원본 HTML 표를 그리드 위에 그대로 보여 줘요(내가 위에 적어 둔 고정 글자라서 안전해요).
export function setup() {
const grid = document.querySelector('.mxg');
const wrap = document.createElement('div');
wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
const label = document.createElement('div');
label.textContent = L(
'서버가 보낸 HTML 표 (이 표를 아래 그리드로 바꿨어요)',
'HTML table sent by the server (turned into the grid below)',
);
label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
const holder = document.createElement('div');
holder.innerHTML = TABLE_HTML;
const table = holder.querySelector('table');
if (table) table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
for (const cell of holder.querySelectorAll<HTMLElement>('th, td')) {
cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
}
wrap.append(label, holder);
grid?.insertAdjacentElement('beforebegin', wrap);
return () => wrap.remove();
}버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<mx-grid style="height: 520px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
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);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { ColumnDef, GridOptions } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type Row = Record<string, string | number>;
// 서버가 이미 그려 주는 평범한 HTML 표예요. data-key는 필드 이름, data-kind는 숫자 표시고요.
// 실제 페이지에서는 이 글자 대신 document.querySelector('table')을 읽으면 돼요.
const TABLE_HTML = `
<table>
<thead>
<tr>
<th data-key="id" data-kind="number">번호</th>
<th data-key="product">품명</th>
<th data-key="stock" data-kind="number">재고</th>
<th data-key="price" data-kind="number">단가(원)</th>
<th data-key="supplier">공급사</th>
</tr>
</thead>
<tbody>
<tr><td>1</td><td>스탠드 조명</td><td>1,240</td><td>18,900</td><td>한빛물류</td></tr>
<tr><td>2</td><td>모니터 받침대</td><td>380</td><td>32,500</td><td>북극성무역</td></tr>
<tr><td>3</td><td>기계식 키보드</td><td>95</td><td>89,000</td><td>한빛물류</td></tr>
<tr><td>4</td><td>케이블 정리함</td><td>2,610</td><td>4,200</td><td>다온상사</td></tr>
</tbody>
</table>`;
function fromTable(html: string): GridOptions<Row> {
const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
if (!table) throw new Error('<table>을 찾지 못했어요');
const heads = Array.from(table.querySelectorAll<HTMLElement>('thead th'));
const columns = heads.map((th): ColumnDef<Row> => ({
id: th.dataset.key ?? '',
title: th.textContent?.trim() ?? '',
kind: th.dataset.kind === 'number' ? 'number' : 'text',
align: th.dataset.kind === 'number' ? 'end' : 'start',
...(th.dataset.kind === 'number'
? { formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR') }
: {}),
}));
const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr): Row => {
const cells = Array.from(tr.querySelectorAll('td'));
return Object.fromEntries(
columns.map((column, index) => {
const text = cells[index]?.textContent?.trim() ?? '';
return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
}),
);
});
return { columns, rows, rowKey: 'id' };
}
export const options: GridOptions<Row> = fromTable(TABLE_HTML);
// 변환하는 원본 HTML 표를 그리드 위에 그대로 보여 줘요(내가 위에 적어 둔 고정 글자라서 안전해요).
export function setup() {
const grid = document.querySelector('.mxg');
const wrap = document.createElement('div');
wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
const label = document.createElement('div');
label.textContent = L(
'서버가 보낸 HTML 표 (이 표를 아래 그리드로 바꿨어요)',
'HTML table sent by the server (turned into the grid below)',
);
label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
const holder = document.createElement('div');
holder.innerHTML = TABLE_HTML;
const table = holder.querySelector('table');
if (table) table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
for (const cell of holder.querySelectorAll<HTMLElement>('th, td')) {
cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
}
wrap.append(label, holder);
grid?.insertAdjacentElement('beforebegin', wrap);
return () => wrap.remove();
}When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div id="grid" style="height: 520px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api);// An ordinary HTML table the server already renders. data-key is the field name and data-kind marks a number.
// In a real page, read document.querySelector('table') instead of this text.
const TABLE_HTML = `
<table>
<thead>
<tr>
<th data-key="id" data-kind="number">No.</th>
<th data-key="product">Product</th>
<th data-key="stock" data-kind="number">Stock</th>
<th data-key="price" data-kind="number">Unit price ($)</th>
<th data-key="supplier">Supplier</th>
</tr>
</thead>
<tbody>
<tr><td>1</td><td>Desk lamp</td><td>1,240</td><td>18,900</td><td>Northwind Logistics</td></tr>
<tr><td>2</td><td>Monitor stand</td><td>380</td><td>32,500</td><td>Polaris Trading</td></tr>
<tr><td>3</td><td>Mechanical keyboard</td><td>95</td><td>89,000</td><td>Northwind Logistics</td></tr>
<tr><td>4</td><td>Cable organizer</td><td>2,610</td><td>4,200</td><td>Harmony Supply</td></tr>
</tbody>
</table>`;
function fromTable(html) {
const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
if (!table)
throw new Error('Could not find <table>');
const heads = Array.from(table.querySelectorAll('thead th'));
const columns = heads.map((th) => ({
id: th.dataset.key ?? '',
title: th.textContent?.trim() ?? '',
kind: th.dataset.kind === 'number' ? 'number' : 'text',
align: th.dataset.kind === 'number' ? 'end' : 'start',
...(th.dataset.kind === 'number'
? { formatValue: (value) => Number(value).toLocaleString('en-US') }
: {}),
}));
const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr) => {
const cells = Array.from(tr.querySelectorAll('td'));
return Object.fromEntries(columns.map((column, index) => {
const text = cells[index]?.textContent?.trim() ?? '';
return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
}));
});
return { columns, rows, rowKey: 'id' };
}
export const options = fromTable(TABLE_HTML);
// Show the source HTML table being converted as is above the grid (safe because it is a fixed string written above).
export function setup() {
const grid = document.querySelector('.mxg');
const wrap = document.createElement('div');
wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
const label = document.createElement('div');
label.textContent = 'HTML table sent by the server (turned into the grid below)';
label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
const holder = document.createElement('div');
holder.innerHTML = TABLE_HTML;
const table = holder.querySelector('table');
if (table)
table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
for (const cell of holder.querySelectorAll('th, td')) {
cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
}
wrap.append(label, holder);
grid?.insertAdjacentElement('beforebegin', wrap);
return () => wrap.remove();
}<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Turn a server-rendered HTML table into a grid</title>
</head>
<body>
<div id="grid" style="height: 520px"></div>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// An ordinary HTML table the server already renders. data-key is the field name and data-kind marks a number.
// In a real page, read document.querySelector('table') instead of this text.
const TABLE_HTML = `
<table>
<thead>
<tr>
<th data-key="id" data-kind="number">No.</th>
<th data-key="product">Product</th>
<th data-key="stock" data-kind="number">Stock</th>
<th data-key="price" data-kind="number">Unit price ($)</th>
<th data-key="supplier">Supplier</th>
</tr>
</thead>
<tbody>
<tr><td>1</td><td>Desk lamp</td><td>1,240</td><td>18,900</td><td>Northwind Logistics</td></tr>
<tr><td>2</td><td>Monitor stand</td><td>380</td><td>32,500</td><td>Polaris Trading</td></tr>
<tr><td>3</td><td>Mechanical keyboard</td><td>95</td><td>89,000</td><td>Northwind Logistics</td></tr>
<tr><td>4</td><td>Cable organizer</td><td>2,610</td><td>4,200</td><td>Harmony Supply</td></tr>
</tbody>
</table>`;
function fromTable(html) {
const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
if (!table)
throw new Error('Could not find <table>');
const heads = Array.from(table.querySelectorAll('thead th'));
const columns = heads.map((th) => ({
id: th.dataset.key ?? '',
title: th.textContent?.trim() ?? '',
kind: th.dataset.kind === 'number' ? 'number' : 'text',
align: th.dataset.kind === 'number' ? 'end' : 'start',
...(th.dataset.kind === 'number'
? { formatValue: (value) => Number(value).toLocaleString('en-US') }
: {}),
}));
const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr) => {
const cells = Array.from(tr.querySelectorAll('td'));
return Object.fromEntries(columns.map((column, index) => {
const text = cells[index]?.textContent?.trim() ?? '';
return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
}));
});
return { columns, rows, rowKey: 'id' };
}
const options = fromTable(TABLE_HTML);
// Show the source HTML table being converted as is above the grid (safe because it is a fixed string written above).
function setup() {
const grid = document.querySelector('.mxg');
const wrap = document.createElement('div');
wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
const label = document.createElement('div');
label.textContent = 'HTML table sent by the server (turned into the grid below)';
label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
const holder = document.createElement('div');
holder.innerHTML = TABLE_HTML;
const table = holder.querySelector('table');
if (table)
table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
for (const cell of holder.querySelectorAll('th, td')) {
cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
}
wrap.append(label, holder);
grid?.insertAdjacentElement('beforebegin', wrap);
return () => wrap.remove();
}
options.ariaLabel = "Turn a server-rendered HTML table into a grid";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(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 { options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api) : undefined), [api]);
return (
<>
<Grid style={{ height: 520 }} ref={gridRef} options={options} />
</>
);
}import type { ColumnDef, GridOptions } from '@maxgrid/react';
export type Row = Record<string, string | number>;
// An ordinary HTML table the server already renders. data-key is the field name and data-kind marks a number.
// In a real page, read document.querySelector('table') instead of this text.
const TABLE_HTML = `
<table>
<thead>
<tr>
<th data-key="id" data-kind="number">No.</th>
<th data-key="product">Product</th>
<th data-key="stock" data-kind="number">Stock</th>
<th data-key="price" data-kind="number">Unit price ($)</th>
<th data-key="supplier">Supplier</th>
</tr>
</thead>
<tbody>
<tr><td>1</td><td>Desk lamp</td><td>1,240</td><td>18,900</td><td>Northwind Logistics</td></tr>
<tr><td>2</td><td>Monitor stand</td><td>380</td><td>32,500</td><td>Polaris Trading</td></tr>
<tr><td>3</td><td>Mechanical keyboard</td><td>95</td><td>89,000</td><td>Northwind Logistics</td></tr>
<tr><td>4</td><td>Cable organizer</td><td>2,610</td><td>4,200</td><td>Harmony Supply</td></tr>
</tbody>
</table>`;
function fromTable(html: string): GridOptions<Row> {
const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
if (!table) throw new Error('Could not find <table>');
const heads = Array.from(table.querySelectorAll<HTMLElement>('thead th'));
const columns = heads.map((th): ColumnDef<Row> => ({
id: th.dataset.key ?? '',
title: th.textContent?.trim() ?? '',
kind: th.dataset.kind === 'number' ? 'number' : 'text',
align: th.dataset.kind === 'number' ? 'end' : 'start',
...(th.dataset.kind === 'number'
? { formatValue: (value: unknown) => Number(value).toLocaleString('en-US') }
: {}),
}));
const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr): Row => {
const cells = Array.from(tr.querySelectorAll('td'));
return Object.fromEntries(
columns.map((column, index) => {
const text = cells[index]?.textContent?.trim() ?? '';
return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
}),
);
});
return { columns, rows, rowKey: 'id' };
}
export const options: GridOptions<Row> = fromTable(TABLE_HTML);
// Show the source HTML table being converted as is above the grid (safe because it is a fixed string written above).
export function setup() {
const grid = document.querySelector('.mxg');
const wrap = document.createElement('div');
wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
const label = document.createElement('div');
label.textContent = 'HTML table sent by the server (turned into the grid below)';
label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
const holder = document.createElement('div');
holder.innerHTML = TABLE_HTML;
const table = holder.querySelector('table');
if (table) table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
for (const cell of holder.querySelectorAll<HTMLElement>('th, td')) {
cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
}
wrap.append(label, holder);
grid?.insertAdjacentElement('beforebegin', wrap);
return () => wrap.remove();
}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 { 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);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<Grid style="height: 520px" :options="options" @ready="onReady" />
</template>import type { ColumnDef, GridOptions } from '@maxgrid/vue';
export type Row = Record<string, string | number>;
// An ordinary HTML table the server already renders. data-key is the field name and data-kind marks a number.
// In a real page, read document.querySelector('table') instead of this text.
const TABLE_HTML = `
<table>
<thead>
<tr>
<th data-key="id" data-kind="number">No.</th>
<th data-key="product">Product</th>
<th data-key="stock" data-kind="number">Stock</th>
<th data-key="price" data-kind="number">Unit price ($)</th>
<th data-key="supplier">Supplier</th>
</tr>
</thead>
<tbody>
<tr><td>1</td><td>Desk lamp</td><td>1,240</td><td>18,900</td><td>Northwind Logistics</td></tr>
<tr><td>2</td><td>Monitor stand</td><td>380</td><td>32,500</td><td>Polaris Trading</td></tr>
<tr><td>3</td><td>Mechanical keyboard</td><td>95</td><td>89,000</td><td>Northwind Logistics</td></tr>
<tr><td>4</td><td>Cable organizer</td><td>2,610</td><td>4,200</td><td>Harmony Supply</td></tr>
</tbody>
</table>`;
function fromTable(html: string): GridOptions<Row> {
const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
if (!table) throw new Error('Could not find <table>');
const heads = Array.from(table.querySelectorAll<HTMLElement>('thead th'));
const columns = heads.map((th): ColumnDef<Row> => ({
id: th.dataset.key ?? '',
title: th.textContent?.trim() ?? '',
kind: th.dataset.kind === 'number' ? 'number' : 'text',
align: th.dataset.kind === 'number' ? 'end' : 'start',
...(th.dataset.kind === 'number'
? { formatValue: (value: unknown) => Number(value).toLocaleString('en-US') }
: {}),
}));
const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr): Row => {
const cells = Array.from(tr.querySelectorAll('td'));
return Object.fromEntries(
columns.map((column, index) => {
const text = cells[index]?.textContent?.trim() ?? '';
return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
}),
);
});
return { columns, rows, rowKey: 'id' };
}
export const options: GridOptions<Row> = fromTable(TABLE_HTML);
// Show the source HTML table being converted as is above the grid (safe because it is a fixed string written above).
export function setup() {
const grid = document.querySelector('.mxg');
const wrap = document.createElement('div');
wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
const label = document.createElement('div');
label.textContent = 'HTML table sent by the server (turned into the grid below)';
label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
const holder = document.createElement('div');
holder.innerHTML = TABLE_HTML;
const table = holder.querySelector('table');
if (table) table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
for (const cell of holder.querySelectorAll<HTMLElement>('th, td')) {
cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
}
wrap.append(label, holder);
grid?.insertAdjacentElement('beforebegin', wrap);
return () => wrap.remove();
}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 { options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<mx-grid style="height: 520px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
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);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { ColumnDef, GridOptions } from '@maxgrid/angular';
export type Row = Record<string, string | number>;
// An ordinary HTML table the server already renders. data-key is the field name and data-kind marks a number.
// In a real page, read document.querySelector('table') instead of this text.
const TABLE_HTML = `
<table>
<thead>
<tr>
<th data-key="id" data-kind="number">No.</th>
<th data-key="product">Product</th>
<th data-key="stock" data-kind="number">Stock</th>
<th data-key="price" data-kind="number">Unit price ($)</th>
<th data-key="supplier">Supplier</th>
</tr>
</thead>
<tbody>
<tr><td>1</td><td>Desk lamp</td><td>1,240</td><td>18,900</td><td>Northwind Logistics</td></tr>
<tr><td>2</td><td>Monitor stand</td><td>380</td><td>32,500</td><td>Polaris Trading</td></tr>
<tr><td>3</td><td>Mechanical keyboard</td><td>95</td><td>89,000</td><td>Northwind Logistics</td></tr>
<tr><td>4</td><td>Cable organizer</td><td>2,610</td><td>4,200</td><td>Harmony Supply</td></tr>
</tbody>
</table>`;
function fromTable(html: string): GridOptions<Row> {
const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
if (!table) throw new Error('Could not find <table>');
const heads = Array.from(table.querySelectorAll<HTMLElement>('thead th'));
const columns = heads.map((th): ColumnDef<Row> => ({
id: th.dataset.key ?? '',
title: th.textContent?.trim() ?? '',
kind: th.dataset.kind === 'number' ? 'number' : 'text',
align: th.dataset.kind === 'number' ? 'end' : 'start',
...(th.dataset.kind === 'number'
? { formatValue: (value: unknown) => Number(value).toLocaleString('en-US') }
: {}),
}));
const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr): Row => {
const cells = Array.from(tr.querySelectorAll('td'));
return Object.fromEntries(
columns.map((column, index) => {
const text = cells[index]?.textContent?.trim() ?? '';
return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
}),
);
});
return { columns, rows, rowKey: 'id' };
}
export const options: GridOptions<Row> = fromTable(TABLE_HTML);
// Show the source HTML table being converted as is above the grid (safe because it is a fixed string written above).
export function setup() {
const grid = document.querySelector('.mxg');
const wrap = document.createElement('div');
wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
const label = document.createElement('div');
label.textContent = 'HTML table sent by the server (turned into the grid below)';
label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
const holder = document.createElement('div');
holder.innerHTML = TABLE_HTML;
const table = holder.querySelector('table');
if (table) table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
for (const cell of holder.querySelectorAll<HTMLElement>('th, td')) {
cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
}
wrap.append(label, holder);
grid?.insertAdjacentElement('beforebegin', wrap);
return () => wrap.remove();
}