조건에 맞는 행과 칸에 색 입히기Style rows and cells by a rule
지역이 서울인 행, 상품이 노트북인 칸, 금액이 100만 원 넘는 칸처럼 조건에 맞는 곳에만 스타일을 입혀요. 조건에 맞으면 스타일 이름만 돌려주고, 색은 CSS가 정해요.Style whole rows or single cells that match a rule, such as a region, a product or a large amount. Return only a style name for matches and CSS decides the look.
코드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">
<select aria-label="강조할 지역(행)" id="region">
<option value="seoul" selected>서울</option>
<option value="busan">부산</option>
<option value="jeju">제주</option>
<option value="none">강조 안 함</option>
</select>
<select aria-label="강조할 상품(칸)" id="product">
<option value="laptop" selected>노트북</option>
<option value="monitor">모니터</option>
<option value="webcam">웹캠</option>
<option value="none">강조 안 함</option>
</select>
<select aria-label="100만 원 이상 금액" id="amount">
<option value="on" selected>눈에 띄게</option>
<option value="off">그대로</option>
</select>
<button type="button" id="boost">부산 행 금액 높이기</button>
</div>
<div id="grid" style="height: 420px"></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);
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('product').addEventListener('change', (event) => actions.product(api, event.target.value));
document.getElementById('amount').addEventListener('change', (event) => actions.amount(api, event.target.value));
document.getElementById('boost').addEventListener('click', () => actions.boost(api));const regions = ['서울', '부산', '대구', '제주'];
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
const products = ['노트북', '모니터', '무선 키보드', '웹캠', '도킹 스테이션'];
const statuses = ['결제 완료', '배송 중', '배송 완료', '취소'];
// 지금 어떤 기준으로 강조할지는 이 변수 세 개가 정해요. 버튼은 값을 바꾸고 api.refresh()로 다시 그려요.
let highlightRegion = '서울';
let highlightProduct = '노트북';
let bigAmount = 'on';
// rowClass는 행 전체, cellClass는 칸 하나에 CSS 클래스 이름을 붙여요. 색은 아래 CSS에서 정해요.
// 둘 다 화면을 그릴 때마다 불려서, 데이터가 바뀌거나 기준이 바뀌면 스타일도 따라가요.
export const options = {
columns: [
{ id: 'region', title: '지역', width: 80 },
{ id: 'customer', title: '고객사', width: 130 },
{
id: 'product',
title: '상품',
width: 140,
cellClass: (ctx) => highlightProduct !== '없음' && ctx.value === highlightProduct ? 'st-product' : undefined,
},
{ id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
cellClass: (ctx) => bigAmount === 'on' && Number(ctx.value) >= 1000000 ? 'st-big' : undefined,
},
{
id: 'status',
title: '상태',
width: 110,
cellClass: (ctx) => (ctx.value === '취소' ? 'st-cancel' : undefined),
},
],
rows: Array.from({ length: 14 }, (_, i) => ({
id: i + 1,
region: regions[(i * 3) % 4],
customer: customers[i % 6],
product: products[(i * 2) % 5],
quantity: 1 + ((i * 3) % 9),
amount: 89000 + ((i * 391000) % 2300000),
status: statuses[(i * 5) % 4],
})),
rowKey: 'id',
rowClass: (row) => highlightRegion !== '없음' && row.region === highlightRegion ? 'st-region' : undefined,
};
// 스타일 규칙은 예제 안에서 넣었다가, 예제가 끝나면 지워요(접두사 st-로 다른 CSS와 겹치지 않게 해요). 색은 테마 색을 따라가서 밝은 화면과 어두운 화면 모두에서 읽혀요.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
export function setup(api) {
highlightRegion = '서울';
highlightProduct = '노트북';
bigAmount = 'on';
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
api.refresh();
return () => style.remove();
}
// 컨트롤 값은 영문 id(seoul·none 같은)이고, 표의 지역·상품 글자로 바꿔서 써요.
const regionOf = { seoul: '서울', busan: '부산', jeju: '제주' };
const productOf = { laptop: '노트북', monitor: '모니터', webcam: '웹캠' };
export const actions = {
region: (api, value) => {
highlightRegion = regionOf[value ?? 'none'] ?? '없음';
api.refresh();
},
product: (api, value) => {
highlightProduct = productOf[value ?? 'none'] ?? '없음';
api.refresh();
},
amount: (api, value) => {
bigAmount = value ?? 'off';
api.refresh();
},
// 데이터가 바뀌면 스타일도 바로 따라와요: 100만 원이 안 되는 부산 행 하나를 240만 원으로 바꿔요.
boost: (api) => {
const row = api.getRows().find((r) => r.region === '부산' && r.amount < 1000000);
if (row)
api.updateRows([{ ...row, amount: 2400000 }]);
},
};<!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">
<select aria-label="강조할 지역(행)" id="region">
<option value="seoul" selected>서울</option>
<option value="busan">부산</option>
<option value="jeju">제주</option>
<option value="none">강조 안 함</option>
</select>
<select aria-label="강조할 상품(칸)" id="product">
<option value="laptop" selected>노트북</option>
<option value="monitor">모니터</option>
<option value="webcam">웹캠</option>
<option value="none">강조 안 함</option>
</select>
<select aria-label="100만 원 이상 금액" id="amount">
<option value="on" selected>눈에 띄게</option>
<option value="off">그대로</option>
</select>
<button type="button" id="boost">부산 행 금액 높이기</button>
</div>
<div id="grid" style="height: 420px"></div>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const regions = ['서울', '부산', '대구', '제주'];
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
const products = ['노트북', '모니터', '무선 키보드', '웹캠', '도킹 스테이션'];
const statuses = ['결제 완료', '배송 중', '배송 완료', '취소'];
// 지금 어떤 기준으로 강조할지는 이 변수 세 개가 정해요. 버튼은 값을 바꾸고 api.refresh()로 다시 그려요.
let highlightRegion = '서울';
let highlightProduct = '노트북';
let bigAmount = 'on';
// rowClass는 행 전체, cellClass는 칸 하나에 CSS 클래스 이름을 붙여요. 색은 아래 CSS에서 정해요.
// 둘 다 화면을 그릴 때마다 불려서, 데이터가 바뀌거나 기준이 바뀌면 스타일도 따라가요.
const options = {
columns: [
{ id: 'region', title: '지역', width: 80 },
{ id: 'customer', title: '고객사', width: 130 },
{
id: 'product',
title: '상품',
width: 140,
cellClass: (ctx) => highlightProduct !== '없음' && ctx.value === highlightProduct ? 'st-product' : undefined,
},
{ id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
cellClass: (ctx) => bigAmount === 'on' && Number(ctx.value) >= 1000000 ? 'st-big' : undefined,
},
{
id: 'status',
title: '상태',
width: 110,
cellClass: (ctx) => (ctx.value === '취소' ? 'st-cancel' : undefined),
},
],
rows: Array.from({ length: 14 }, (_, i) => ({
id: i + 1,
region: regions[(i * 3) % 4],
customer: customers[i % 6],
product: products[(i * 2) % 5],
quantity: 1 + ((i * 3) % 9),
amount: 89000 + ((i * 391000) % 2300000),
status: statuses[(i * 5) % 4],
})),
rowKey: 'id',
rowClass: (row) => highlightRegion !== '없음' && row.region === highlightRegion ? 'st-region' : undefined,
};
// 스타일 규칙은 예제 안에서 넣었다가, 예제가 끝나면 지워요(접두사 st-로 다른 CSS와 겹치지 않게 해요). 색은 테마 색을 따라가서 밝은 화면과 어두운 화면 모두에서 읽혀요.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
function setup(api) {
highlightRegion = '서울';
highlightProduct = '노트북';
bigAmount = 'on';
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
api.refresh();
return () => style.remove();
}
// 컨트롤 값은 영문 id(seoul·none 같은)이고, 표의 지역·상품 글자로 바꿔서 써요.
const regionOf = { seoul: '서울', busan: '부산', jeju: '제주' };
const productOf = { laptop: '노트북', monitor: '모니터', webcam: '웹캠' };
const actions = {
region: (api, value) => {
highlightRegion = regionOf[value ?? 'none'] ?? '없음';
api.refresh();
},
product: (api, value) => {
highlightProduct = productOf[value ?? 'none'] ?? '없음';
api.refresh();
},
amount: (api, value) => {
bigAmount = value ?? 'off';
api.refresh();
},
// 데이터가 바뀌면 스타일도 바로 따라와요: 100만 원이 안 되는 부산 행 하나를 240만 원으로 바꿔요.
boost: (api) => {
const row = api.getRows().find((r) => r.region === '부산' && r.amount < 1000000);
if (row)
api.updateRows([{ ...row, amount: 2400000 }]);
},
};
options.ariaLabel = "조건에 맞는 행과 칸에 색 입히기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api);
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('product').addEventListener('change', (event) => actions.product(api, event.target.value));
document.getElementById('amount').addEventListener('change', (event) => actions.amount(api, event.target.value));
document.getElementById('boost').addEventListener('click', () => actions.boost(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) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="강조할 지역(행)"
disabled={!api}
onChange={(event) => api && actions.region(api, event.target.value)}
>
<option value="seoul">서울</option>
<option value="busan">부산</option>
<option value="jeju">제주</option>
<option value="none">강조 안 함</option>
</select>
<select defaultValue="seoul"
aria-label="강조할 상품(칸)"
disabled={!api}
onChange={(event) => api && actions.product(api, event.target.value)}
>
<option value="laptop">노트북</option>
<option value="monitor">모니터</option>
<option value="webcam">웹캠</option>
<option value="none">강조 안 함</option>
</select>
<select defaultValue="laptop"
aria-label="100만 원 이상 금액"
disabled={!api}
onChange={(event) => api && actions.amount(api, event.target.value)}
>
<option value="on">눈에 띄게</option>
<option value="off">그대로</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.boost(api)}
>부산 행 금액 높이기</button>
</div>
<Grid style={{ height: 420 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export interface Row {
id: number;
region: string;
customer: string;
product: string;
quantity: number;
amount: number;
status: string;
}
const regions = ['서울', '부산', '대구', '제주'];
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
const products = ['노트북', '모니터', '무선 키보드', '웹캠', '도킹 스테이션'];
const statuses = ['결제 완료', '배송 중', '배송 완료', '취소'];
// 지금 어떤 기준으로 강조할지는 이 변수 세 개가 정해요. 버튼은 값을 바꾸고 api.refresh()로 다시 그려요.
let highlightRegion = '서울';
let highlightProduct = '노트북';
let bigAmount = 'on';
// rowClass는 행 전체, cellClass는 칸 하나에 CSS 클래스 이름을 붙여요. 색은 아래 CSS에서 정해요.
// 둘 다 화면을 그릴 때마다 불려서, 데이터가 바뀌거나 기준이 바뀌면 스타일도 따라가요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: '지역', width: 80 },
{ id: 'customer', title: '고객사', width: 130 },
{
id: 'product',
title: '상품',
width: 140,
cellClass: (ctx) =>
highlightProduct !== '없음' && ctx.value === highlightProduct ? 'st-product' : undefined,
},
{ id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
cellClass: (ctx) =>
bigAmount === 'on' && Number(ctx.value) >= 1000000 ? 'st-big' : undefined,
},
{
id: 'status',
title: '상태',
width: 110,
cellClass: (ctx) => (ctx.value === '취소' ? 'st-cancel' : undefined),
},
],
rows: Array.from({ length: 14 }, (_, i) => ({
id: i + 1,
region: regions[(i * 3) % 4] as string,
customer: customers[i % 6] as string,
product: products[(i * 2) % 5] as string,
quantity: 1 + ((i * 3) % 9),
amount: 89000 + ((i * 391000) % 2300000),
status: statuses[(i * 5) % 4] as string,
})),
rowKey: 'id',
rowClass: (row) =>
highlightRegion !== '없음' && row.region === highlightRegion ? 'st-region' : undefined,
};
// 스타일 규칙은 예제 안에서 넣었다가, 예제가 끝나면 지워요(접두사 st-로 다른 CSS와 겹치지 않게 해요). 색은 테마 색을 따라가서 밝은 화면과 어두운 화면 모두에서 읽혀요.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
export function setup(api: GridApi<Row>) {
highlightRegion = '서울';
highlightProduct = '노트북';
bigAmount = 'on';
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
api.refresh();
return () => style.remove();
}
// 컨트롤 값은 영문 id(seoul·none 같은)이고, 표의 지역·상품 글자로 바꿔서 써요.
const regionOf: Record<string, string> = { seoul: '서울', busan: '부산', jeju: '제주' };
const productOf: Record<string, string> = { laptop: '노트북', monitor: '모니터', webcam: '웹캠' };
export const actions = {
region: (api: GridApi<Row>, value?: string) => {
highlightRegion = regionOf[value ?? 'none'] ?? '없음';
api.refresh();
},
product: (api: GridApi<Row>, value?: string) => {
highlightProduct = productOf[value ?? 'none'] ?? '없음';
api.refresh();
},
amount: (api: GridApi<Row>, value?: string) => {
bigAmount = value ?? 'off';
api.refresh();
},
// 데이터가 바뀌면 스타일도 바로 따라와요: 100만 원이 안 되는 부산 행 하나를 240만 원으로 바꿔요.
boost: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => r.region === '부산' && r.amount < 1000000);
if (row) api.updateRows([{ ...row, amount: 2400000 }]);
},
};버튼을 누르면 이 예제의 코드가 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);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="강조할 지역(행)"
:disabled="!api"
@change="api && actions.region(api, ($event.target as HTMLSelectElement).value)"
>
<option value="seoul" selected>서울</option>
<option value="busan">부산</option>
<option value="jeju">제주</option>
<option value="none">강조 안 함</option>
</select>
<select
aria-label="강조할 상품(칸)"
:disabled="!api"
@change="api && actions.product(api, ($event.target as HTMLSelectElement).value)"
>
<option value="laptop" selected>노트북</option>
<option value="monitor">모니터</option>
<option value="webcam">웹캠</option>
<option value="none">강조 안 함</option>
</select>
<select
aria-label="100만 원 이상 금액"
:disabled="!api"
@change="api && actions.amount(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>눈에 띄게</option>
<option value="off">그대로</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.boost(api)">부산 행 금액 높이기</button>
</div>
<Grid style="height: 420px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export interface Row {
id: number;
region: string;
customer: string;
product: string;
quantity: number;
amount: number;
status: string;
}
const regions = ['서울', '부산', '대구', '제주'];
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
const products = ['노트북', '모니터', '무선 키보드', '웹캠', '도킹 스테이션'];
const statuses = ['결제 완료', '배송 중', '배송 완료', '취소'];
// 지금 어떤 기준으로 강조할지는 이 변수 세 개가 정해요. 버튼은 값을 바꾸고 api.refresh()로 다시 그려요.
let highlightRegion = '서울';
let highlightProduct = '노트북';
let bigAmount = 'on';
// rowClass는 행 전체, cellClass는 칸 하나에 CSS 클래스 이름을 붙여요. 색은 아래 CSS에서 정해요.
// 둘 다 화면을 그릴 때마다 불려서, 데이터가 바뀌거나 기준이 바뀌면 스타일도 따라가요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: '지역', width: 80 },
{ id: 'customer', title: '고객사', width: 130 },
{
id: 'product',
title: '상품',
width: 140,
cellClass: (ctx) =>
highlightProduct !== '없음' && ctx.value === highlightProduct ? 'st-product' : undefined,
},
{ id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
cellClass: (ctx) =>
bigAmount === 'on' && Number(ctx.value) >= 1000000 ? 'st-big' : undefined,
},
{
id: 'status',
title: '상태',
width: 110,
cellClass: (ctx) => (ctx.value === '취소' ? 'st-cancel' : undefined),
},
],
rows: Array.from({ length: 14 }, (_, i) => ({
id: i + 1,
region: regions[(i * 3) % 4] as string,
customer: customers[i % 6] as string,
product: products[(i * 2) % 5] as string,
quantity: 1 + ((i * 3) % 9),
amount: 89000 + ((i * 391000) % 2300000),
status: statuses[(i * 5) % 4] as string,
})),
rowKey: 'id',
rowClass: (row) =>
highlightRegion !== '없음' && row.region === highlightRegion ? 'st-region' : undefined,
};
// 스타일 규칙은 예제 안에서 넣었다가, 예제가 끝나면 지워요(접두사 st-로 다른 CSS와 겹치지 않게 해요). 색은 테마 색을 따라가서 밝은 화면과 어두운 화면 모두에서 읽혀요.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
export function setup(api: GridApi<Row>) {
highlightRegion = '서울';
highlightProduct = '노트북';
bigAmount = 'on';
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
api.refresh();
return () => style.remove();
}
// 컨트롤 값은 영문 id(seoul·none 같은)이고, 표의 지역·상품 글자로 바꿔서 써요.
const regionOf: Record<string, string> = { seoul: '서울', busan: '부산', jeju: '제주' };
const productOf: Record<string, string> = { laptop: '노트북', monitor: '모니터', webcam: '웹캠' };
export const actions = {
region: (api: GridApi<Row>, value?: string) => {
highlightRegion = regionOf[value ?? 'none'] ?? '없음';
api.refresh();
},
product: (api: GridApi<Row>, value?: string) => {
highlightProduct = productOf[value ?? 'none'] ?? '없음';
api.refresh();
},
amount: (api: GridApi<Row>, value?: string) => {
bigAmount = value ?? 'off';
api.refresh();
},
// 데이터가 바뀌면 스타일도 바로 따라와요: 100만 원이 안 되는 부산 행 하나를 240만 원으로 바꿔요.
boost: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => r.region === '부산' && r.amount < 1000000);
if (row) api.updateRows([{ ...row, amount: 2400000 }]);
},
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="강조할 지역(행)"
[disabled]="!api"
(change)="api && actions.region(api, $any($event.target).value)"
>
<option value="seoul" selected>서울</option>
<option value="busan">부산</option>
<option value="jeju">제주</option>
<option value="none">강조 안 함</option>
</select>
<select
aria-label="강조할 상품(칸)"
[disabled]="!api"
(change)="api && actions.product(api, $any($event.target).value)"
>
<option value="laptop" selected>노트북</option>
<option value="monitor">모니터</option>
<option value="webcam">웹캠</option>
<option value="none">강조 안 함</option>
</select>
<select
aria-label="100만 원 이상 금액"
[disabled]="!api"
(change)="api && actions.amount(api, $any($event.target).value)"
>
<option value="on" selected>눈에 띄게</option>
<option value="off">그대로</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.boost(api)"
>부산 행 금액 높이기</button>
</div>
<mx-grid style="height: 420px" [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);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export interface Row {
id: number;
region: string;
customer: string;
product: string;
quantity: number;
amount: number;
status: string;
}
const regions = ['서울', '부산', '대구', '제주'];
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
const products = ['노트북', '모니터', '무선 키보드', '웹캠', '도킹 스테이션'];
const statuses = ['결제 완료', '배송 중', '배송 완료', '취소'];
// 지금 어떤 기준으로 강조할지는 이 변수 세 개가 정해요. 버튼은 값을 바꾸고 api.refresh()로 다시 그려요.
let highlightRegion = '서울';
let highlightProduct = '노트북';
let bigAmount = 'on';
// rowClass는 행 전체, cellClass는 칸 하나에 CSS 클래스 이름을 붙여요. 색은 아래 CSS에서 정해요.
// 둘 다 화면을 그릴 때마다 불려서, 데이터가 바뀌거나 기준이 바뀌면 스타일도 따라가요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: '지역', width: 80 },
{ id: 'customer', title: '고객사', width: 130 },
{
id: 'product',
title: '상품',
width: 140,
cellClass: (ctx) =>
highlightProduct !== '없음' && ctx.value === highlightProduct ? 'st-product' : undefined,
},
{ id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
{
id: 'amount',
title: '금액(원)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
cellClass: (ctx) =>
bigAmount === 'on' && Number(ctx.value) >= 1000000 ? 'st-big' : undefined,
},
{
id: 'status',
title: '상태',
width: 110,
cellClass: (ctx) => (ctx.value === '취소' ? 'st-cancel' : undefined),
},
],
rows: Array.from({ length: 14 }, (_, i) => ({
id: i + 1,
region: regions[(i * 3) % 4] as string,
customer: customers[i % 6] as string,
product: products[(i * 2) % 5] as string,
quantity: 1 + ((i * 3) % 9),
amount: 89000 + ((i * 391000) % 2300000),
status: statuses[(i * 5) % 4] as string,
})),
rowKey: 'id',
rowClass: (row) =>
highlightRegion !== '없음' && row.region === highlightRegion ? 'st-region' : undefined,
};
// 스타일 규칙은 예제 안에서 넣었다가, 예제가 끝나면 지워요(접두사 st-로 다른 CSS와 겹치지 않게 해요). 색은 테마 색을 따라가서 밝은 화면과 어두운 화면 모두에서 읽혀요.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
export function setup(api: GridApi<Row>) {
highlightRegion = '서울';
highlightProduct = '노트북';
bigAmount = 'on';
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
api.refresh();
return () => style.remove();
}
// 컨트롤 값은 영문 id(seoul·none 같은)이고, 표의 지역·상품 글자로 바꿔서 써요.
const regionOf: Record<string, string> = { seoul: '서울', busan: '부산', jeju: '제주' };
const productOf: Record<string, string> = { laptop: '노트북', monitor: '모니터', webcam: '웹캠' };
export const actions = {
region: (api: GridApi<Row>, value?: string) => {
highlightRegion = regionOf[value ?? 'none'] ?? '없음';
api.refresh();
},
product: (api: GridApi<Row>, value?: string) => {
highlightProduct = productOf[value ?? 'none'] ?? '없음';
api.refresh();
},
amount: (api: GridApi<Row>, value?: string) => {
bigAmount = value ?? 'off';
api.refresh();
},
// 데이터가 바뀌면 스타일도 바로 따라와요: 100만 원이 안 되는 부산 행 하나를 240만 원으로 바꿔요.
boost: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => r.region === '부산' && r.amount < 1000000);
if (row) api.updateRows([{ ...row, amount: 2400000 }]);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<select aria-label="Row highlight: region" id="region">
<option value="seoul" selected>Seoul</option>
<option value="busan">Busan</option>
<option value="jeju">Jeju</option>
<option value="none">None</option>
</select>
<select aria-label="Cell highlight: product" id="product">
<option value="laptop" selected>Laptop</option>
<option value="monitor">Monitor</option>
<option value="webcam">Webcam</option>
<option value="none">None</option>
</select>
<select aria-label="Amounts over $1K" id="amount">
<option value="on" selected>Highlight</option>
<option value="off">Plain</option>
</select>
<button type="button" id="boost">Boost a Busan amount</button>
</div>
<div id="grid" style="height: 420px"></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);
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('product').addEventListener('change', (event) => actions.product(api, event.target.value));
document.getElementById('amount').addEventListener('change', (event) => actions.amount(api, event.target.value));
document.getElementById('boost').addEventListener('click', () => actions.boost(api));const regions = ['Seoul', 'Busan', 'Daegu', 'Jeju'];
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Dawn Commerce',
'Sunrise Farm',
'Moda Fashion',
];
const products = ['Laptop', 'Monitor', 'Wireless Keyboard', 'Webcam', 'Docking Station'];
const statuses = ['Paid', 'Shipping', 'Delivered', 'Cancelled'];
// Control values are English ids (seoul, laptop, none ...); they are mapped to the values in the data.
const NONE = 'none';
const REGION = { seoul: 'Seoul', busan: 'Busan', jeju: 'Jeju' };
const PRODUCT = { laptop: 'Laptop', monitor: 'Monitor', webcam: 'Webcam' };
const toRegion = (value) => REGION[value ?? NONE] ?? NONE;
const toProduct = (value) => PRODUCT[value ?? NONE] ?? NONE;
// These three variables decide what is highlighted now. A button changes the value and redraws with api.refresh().
let highlightRegion = 'Seoul';
let highlightProduct = 'Laptop';
let bigAmount = 'on';
// rowClass attaches a CSS class name to a whole row, cellClass to a single cell. The colors are set in the CSS below.
// Both are called each time the screen is drawn, so the styles follow when the data or the rule changes.
export const options = {
columns: [
{ id: 'region', title: 'Region', width: 80 },
{ id: 'customer', title: 'Customer', width: 150 },
{
id: 'product',
title: 'Product',
width: 160,
cellClass: (ctx) => highlightProduct !== NONE && ctx.value === highlightProduct ? 'st-product' : undefined,
},
{ id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
cellClass: (ctx) => (bigAmount === 'on' && Number(ctx.value) >= 1000 ? 'st-big' : undefined),
},
{
id: 'status',
title: 'Status',
width: 110,
cellClass: (ctx) => (ctx.value === 'Cancelled' ? 'st-cancel' : undefined),
},
],
rows: Array.from({ length: 14 }, (_, i) => ({
id: i + 1,
region: regions[(i * 3) % 4],
customer: customers[i % 6],
product: products[(i * 2) % 5],
quantity: 1 + ((i * 3) % 9),
amount: 89 + ((i * 391) % 2300),
status: statuses[(i * 5) % 4],
})),
rowKey: 'id',
rowClass: (row) => highlightRegion !== NONE && row.region === highlightRegion ? 'st-region' : undefined,
};
// The style rules are added inside the example and removed when it ends (the st- prefix keeps them from clashing with other CSS). Colors follow the theme, so they read on both light and dark screens.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
export function setup(api) {
highlightRegion = 'Seoul';
highlightProduct = 'Laptop';
bigAmount = 'on';
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
api.refresh();
return () => style.remove();
}
export const actions = {
region: (api, value) => {
highlightRegion = toRegion(value);
api.refresh();
},
product: (api, value) => {
highlightProduct = toProduct(value);
api.refresh();
},
amount: (api, value) => {
bigAmount = value ?? 'off';
api.refresh();
},
// When the data changes, the style follows at once: change one Busan row under $1,000 to $2,400.
boost: (api) => {
const row = api.getRows().find((r) => r.region === 'Busan' && r.amount < 1000);
if (row)
api.updateRows([{ ...row, amount: 2400 }]);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Style rows and cells by a rule</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Row highlight: region" id="region">
<option value="seoul" selected>Seoul</option>
<option value="busan">Busan</option>
<option value="jeju">Jeju</option>
<option value="none">None</option>
</select>
<select aria-label="Cell highlight: product" id="product">
<option value="laptop" selected>Laptop</option>
<option value="monitor">Monitor</option>
<option value="webcam">Webcam</option>
<option value="none">None</option>
</select>
<select aria-label="Amounts over $1K" id="amount">
<option value="on" selected>Highlight</option>
<option value="off">Plain</option>
</select>
<button type="button" id="boost">Boost a Busan amount</button>
</div>
<div id="grid" style="height: 420px"></div>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const regions = ['Seoul', 'Busan', 'Daegu', 'Jeju'];
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Dawn Commerce',
'Sunrise Farm',
'Moda Fashion',
];
const products = ['Laptop', 'Monitor', 'Wireless Keyboard', 'Webcam', 'Docking Station'];
const statuses = ['Paid', 'Shipping', 'Delivered', 'Cancelled'];
// Control values are English ids (seoul, laptop, none ...); they are mapped to the values in the data.
const NONE = 'none';
const REGION = { seoul: 'Seoul', busan: 'Busan', jeju: 'Jeju' };
const PRODUCT = { laptop: 'Laptop', monitor: 'Monitor', webcam: 'Webcam' };
const toRegion = (value) => REGION[value ?? NONE] ?? NONE;
const toProduct = (value) => PRODUCT[value ?? NONE] ?? NONE;
// These three variables decide what is highlighted now. A button changes the value and redraws with api.refresh().
let highlightRegion = 'Seoul';
let highlightProduct = 'Laptop';
let bigAmount = 'on';
// rowClass attaches a CSS class name to a whole row, cellClass to a single cell. The colors are set in the CSS below.
// Both are called each time the screen is drawn, so the styles follow when the data or the rule changes.
const options = {
columns: [
{ id: 'region', title: 'Region', width: 80 },
{ id: 'customer', title: 'Customer', width: 150 },
{
id: 'product',
title: 'Product',
width: 160,
cellClass: (ctx) => highlightProduct !== NONE && ctx.value === highlightProduct ? 'st-product' : undefined,
},
{ id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
cellClass: (ctx) => (bigAmount === 'on' && Number(ctx.value) >= 1000 ? 'st-big' : undefined),
},
{
id: 'status',
title: 'Status',
width: 110,
cellClass: (ctx) => (ctx.value === 'Cancelled' ? 'st-cancel' : undefined),
},
],
rows: Array.from({ length: 14 }, (_, i) => ({
id: i + 1,
region: regions[(i * 3) % 4],
customer: customers[i % 6],
product: products[(i * 2) % 5],
quantity: 1 + ((i * 3) % 9),
amount: 89 + ((i * 391) % 2300),
status: statuses[(i * 5) % 4],
})),
rowKey: 'id',
rowClass: (row) => highlightRegion !== NONE && row.region === highlightRegion ? 'st-region' : undefined,
};
// The style rules are added inside the example and removed when it ends (the st- prefix keeps them from clashing with other CSS). Colors follow the theme, so they read on both light and dark screens.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
function setup(api) {
highlightRegion = 'Seoul';
highlightProduct = 'Laptop';
bigAmount = 'on';
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
api.refresh();
return () => style.remove();
}
const actions = {
region: (api, value) => {
highlightRegion = toRegion(value);
api.refresh();
},
product: (api, value) => {
highlightProduct = toProduct(value);
api.refresh();
},
amount: (api, value) => {
bigAmount = value ?? 'off';
api.refresh();
},
// When the data changes, the style follows at once: change one Busan row under $1,000 to $2,400.
boost: (api) => {
const row = api.getRows().find((r) => r.region === 'Busan' && r.amount < 1000);
if (row)
api.updateRows([{ ...row, amount: 2400 }]);
},
};
options.ariaLabel = "Style rows and cells by a rule";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api);
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('product').addEventListener('change', (event) => actions.product(api, event.target.value));
document.getElementById('amount').addEventListener('change', (event) => actions.amount(api, event.target.value));
document.getElementById('boost').addEventListener('click', () => actions.boost(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) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="Row highlight: region"
disabled={!api}
onChange={(event) => api && actions.region(api, event.target.value)}
>
<option value="seoul">Seoul</option>
<option value="busan">Busan</option>
<option value="jeju">Jeju</option>
<option value="none">None</option>
</select>
<select defaultValue="seoul"
aria-label="Cell highlight: product"
disabled={!api}
onChange={(event) => api && actions.product(api, event.target.value)}
>
<option value="laptop">Laptop</option>
<option value="monitor">Monitor</option>
<option value="webcam">Webcam</option>
<option value="none">None</option>
</select>
<select defaultValue="laptop"
aria-label="Amounts over $1K"
disabled={!api}
onChange={(event) => api && actions.amount(api, event.target.value)}
>
<option value="on">Highlight</option>
<option value="off">Plain</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.boost(api)}
>Boost a Busan amount</button>
</div>
<Grid style={{ height: 420 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export interface Row {
id: number;
region: string;
customer: string;
product: string;
quantity: number;
amount: number;
status: string;
}
const regions = ['Seoul', 'Busan', 'Daegu', 'Jeju'];
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Dawn Commerce',
'Sunrise Farm',
'Moda Fashion',
];
const products = ['Laptop', 'Monitor', 'Wireless Keyboard', 'Webcam', 'Docking Station'];
const statuses = ['Paid', 'Shipping', 'Delivered', 'Cancelled'];
// Control values are English ids (seoul, laptop, none ...); they are mapped to the values in the data.
const NONE = 'none';
const REGION: Record<string, string> = { seoul: 'Seoul', busan: 'Busan', jeju: 'Jeju' };
const PRODUCT: Record<string, string> = { laptop: 'Laptop', monitor: 'Monitor', webcam: 'Webcam' };
const toRegion = (value?: string): string => REGION[value ?? NONE] ?? NONE;
const toProduct = (value?: string): string => PRODUCT[value ?? NONE] ?? NONE;
// These three variables decide what is highlighted now. A button changes the value and redraws with api.refresh().
let highlightRegion = 'Seoul';
let highlightProduct = 'Laptop';
let bigAmount = 'on';
// rowClass attaches a CSS class name to a whole row, cellClass to a single cell. The colors are set in the CSS below.
// Both are called each time the screen is drawn, so the styles follow when the data or the rule changes.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: 'Region', width: 80 },
{ id: 'customer', title: 'Customer', width: 150 },
{
id: 'product',
title: 'Product',
width: 160,
cellClass: (ctx) =>
highlightProduct !== NONE && ctx.value === highlightProduct ? 'st-product' : undefined,
},
{ id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
cellClass: (ctx) => (bigAmount === 'on' && Number(ctx.value) >= 1000 ? 'st-big' : undefined),
},
{
id: 'status',
title: 'Status',
width: 110,
cellClass: (ctx) => (ctx.value === 'Cancelled' ? 'st-cancel' : undefined),
},
],
rows: Array.from({ length: 14 }, (_, i) => ({
id: i + 1,
region: regions[(i * 3) % 4] as string,
customer: customers[i % 6] as string,
product: products[(i * 2) % 5] as string,
quantity: 1 + ((i * 3) % 9),
amount: 89 + ((i * 391) % 2300),
status: statuses[(i * 5) % 4] as string,
})),
rowKey: 'id',
rowClass: (row) =>
highlightRegion !== NONE && row.region === highlightRegion ? 'st-region' : undefined,
};
// The style rules are added inside the example and removed when it ends (the st- prefix keeps them from clashing with other CSS). Colors follow the theme, so they read on both light and dark screens.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
export function setup(api: GridApi<Row>) {
highlightRegion = 'Seoul';
highlightProduct = 'Laptop';
bigAmount = 'on';
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
api.refresh();
return () => style.remove();
}
export const actions = {
region: (api: GridApi<Row>, value?: string) => {
highlightRegion = toRegion(value);
api.refresh();
},
product: (api: GridApi<Row>, value?: string) => {
highlightProduct = toProduct(value);
api.refresh();
},
amount: (api: GridApi<Row>, value?: string) => {
bigAmount = value ?? 'off';
api.refresh();
},
// When the data changes, the style follows at once: change one Busan row under $1,000 to $2,400.
boost: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => r.region === 'Busan' && r.amount < 1000);
if (row) api.updateRows([{ ...row, amount: 2400 }]);
},
};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);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="Row highlight: region"
:disabled="!api"
@change="api && actions.region(api, ($event.target as HTMLSelectElement).value)"
>
<option value="seoul" selected>Seoul</option>
<option value="busan">Busan</option>
<option value="jeju">Jeju</option>
<option value="none">None</option>
</select>
<select
aria-label="Cell highlight: product"
:disabled="!api"
@change="api && actions.product(api, ($event.target as HTMLSelectElement).value)"
>
<option value="laptop" selected>Laptop</option>
<option value="monitor">Monitor</option>
<option value="webcam">Webcam</option>
<option value="none">None</option>
</select>
<select
aria-label="Amounts over $1K"
:disabled="!api"
@change="api && actions.amount(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>Highlight</option>
<option value="off">Plain</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.boost(api)">Boost a Busan amount</button>
</div>
<Grid style="height: 420px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export interface Row {
id: number;
region: string;
customer: string;
product: string;
quantity: number;
amount: number;
status: string;
}
const regions = ['Seoul', 'Busan', 'Daegu', 'Jeju'];
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Dawn Commerce',
'Sunrise Farm',
'Moda Fashion',
];
const products = ['Laptop', 'Monitor', 'Wireless Keyboard', 'Webcam', 'Docking Station'];
const statuses = ['Paid', 'Shipping', 'Delivered', 'Cancelled'];
// Control values are English ids (seoul, laptop, none ...); they are mapped to the values in the data.
const NONE = 'none';
const REGION: Record<string, string> = { seoul: 'Seoul', busan: 'Busan', jeju: 'Jeju' };
const PRODUCT: Record<string, string> = { laptop: 'Laptop', monitor: 'Monitor', webcam: 'Webcam' };
const toRegion = (value?: string): string => REGION[value ?? NONE] ?? NONE;
const toProduct = (value?: string): string => PRODUCT[value ?? NONE] ?? NONE;
// These three variables decide what is highlighted now. A button changes the value and redraws with api.refresh().
let highlightRegion = 'Seoul';
let highlightProduct = 'Laptop';
let bigAmount = 'on';
// rowClass attaches a CSS class name to a whole row, cellClass to a single cell. The colors are set in the CSS below.
// Both are called each time the screen is drawn, so the styles follow when the data or the rule changes.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: 'Region', width: 80 },
{ id: 'customer', title: 'Customer', width: 150 },
{
id: 'product',
title: 'Product',
width: 160,
cellClass: (ctx) =>
highlightProduct !== NONE && ctx.value === highlightProduct ? 'st-product' : undefined,
},
{ id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
cellClass: (ctx) => (bigAmount === 'on' && Number(ctx.value) >= 1000 ? 'st-big' : undefined),
},
{
id: 'status',
title: 'Status',
width: 110,
cellClass: (ctx) => (ctx.value === 'Cancelled' ? 'st-cancel' : undefined),
},
],
rows: Array.from({ length: 14 }, (_, i) => ({
id: i + 1,
region: regions[(i * 3) % 4] as string,
customer: customers[i % 6] as string,
product: products[(i * 2) % 5] as string,
quantity: 1 + ((i * 3) % 9),
amount: 89 + ((i * 391) % 2300),
status: statuses[(i * 5) % 4] as string,
})),
rowKey: 'id',
rowClass: (row) =>
highlightRegion !== NONE && row.region === highlightRegion ? 'st-region' : undefined,
};
// The style rules are added inside the example and removed when it ends (the st- prefix keeps them from clashing with other CSS). Colors follow the theme, so they read on both light and dark screens.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
export function setup(api: GridApi<Row>) {
highlightRegion = 'Seoul';
highlightProduct = 'Laptop';
bigAmount = 'on';
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
api.refresh();
return () => style.remove();
}
export const actions = {
region: (api: GridApi<Row>, value?: string) => {
highlightRegion = toRegion(value);
api.refresh();
},
product: (api: GridApi<Row>, value?: string) => {
highlightProduct = toProduct(value);
api.refresh();
},
amount: (api: GridApi<Row>, value?: string) => {
bigAmount = value ?? 'off';
api.refresh();
},
// When the data changes, the style follows at once: change one Busan row under $1,000 to $2,400.
boost: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => r.region === 'Busan' && r.amount < 1000);
if (row) api.updateRows([{ ...row, amount: 2400 }]);
},
};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">
<select
aria-label="Row highlight: region"
[disabled]="!api"
(change)="api && actions.region(api, $any($event.target).value)"
>
<option value="seoul" selected>Seoul</option>
<option value="busan">Busan</option>
<option value="jeju">Jeju</option>
<option value="none">None</option>
</select>
<select
aria-label="Cell highlight: product"
[disabled]="!api"
(change)="api && actions.product(api, $any($event.target).value)"
>
<option value="laptop" selected>Laptop</option>
<option value="monitor">Monitor</option>
<option value="webcam">Webcam</option>
<option value="none">None</option>
</select>
<select
aria-label="Amounts over $1K"
[disabled]="!api"
(change)="api && actions.amount(api, $any($event.target).value)"
>
<option value="on" selected>Highlight</option>
<option value="off">Plain</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.boost(api)"
>Boost a Busan amount</button>
</div>
<mx-grid style="height: 420px" [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);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export interface Row {
id: number;
region: string;
customer: string;
product: string;
quantity: number;
amount: number;
status: string;
}
const regions = ['Seoul', 'Busan', 'Daegu', 'Jeju'];
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Dawn Commerce',
'Sunrise Farm',
'Moda Fashion',
];
const products = ['Laptop', 'Monitor', 'Wireless Keyboard', 'Webcam', 'Docking Station'];
const statuses = ['Paid', 'Shipping', 'Delivered', 'Cancelled'];
// Control values are English ids (seoul, laptop, none ...); they are mapped to the values in the data.
const NONE = 'none';
const REGION: Record<string, string> = { seoul: 'Seoul', busan: 'Busan', jeju: 'Jeju' };
const PRODUCT: Record<string, string> = { laptop: 'Laptop', monitor: 'Monitor', webcam: 'Webcam' };
const toRegion = (value?: string): string => REGION[value ?? NONE] ?? NONE;
const toProduct = (value?: string): string => PRODUCT[value ?? NONE] ?? NONE;
// These three variables decide what is highlighted now. A button changes the value and redraws with api.refresh().
let highlightRegion = 'Seoul';
let highlightProduct = 'Laptop';
let bigAmount = 'on';
// rowClass attaches a CSS class name to a whole row, cellClass to a single cell. The colors are set in the CSS below.
// Both are called each time the screen is drawn, so the styles follow when the data or the rule changes.
export const options: GridOptions<Row> = {
columns: [
{ id: 'region', title: 'Region', width: 80 },
{ id: 'customer', title: 'Customer', width: 150 },
{
id: 'product',
title: 'Product',
width: 160,
cellClass: (ctx) =>
highlightProduct !== NONE && ctx.value === highlightProduct ? 'st-product' : undefined,
},
{ id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
{
id: 'amount',
title: 'Amount ($)',
kind: 'number',
width: 120,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
cellClass: (ctx) => (bigAmount === 'on' && Number(ctx.value) >= 1000 ? 'st-big' : undefined),
},
{
id: 'status',
title: 'Status',
width: 110,
cellClass: (ctx) => (ctx.value === 'Cancelled' ? 'st-cancel' : undefined),
},
],
rows: Array.from({ length: 14 }, (_, i) => ({
id: i + 1,
region: regions[(i * 3) % 4] as string,
customer: customers[i % 6] as string,
product: products[(i * 2) % 5] as string,
quantity: 1 + ((i * 3) % 9),
amount: 89 + ((i * 391) % 2300),
status: statuses[(i * 5) % 4] as string,
})),
rowKey: 'id',
rowClass: (row) =>
highlightRegion !== NONE && row.region === highlightRegion ? 'st-region' : undefined,
};
// The style rules are added inside the example and removed when it ends (the st- prefix keeps them from clashing with other CSS). Colors follow the theme, so they read on both light and dark screens.
const CSS = `
.mxg .mxg-row.st-region { background: color-mix(in srgb, var(--mxg-accent) 14%, var(--mxg-bg)); box-shadow: inset 3px 0 0 var(--mxg-accent); }
.mxg .mxg-cell.st-product { color: var(--mxg-tone-danger-fg); font-weight: 700; }
.mxg .mxg-cell.st-big { background: var(--mxg-bg-dirty); color: var(--mxg-tone-warning-fg); font-weight: 700; }
.mxg .mxg-cell.st-cancel { color: var(--mxg-danger); text-decoration: line-through; }
`;
export function setup(api: GridApi<Row>) {
highlightRegion = 'Seoul';
highlightProduct = 'Laptop';
bigAmount = 'on';
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
api.refresh();
return () => style.remove();
}
export const actions = {
region: (api: GridApi<Row>, value?: string) => {
highlightRegion = toRegion(value);
api.refresh();
},
product: (api: GridApi<Row>, value?: string) => {
highlightProduct = toProduct(value);
api.refresh();
},
amount: (api: GridApi<Row>, value?: string) => {
bigAmount = value ?? 'off';
api.refresh();
},
// When the data changes, the style follows at once: change one Busan row under $1,000 to $2,400.
boost: (api: GridApi<Row>) => {
const row = api.getRows().find((r) => r.region === 'Busan' && r.amount < 1000);
if (row) api.updateRows([{ ...row, amount: 2400 }]);
},
};