직접 만든 머리글 렌더러A custom header renderer
headerRenderer에 함수를 주면 머리글 안에 직접 만든 요소를 넣어요. 함수는 mount(el, ctx)·update(ctx)·destroy()를 가진 객체를 돌려줘요. 폭·순서를 바꿔 머리글을 다시 그려도 mount는 한 번이고 update만 불려 같은 요소가 새 칸으로 옮겨져요. 컬럼이 없어지면 destroy가 불려요.Give headerRenderer a function to put your own element in the header. The function returns an object with mount(el, ctx), update(ctx) and destroy(). When the header is redrawn for a width or order change, mount runs once and only update is called, moving the same element to the new cell. destroy runs when the column goes away.
코드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="widen">담당 폭 넓히기</button>
<button type="button" id="remove">작업 컬럼 없애기</button>
</div>
<div id="grid" style="height: 200px"></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('widen').addEventListener('click', () => actions.widen(api));
document.getElementById('remove').addEventListener('click', () => actions.remove(api));const rows = [
{ id: 1, task: '로그인 화면 수정', owner: '김하늘', done: false },
{ id: 2, task: '결제 흐름 검토', owner: '이도윤', done: true },
{ id: 3, task: '새 아이콘 세트', owner: '박서연', done: false },
{ id: 4, task: '배포 점검', owner: '최지우', done: false },
];
// 직접 만든 머리글 렌더러: 팩토리가 mount(el, ctx)·update(ctx)·destroy()를 가진 객체를 돌려줘요.
// 폭·순서를 바꿔 머리글을 다시 그려도 mount는 한 번이고 update만 불리며 요소 상태가 유지돼요.
let say = () => { };
const counter = () => {
let clicks = 0;
let node = null;
return {
mount(el, ctx) {
say({ ko: `mount(${ctx.columnId})`, en: `mount(${ctx.columnId})` });
node = el.ownerDocument.createElement('button');
node.type = 'button';
node.tabIndex = -1;
node.addEventListener('click', () => {
clicks += 1;
node.textContent = `누른 횟수 ${clicks}`;
});
node.textContent = `누른 횟수 ${clicks}`;
el.append(node);
},
update() {
say({
ko: 'update: 같은 요소를 새 머리글 칸으로 옮겼어요(횟수 유지)',
en: 'update: the same element moved to the new header cell (count kept)',
});
},
destroy() {
say({ ko: 'destroy', en: 'destroy' });
},
};
};
export const options = {
columns: [
{ id: 'task', title: '작업', width: 170, headerRenderer: counter },
{ id: 'owner', title: '담당', width: 100 },
{ id: 'done', title: '완료', kind: 'boolean', width: 90 },
],
rows,
rowKey: 'id',
};
export function setup(_api, log) {
say = log;
log({
ko: '"작업" 머리글의 버튼을 몇 번 누른 뒤 컬럼 폭을 끌어 바꿔 보세요. 횟수가 유지돼요.',
en: 'Press the button in the Task header a few times, then drag a column width. The count stays.',
});
}
export const actions = {
widen: (api) => api.updateColumn('owner', { width: 160 }),
// 이미 지운 뒤에 또 눌러도 오류가 나지 않게 컬럼이 있을 때만 지워요.
remove: (api) => {
if (api.getColumns().some((c) => c.id === 'task'))
api.removeColumn('task');
},
};<!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="widen">담당 폭 넓히기</button>
<button type="button" id="remove">작업 컬럼 없애기</button>
</div>
<div id="grid" style="height: 200px"></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, task: '로그인 화면 수정', owner: '김하늘', done: false },
{ id: 2, task: '결제 흐름 검토', owner: '이도윤', done: true },
{ id: 3, task: '새 아이콘 세트', owner: '박서연', done: false },
{ id: 4, task: '배포 점검', owner: '최지우', done: false },
];
// 직접 만든 머리글 렌더러: 팩토리가 mount(el, ctx)·update(ctx)·destroy()를 가진 객체를 돌려줘요.
// 폭·순서를 바꿔 머리글을 다시 그려도 mount는 한 번이고 update만 불리며 요소 상태가 유지돼요.
let say = () => { };
const counter = () => {
let clicks = 0;
let node = null;
return {
mount(el, ctx) {
say({ ko: `mount(${ctx.columnId})`, en: `mount(${ctx.columnId})` });
node = el.ownerDocument.createElement('button');
node.type = 'button';
node.tabIndex = -1;
node.addEventListener('click', () => {
clicks += 1;
node.textContent = `누른 횟수 ${clicks}`;
});
node.textContent = `누른 횟수 ${clicks}`;
el.append(node);
},
update() {
say({
ko: 'update: 같은 요소를 새 머리글 칸으로 옮겼어요(횟수 유지)',
en: 'update: the same element moved to the new header cell (count kept)',
});
},
destroy() {
say({ ko: 'destroy', en: 'destroy' });
},
};
};
const options = {
columns: [
{ id: 'task', title: '작업', width: 170, headerRenderer: counter },
{ id: 'owner', title: '담당', width: 100 },
{ id: 'done', title: '완료', kind: 'boolean', width: 90 },
],
rows,
rowKey: 'id',
};
function setup(_api, log) {
say = log;
log({
ko: '"작업" 머리글의 버튼을 몇 번 누른 뒤 컬럼 폭을 끌어 바꿔 보세요. 횟수가 유지돼요.',
en: 'Press the button in the Task header a few times, then drag a column width. The count stays.',
});
}
const actions = {
widen: (api) => api.updateColumn('owner', { width: 160 }),
// 이미 지운 뒤에 또 눌러도 오류가 나지 않게 컬럼이 있을 때만 지워요.
remove: (api) => {
if (api.getColumns().some((c) => c.id === 'task'))
api.removeColumn('task');
},
};
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('widen').addEventListener('click', () => actions.widen(api));
document.getElementById('remove').addEventListener('click', () => actions.remove(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.widen(api)}
>담당 폭 넓히기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.remove(api)}
>작업 컬럼 없애기</button>
</div>
<Grid style={{ height: 200 }} 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;
done: boolean;
}
const rows: Row[] = [
{ id: 1, task: '로그인 화면 수정', owner: '김하늘', done: false },
{ id: 2, task: '결제 흐름 검토', owner: '이도윤', done: true },
{ id: 3, task: '새 아이콘 세트', owner: '박서연', done: false },
{ id: 4, task: '배포 점검', owner: '최지우', done: false },
];
// 직접 만든 머리글 렌더러: 팩토리가 mount(el, ctx)·update(ctx)·destroy()를 가진 객체를 돌려줘요.
// 폭·순서를 바꿔 머리글을 다시 그려도 mount는 한 번이고 update만 불리며 요소 상태가 유지돼요.
let say: (message: LogText) => void = () => {};
const counter = () => {
let clicks = 0;
let node: HTMLButtonElement | null = null;
return {
mount(el: HTMLElement, ctx: { columnId: string; params: unknown }) {
say({ ko: `mount(${ctx.columnId})`, en: `mount(${ctx.columnId})` });
node = el.ownerDocument.createElement('button');
node.type = 'button';
node.tabIndex = -1;
node.addEventListener('click', () => {
clicks += 1;
node!.textContent = `누른 횟수 ${clicks}`;
});
node.textContent = `누른 횟수 ${clicks}`;
el.append(node);
},
update() {
say({
ko: 'update: 같은 요소를 새 머리글 칸으로 옮겼어요(횟수 유지)',
en: 'update: the same element moved to the new header cell (count kept)',
});
},
destroy() {
say({ ko: 'destroy', en: 'destroy' });
},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'task', title: '작업', width: 170, headerRenderer: counter },
{ id: 'owner', title: '담당', width: 100 },
{ id: 'done', title: '완료', kind: 'boolean', width: 90 },
],
rows,
rowKey: 'id',
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '"작업" 머리글의 버튼을 몇 번 누른 뒤 컬럼 폭을 끌어 바꿔 보세요. 횟수가 유지돼요.',
en: 'Press the button in the Task header a few times, then drag a column width. The count stays.',
});
}
export const actions = {
widen: (api: GridApi<Row>) => api.updateColumn('owner', { width: 160 }),
// 이미 지운 뒤에 또 눌러도 오류가 나지 않게 컬럼이 있을 때만 지워요.
remove: (api: GridApi<Row>) => {
if (api.getColumns().some((c) => c.id === 'task')) api.removeColumn('task');
},
};버튼을 누르면 이 예제의 코드가 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.widen(api)">담당 폭 넓히기</button>
<button type="button" :disabled="!api" @click="api && actions.remove(api)">작업 컬럼 없애기</button>
</div>
<Grid style="height: 200px" :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;
done: boolean;
}
const rows: Row[] = [
{ id: 1, task: '로그인 화면 수정', owner: '김하늘', done: false },
{ id: 2, task: '결제 흐름 검토', owner: '이도윤', done: true },
{ id: 3, task: '새 아이콘 세트', owner: '박서연', done: false },
{ id: 4, task: '배포 점검', owner: '최지우', done: false },
];
// 직접 만든 머리글 렌더러: 팩토리가 mount(el, ctx)·update(ctx)·destroy()를 가진 객체를 돌려줘요.
// 폭·순서를 바꿔 머리글을 다시 그려도 mount는 한 번이고 update만 불리며 요소 상태가 유지돼요.
let say: (message: LogText) => void = () => {};
const counter = () => {
let clicks = 0;
let node: HTMLButtonElement | null = null;
return {
mount(el: HTMLElement, ctx: { columnId: string; params: unknown }) {
say({ ko: `mount(${ctx.columnId})`, en: `mount(${ctx.columnId})` });
node = el.ownerDocument.createElement('button');
node.type = 'button';
node.tabIndex = -1;
node.addEventListener('click', () => {
clicks += 1;
node!.textContent = `누른 횟수 ${clicks}`;
});
node.textContent = `누른 횟수 ${clicks}`;
el.append(node);
},
update() {
say({
ko: 'update: 같은 요소를 새 머리글 칸으로 옮겼어요(횟수 유지)',
en: 'update: the same element moved to the new header cell (count kept)',
});
},
destroy() {
say({ ko: 'destroy', en: 'destroy' });
},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'task', title: '작업', width: 170, headerRenderer: counter },
{ id: 'owner', title: '담당', width: 100 },
{ id: 'done', title: '완료', kind: 'boolean', width: 90 },
],
rows,
rowKey: 'id',
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '"작업" 머리글의 버튼을 몇 번 누른 뒤 컬럼 폭을 끌어 바꿔 보세요. 횟수가 유지돼요.',
en: 'Press the button in the Task header a few times, then drag a column width. The count stays.',
});
}
export const actions = {
widen: (api: GridApi<Row>) => api.updateColumn('owner', { width: 160 }),
// 이미 지운 뒤에 또 눌러도 오류가 나지 않게 컬럼이 있을 때만 지워요.
remove: (api: GridApi<Row>) => {
if (api.getColumns().some((c) => c.id === 'task')) api.removeColumn('task');
},
};버튼을 누르면 이 예제의 코드가 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.widen(api)"
>담당 폭 넓히기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.remove(api)"
>작업 컬럼 없애기</button>
</div>
<mx-grid style="height: 200px" [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;
done: boolean;
}
const rows: Row[] = [
{ id: 1, task: '로그인 화면 수정', owner: '김하늘', done: false },
{ id: 2, task: '결제 흐름 검토', owner: '이도윤', done: true },
{ id: 3, task: '새 아이콘 세트', owner: '박서연', done: false },
{ id: 4, task: '배포 점검', owner: '최지우', done: false },
];
// 직접 만든 머리글 렌더러: 팩토리가 mount(el, ctx)·update(ctx)·destroy()를 가진 객체를 돌려줘요.
// 폭·순서를 바꿔 머리글을 다시 그려도 mount는 한 번이고 update만 불리며 요소 상태가 유지돼요.
let say: (message: LogText) => void = () => {};
const counter = () => {
let clicks = 0;
let node: HTMLButtonElement | null = null;
return {
mount(el: HTMLElement, ctx: { columnId: string; params: unknown }) {
say({ ko: `mount(${ctx.columnId})`, en: `mount(${ctx.columnId})` });
node = el.ownerDocument.createElement('button');
node.type = 'button';
node.tabIndex = -1;
node.addEventListener('click', () => {
clicks += 1;
node!.textContent = `누른 횟수 ${clicks}`;
});
node.textContent = `누른 횟수 ${clicks}`;
el.append(node);
},
update() {
say({
ko: 'update: 같은 요소를 새 머리글 칸으로 옮겼어요(횟수 유지)',
en: 'update: the same element moved to the new header cell (count kept)',
});
},
destroy() {
say({ ko: 'destroy', en: 'destroy' });
},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'task', title: '작업', width: 170, headerRenderer: counter },
{ id: 'owner', title: '담당', width: 100 },
{ id: 'done', title: '완료', kind: 'boolean', width: 90 },
],
rows,
rowKey: 'id',
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '"작업" 머리글의 버튼을 몇 번 누른 뒤 컬럼 폭을 끌어 바꿔 보세요. 횟수가 유지돼요.',
en: 'Press the button in the Task header a few times, then drag a column width. The count stays.',
});
}
export const actions = {
widen: (api: GridApi<Row>) => api.updateColumn('owner', { width: 160 }),
// 이미 지운 뒤에 또 눌러도 오류가 나지 않게 컬럼이 있을 때만 지워요.
remove: (api: GridApi<Row>) => {
if (api.getColumns().some((c) => c.id === 'task')) api.removeColumn('task');
},
};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="widen">Widen Owner</button>
<button type="button" id="remove">Remove Task</button>
</div>
<div id="grid" style="height: 200px"></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('widen').addEventListener('click', () => actions.widen(api));
document.getElementById('remove').addEventListener('click', () => actions.remove(api));const rows = [
{ id: 1, task: 'Fix login screen', owner: 'Liam Carter', done: false },
{ id: 2, task: 'Review payment flow', owner: 'Ethan Clark', done: true },
{ id: 3, task: 'New icon set', owner: 'Emma Stone', done: false },
{ id: 4, task: 'Deployment check', owner: 'Olivia Reed', done: false },
];
// A custom header renderer: the factory returns an object with mount(el, ctx), update(ctx) and destroy().
// Even when a width or order change redraws the header, mount runs once, only update is called and the element state is kept.
let say = () => { };
const counter = () => {
let clicks = 0;
let node = null;
return {
mount(el, ctx) {
say(`mount(${ctx.columnId})`);
node = el.ownerDocument.createElement('button');
node.type = 'button';
node.tabIndex = -1;
node.addEventListener('click', () => {
clicks += 1;
node.textContent = `Clicks ${clicks}`;
});
node.textContent = `Clicks ${clicks}`;
el.append(node);
},
update() {
say('update: the same element moved to the new header cell (count kept)');
},
destroy() {
say('destroy');
},
};
};
export const options = {
columns: [
{ id: 'task', title: 'Task', width: 170, headerRenderer: counter },
{ id: 'owner', title: 'Owner', width: 100 },
{ id: 'done', title: 'Done', kind: 'boolean', width: 90 },
],
rows,
rowKey: 'id',
};
export function setup(_api, log) {
say = log;
log('Press the button in the Task header a few times, then drag a column width. The count stays.');
}
export const actions = {
widen: (api) => api.updateColumn('owner', { width: 160 }),
// Remove the column only if it exists, so pressing again after removal does not raise an error.
remove: (api) => {
if (api.getColumns().some((c) => c.id === 'task'))
api.removeColumn('task');
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>A custom header renderer</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="widen">Widen Owner</button>
<button type="button" id="remove">Remove Task</button>
</div>
<div id="grid" style="height: 200px"></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, task: 'Fix login screen', owner: 'Liam Carter', done: false },
{ id: 2, task: 'Review payment flow', owner: 'Ethan Clark', done: true },
{ id: 3, task: 'New icon set', owner: 'Emma Stone', done: false },
{ id: 4, task: 'Deployment check', owner: 'Olivia Reed', done: false },
];
// A custom header renderer: the factory returns an object with mount(el, ctx), update(ctx) and destroy().
// Even when a width or order change redraws the header, mount runs once, only update is called and the element state is kept.
let say = () => { };
const counter = () => {
let clicks = 0;
let node = null;
return {
mount(el, ctx) {
say(`mount(${ctx.columnId})`);
node = el.ownerDocument.createElement('button');
node.type = 'button';
node.tabIndex = -1;
node.addEventListener('click', () => {
clicks += 1;
node.textContent = `Clicks ${clicks}`;
});
node.textContent = `Clicks ${clicks}`;
el.append(node);
},
update() {
say('update: the same element moved to the new header cell (count kept)');
},
destroy() {
say('destroy');
},
};
};
const options = {
columns: [
{ id: 'task', title: 'Task', width: 170, headerRenderer: counter },
{ id: 'owner', title: 'Owner', width: 100 },
{ id: 'done', title: 'Done', kind: 'boolean', width: 90 },
],
rows,
rowKey: 'id',
};
function setup(_api, log) {
say = log;
log('Press the button in the Task header a few times, then drag a column width. The count stays.');
}
const actions = {
widen: (api) => api.updateColumn('owner', { width: 160 }),
// Remove the column only if it exists, so pressing again after removal does not raise an error.
remove: (api) => {
if (api.getColumns().some((c) => c.id === 'task'))
api.removeColumn('task');
},
};
options.ariaLabel = "A custom header renderer";
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('widen').addEventListener('click', () => actions.widen(api));
document.getElementById('remove').addEventListener('click', () => actions.remove(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.widen(api)}
>Widen Owner</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.remove(api)}
>Remove Task</button>
</div>
<Grid style={{ height: 200 }} 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;
done: boolean;
}
const rows: Row[] = [
{ id: 1, task: 'Fix login screen', owner: 'Liam Carter', done: false },
{ id: 2, task: 'Review payment flow', owner: 'Ethan Clark', done: true },
{ id: 3, task: 'New icon set', owner: 'Emma Stone', done: false },
{ id: 4, task: 'Deployment check', owner: 'Olivia Reed', done: false },
];
// A custom header renderer: the factory returns an object with mount(el, ctx), update(ctx) and destroy().
// Even when a width or order change redraws the header, mount runs once, only update is called and the element state is kept.
let say: (message: LogText) => void = () => {};
const counter = () => {
let clicks = 0;
let node: HTMLButtonElement | null = null;
return {
mount(el: HTMLElement, ctx: { columnId: string; params: unknown }) {
say(`mount(${ctx.columnId})`);
node = el.ownerDocument.createElement('button');
node.type = 'button';
node.tabIndex = -1;
node.addEventListener('click', () => {
clicks += 1;
node!.textContent = `Clicks ${clicks}`;
});
node.textContent = `Clicks ${clicks}`;
el.append(node);
},
update() {
say('update: the same element moved to the new header cell (count kept)');
},
destroy() {
say('destroy');
},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'task', title: 'Task', width: 170, headerRenderer: counter },
{ id: 'owner', title: 'Owner', width: 100 },
{ id: 'done', title: 'Done', kind: 'boolean', width: 90 },
],
rows,
rowKey: 'id',
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(
'Press the button in the Task header a few times, then drag a column width. The count stays.',
);
}
export const actions = {
widen: (api: GridApi<Row>) => api.updateColumn('owner', { width: 160 }),
// Remove the column only if it exists, so pressing again after removal does not raise an error.
remove: (api: GridApi<Row>) => {
if (api.getColumns().some((c) => c.id === 'task')) api.removeColumn('task');
},
};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.widen(api)">Widen Owner</button>
<button type="button" :disabled="!api" @click="api && actions.remove(api)">Remove Task</button>
</div>
<Grid style="height: 200px" :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;
done: boolean;
}
const rows: Row[] = [
{ id: 1, task: 'Fix login screen', owner: 'Liam Carter', done: false },
{ id: 2, task: 'Review payment flow', owner: 'Ethan Clark', done: true },
{ id: 3, task: 'New icon set', owner: 'Emma Stone', done: false },
{ id: 4, task: 'Deployment check', owner: 'Olivia Reed', done: false },
];
// A custom header renderer: the factory returns an object with mount(el, ctx), update(ctx) and destroy().
// Even when a width or order change redraws the header, mount runs once, only update is called and the element state is kept.
let say: (message: LogText) => void = () => {};
const counter = () => {
let clicks = 0;
let node: HTMLButtonElement | null = null;
return {
mount(el: HTMLElement, ctx: { columnId: string; params: unknown }) {
say(`mount(${ctx.columnId})`);
node = el.ownerDocument.createElement('button');
node.type = 'button';
node.tabIndex = -1;
node.addEventListener('click', () => {
clicks += 1;
node!.textContent = `Clicks ${clicks}`;
});
node.textContent = `Clicks ${clicks}`;
el.append(node);
},
update() {
say('update: the same element moved to the new header cell (count kept)');
},
destroy() {
say('destroy');
},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'task', title: 'Task', width: 170, headerRenderer: counter },
{ id: 'owner', title: 'Owner', width: 100 },
{ id: 'done', title: 'Done', kind: 'boolean', width: 90 },
],
rows,
rowKey: 'id',
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(
'Press the button in the Task header a few times, then drag a column width. The count stays.',
);
}
export const actions = {
widen: (api: GridApi<Row>) => api.updateColumn('owner', { width: 160 }),
// Remove the column only if it exists, so pressing again after removal does not raise an error.
remove: (api: GridApi<Row>) => {
if (api.getColumns().some((c) => c.id === 'task')) api.removeColumn('task');
},
};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.widen(api)"
>Widen Owner</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.remove(api)"
>Remove Task</button>
</div>
<mx-grid style="height: 200px" [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;
done: boolean;
}
const rows: Row[] = [
{ id: 1, task: 'Fix login screen', owner: 'Liam Carter', done: false },
{ id: 2, task: 'Review payment flow', owner: 'Ethan Clark', done: true },
{ id: 3, task: 'New icon set', owner: 'Emma Stone', done: false },
{ id: 4, task: 'Deployment check', owner: 'Olivia Reed', done: false },
];
// A custom header renderer: the factory returns an object with mount(el, ctx), update(ctx) and destroy().
// Even when a width or order change redraws the header, mount runs once, only update is called and the element state is kept.
let say: (message: LogText) => void = () => {};
const counter = () => {
let clicks = 0;
let node: HTMLButtonElement | null = null;
return {
mount(el: HTMLElement, ctx: { columnId: string; params: unknown }) {
say(`mount(${ctx.columnId})`);
node = el.ownerDocument.createElement('button');
node.type = 'button';
node.tabIndex = -1;
node.addEventListener('click', () => {
clicks += 1;
node!.textContent = `Clicks ${clicks}`;
});
node.textContent = `Clicks ${clicks}`;
el.append(node);
},
update() {
say('update: the same element moved to the new header cell (count kept)');
},
destroy() {
say('destroy');
},
};
};
export const options: GridOptions<Row> = {
columns: [
{ id: 'task', title: 'Task', width: 170, headerRenderer: counter },
{ id: 'owner', title: 'Owner', width: 100 },
{ id: 'done', title: 'Done', kind: 'boolean', width: 90 },
],
rows,
rowKey: 'id',
};
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log(
'Press the button in the Task header a few times, then drag a column width. The count stays.',
);
}
export const actions = {
widen: (api: GridApi<Row>) => api.updateColumn('owner', { width: 160 }),
// Remove the column only if it exists, so pressing again after removal does not raise an error.
remove: (api: GridApi<Row>) => {
if (api.getColumns().some((c) => c.id === 'task')) api.removeColumn('task');
},
};