여러 열 셀·줄바꿈·행 높이
colSpan으로 셀이 여러 열을 차지하게 하고, wrapText와 autoRowHeight로 긴 글을 줄바꿈하며, getRowHeight와 autoHeight로 행 높이와 그리드 높이를 정합니다.
실행 예제여러 열 셀·줄바꿈·행 높이
여러 열을 차지하는 안내 행, 줄바꿈과 자동 행 높이, 행마다 다른 높이, 헤더 버튼.
이 데모의 코드
import { createGrid, type ColumnDef, type GridApi, type Row } from '@freegridjs/core';
import { separator, text, toggle, tr, type DemoContext } from '../ui';
export default function mount(ctx: DemoContext) {
const { lang } = ctx;
const h = (en: string, ko: string) => tr(lang, { en, ko });
const regions = [
{ region: h('Seoul', '서울'), items: [[h('Monitor', '모니터'), h('Pending payment for the March order; follow up with the buyer before the end of the week.', '3월 주문 입금 대기 중입니다. 이번 주가 끝나기 전에 구매 담당자에게 다시 연락해야 합니다.')], [h('Keyboard', '키보드'), h('Shipped.', '출고 완료.')], [h('Desk', '책상'), h('Assembly service booked for Friday afternoon, customer asked for a call 30 minutes before arrival.', '금요일 오후 조립 서비스 예약. 도착 30분 전에 전화해 달라는 요청이 있었습니다.')]] },
{ region: h('Busan', '부산'), items: [[h('Chair', '의자'), h('Back-ordered: the supplier expects new stock in two weeks.', '재고 없음: 공급처 입고까지 2주 예상.')], [h('Lamp', '조명'), h('Delivered.', '배송 완료.')]] },
{ region: h('Tokyo', '도쿄'), items: [[h('Monitor arm', '모니터 암'), h('Customs paperwork done.', '통관 서류 처리 완료.')], [h('Cable kit', '케이블 세트'), h('Gift wrap requested.', '선물 포장 요청.')]] },
];
const data: Row[] = [];
for (const r of regions) {
r.items.forEach(([item, memo], i) => data.push({
region: r.region, item, memo,
qty: 1 + ((data.length * 7) % 9), price: 30 + ((data.length * 37) % 400),
}));
data.push({ kind: 'note', item: h(`${r.region}: shipping cut-off is 3 pm`, `${r.region}: 오후 3시 이후 주문은 다음 날 출고`) });
}
const columns: ColumnDef[] = [
{ field: 'region', header: h('Region', '지역'), width: 110 },
// note rows span the item, memo and qty columns
{ field: 'item', header: h('Item', '품목'), width: 150, colSpan: ({ row }) => (row.kind === 'note' ? 3 : 1),
cellClass: ({ row }) => (row.kind === 'note' ? 'demo-note' : undefined) },
// long memos wrap; autoRowHeight grows the row
{ field: 'memo', header: h('Memo', '메모'), width: 280, wrapText: true },
{ field: 'qty', header: h('Qty', '수량'), type: 'number', width: 90 },
{
field: 'price', header: h('Price', '단가'), type: 'number', format: '#,##0', width: 120, headerClass: 'demo-money',
// a help button in the header; pressing it does not sort
headerRenderer: ({ header }) => {
const span = document.createElement('span');
const b = document.createElement('button');
b.type = 'button';
b.textContent = '?';
b.className = 'demo-help';
b.addEventListener('click', () => ctx.log(h('Prices are in USD, before tax.', '단가는 달러, 세전 금액입니다.')));
span.append(`${header} `, b);
return span;
},
},
];
let grid: GridApi;
const create = (auto: boolean) => {
grid?.destroy();
grid = createGrid(ctx.host, {
columns, data, locale: lang,
autoRowHeight: auto, // rows grow to fit the wrapped memos
// note rows are a little lower than the others
getRowHeight: row => (row.kind === 'note' ? 30 : undefined),
});
};
create(true);
text(ctx, h('Note rows span three columns, long memos wrap and the row grows. Press ? in the Price header.',
'안내 행은 세 칸을 차지하고, 긴 메모는 줄바꿈되며 행 높이가 늘어납니다. 단가 헤더의 ? 버튼도 눌러 보세요.'));
separator(ctx);
toggle(ctx, h('Rows grow to fit (autoRowHeight)', '내용에 맞춰 행 높이 (autoRowHeight)'), true, on => { create(on); ctx.log(`autoRowHeight: ${on}`); });
return grid!;
}colSpan은 셀마다 몇 개의 열을 차지할지 함수로 정합니다. 안내 행 하나를 여러 컬럼에 걸쳐 쓰거나, 옆의 빈 칸까지 이어지는 제목을 만들 때 씁니다. 이렇게 넓어진 셀은 포커스와 복사에서도 한 칸으로 다뤄집니다. 컬럼에 wrapText: true를 주면 긴 글이 여러 줄로 감기고, autoRowHeight: true를 켜면 행 높이가 내용에 맞춰 늘어납니다. 이때 rowHeight는 최소 높이가 됩니다.
getRowHeight로 안내 행을 조금 낮게 하는 것처럼 행마다 높이를 따로 줄 수 있습니다. wrapHeaderText(컬럼에 주거나, 그리드 옵션으로 모든 컬럼에)는 긴 헤더를 자르지 않고 줄바꿈하고, headerRenderer로 헤더에 아이콘이나 도움말 버튼을 넣을 수 있습니다. 그 버튼을 눌러도 정렬되지 않습니다. autoHeight: true를 켜면 그리드 안에 스크롤이 생기지 않고 행 수만큼 늘어나므로, 수백 행 이하의 짧은 목록에 알맞습니다. 너비는 그대로 컨테이너를 따르고 넓은 컬럼은 가로로 스크롤되며, 행이 없으면 "데이터 없음" 안내가 보이도록 세 행 높이를 남깁니다.
createGrid(el, {
columns: [
// one cell spans the row's first three columns when it is a note row
{ field: 'title', colSpan: ({ row }) => (row.kind === 'note' ? 3 : 1) },
// long text wraps; the row grows to fit
{ field: 'memo', width: 220, wrapText: true },
// a long header wraps instead of being cut off
{ field: 'q1', header: 'First quarter revenue', wrapHeaderText: true },
// icons or buttons in the header; sorting still works
{ field: 'amount', type: 'number', headerClass: 'money',
headerRenderer: ({ header }) => `${header} <button type="button" data-fg-no-sort>?</button>` },
],
data,
autoRowHeight: true, // rowHeight becomes the minimum
getRowHeight: row => (row.kind === 'note' ? 28 : undefined),
// autoHeight: true, // no inner scroll: the grid grows with its rows
});여러 행에 걸쳐 셀을 합치려면 셀 병합을 보세요. 오른쪽에서 왼쪽으로 배치하는 방법은 다국어와 오른쪽→왼쪽 배치, 휴대폰용 카드는 휴대폰 카드 보기에 있습니다.