컬럼 너비 자동 맞춤
autoSizeColumns는 첫 행이 그려지면 컬럼을 헤더와 내용에 맞추고, 'always'면 새 데이터가 올 때마다 다시 맞추며, 사용자가 너비를 바꾼 컬럼은 그대로 둡니다.
실행 예제컬럼 너비 자동 맞춤
짧은·긴 데이터 넣기, 한 컬럼 너비 직접 바꾸기.
이 데모의 코드
import { createGrid } from '@freegridjs/core';
import { button, separator, text, tr, type DemoContext } from '../ui';
export default function mount(ctx: DemoContext) {
const h = (en: string, ko: string) => tr(ctx.lang, { en, ko });
const short = Array.from({ length: 50 }, (_, i) => ({ id: i + 1, code: `A${i}`, name: 'Kim', city: 'Seoul', note: '' }));
const long = Array.from({ length: 50 }, (_, i) => ({
id: i + 1, code: `ORDER-2026-${String(100000 + i)}`, name: h('Alexandra Montgomery-Smith', '김수한무거북이와두루미'),
city: h('San Francisco, California', '경기도 성남시 분당구'), note: h('Leave it at the front desk', '경비실에 맡겨 주세요'),
}));
const grid = createGrid(ctx.host, {
columns: [
{ field: 'id', header: 'ID', type: 'number', width: 60, autoSize: false },
{ field: 'code', header: h('Code', '코드'), width: 60 },
{ field: 'name', header: h('Name', '이름'), width: 60 },
{ field: 'city', header: h('City', '도시'), width: 60 },
{ field: 'note', header: h('Note (flex)', '메모(flex)'), flex: 1 },
],
data: short, locale: ctx.lang, autoSizeColumns: 'always',
});
grid.on('columnResize', e => ctx.log(`columnResize ${e.colId} → ${e.width}px`));
button(ctx, h('Short data', '짧은 데이터'), () => grid.setData(short));
button(ctx, h('Long data', '긴 데이터'), () => grid.setData(long));
separator(ctx);
button(ctx, h('Fit all now', '지금 모두 맞추기'), () => grid.autoSizeColumns());
text(ctx, h('Switch the data: Code, Name and City follow. Resize one of them by hand and switch again: that one keeps your width. ID has autoSize: false; Note is flex.',
'데이터를 바꿔 보세요. 코드·이름·도시가 따라갑니다. 그중 하나를 직접 넓힌 뒤 다시 바꾸면 그 컬럼은 정한 너비를 유지합니다. ID는 autoSize: false, 메모는 flex입니다.'));
return grid;
}직접 정한 너비는 데이터가 바뀌면 곧 맞지 않게 됩니다. autoSizeColumns를 켜면 그리드가 컬럼마다 헤더와 화면의 행을 재어 너비를 정합니다. 헤더 경계를 더블클릭하거나 autoSizeColumns()를 부르는 것과 같습니다.
createGrid(el, {
columns: [
{ field: 'name' },
{ field: 'email' },
{ field: 'note', flex: 1 }, // takes the room left; not measured
{ field: 'id', width: 60, autoSize: false }, // keeps its width
],
data,
autoSizeColumns: 'always', // true: once, after the first rows are drawn
});
// or by hand, any time
grid.autoSizeColumns(); // every column
grid.autoSizeColumns(['email']); // some| 값 | 맞추는 때 |
|---|---|
| true | 첫 행이 화면에 나올 때 한 번(datasource가 답한 뒤도) |
| 'always' | 그 뒤 setData와 트랜잭션 때마다, 한 프레임에 한 번 |
건드리지 않는 컬럼
flex컬럼: 남는 공간을 나눠 가집니다.autoSize: false컬럼, 너비를 바꿀 수 없는 컬럼(resizable: false).- 사용자가 너비를 바꾼 컬럼: 'always'도 그 선택을 되돌리지 않습니다.
resetColumnState()뒤 새로고침하면 다시 자동이 됩니다. - stateKey로 되살린 너비: 저장된 레이아웃이 우선입니다.
- 선택, 드래그 손잡이, 행 번호 컬럼.
화면에 보이는 행만 재므로, 아래쪽의 아주 긴 값은 잘릴 수 있습니다. 스크롤한 뒤 autoSizeColumns()를 부르거나, 긴 글 하나가 전체 폭을 차지하지 않게 maxWidth를 주세요. 맞출 때마다 columnResize가 발생합니다.
이 페이지에 대한 질문
그리드를 불러올 때 컬럼이 내용에 맞게 하려면?
autoSizeColumns: true를 주세요. 첫 행이 그려지면 flex를 뺀 모든 컬럼이 헤더와 화면의 행에 맞는 너비가 됩니다. 데이터가 바뀔 때마다 다시 맞추려면 'always'를 쓰세요.