Resize, move and pin columns
On a wide table, every user wants a different set of columns. They can drag a header edge to resize, drag a header to reorder, and you can pin the name column to the left. The same operations are available from code, so saving "the layout they left" and restoring it later is a few lines.
In the demo below, drag a header edge to resize and drag a header to reorder. The checkboxes hide columns or pin the name column, and Save state and Restore show the save and restore round trip.
What users can do
| Goal | Mouse and touch | Keyboard (on the focused cell) |
|---|---|---|
| Resize | Drag the right edge of a header. The change is committed on release | Alt + Shift + ← →, 10 px per press |
| Reorder | Drag a header to the insertion line where you want it | Alt + ← →, one column per press |
| Hide or pin | There is no built-in button. Build one with the API below | none |
- Press
Escduring a resize to restore the original width. - Hold
Ctrlwith the keyboard resize shortcut for 50 px steps. - On touch, reordering starts after a long press of about 0.4 s. A short tap sorts.
- A drag of more than 5 px is not treated as a sort click, so reordering never changes the sort by accident.
- Screen readers announce changes such as "Moved Name to position 3". Change the wording with
messages.
Turn user operations off with options. For one column, set resizable: false or movable: false on its definition.
const options: GridOptions<Member> = {
columns,
rows,
columnsResizable: true, // false: users cannot resize
columnsMovable: true, // false: users cannot reorder
};Change columns from code
Every operation is also a GridApi method. Invalid input throws invalid-option before any state changes.
| Method | Effect |
|---|---|
moveColumn(id, toIndex) | Moves a column. toIndex is the index after the move, and hidden columns count |
resizeColumn(id, width) | Sets the width in px, clamped to the column's minWidth and maxWidth |
setColumnVisible(id, visible) | Shows or hides a column. The last visible column cannot be hidden |
pinColumn(id, side) | Pins to 'start' (left) or 'end' (right). null unpins |
getColumnOrder() | The current column ids in order, hidden columns included |
getColumnState() | Order, width, hidden and pinned as an array you can store (a renamed header title is title, 1.5.0) |
setColumnState(state) | Restores a stored array. Unknown ids are ignored |
api.resizeColumn('name', 200);
api.pinColumn('name', 'start');
api.setColumnVisible('bonus', false);
api.moveColumn('salary', 1);To add, remove or patch a single column, see Add, remove and patch columns.
Pin columns
A pinned column stays at the edge while the rest scrolls horizontally. To start pinned, set pinned on the definition.
const columns: ColumnDef<Member>[] = [
{ id: 'name', title: 'Name', width: 150, pinned: 'start' },
{ id: 'salary', title: 'Salary', width: 130, kind: 'number', pinned: 'end' },
// ...
];- Pinned columns always sit at the edges, in the order left-pinned, regular, right-pinned.
- Dragging moves a column only inside its own zone (left-pinned, regular or right-pinned). Use
pinColumnto change zones. - You can combine them with
pinnedRows, which keeps the top rows in place. The top-left corner stays put while you scroll in both directions, and merged cells and header groups work alongside (example). - The row-number column and the selection checkbox column are pinned along with left-pinned columns.
Width limits
minWidth and maxWidth set the resize range. Widths set by user resizing also have an absolute floor of 24 px, so a touch handle can never swallow a column. A width in the column definition is applied as written and does not go through that floor.
Group columns under header groups
You can add another header row above the columns. Keep the column definitions as they are and list column ids in headerGroups.
const options: GridOptions<Member> = {
columns,
rows,
headerGroups: [
{ id: 'person', title: 'Person', children: ['name', 'team', 'level'] },
{ id: 'pay', title: 'Pay', children: ['salary', 'bonus'] },
],
};children can contain nested groups instead of column ids to stack more levels. A column that belongs to no group (ID and City in the demo) stretches down through the group rows.
- A group header does not sort and cannot be dragged. Only leaf column headers sort and drag.
- If hiding or moving separates the columns of one group, the group splits into two cells with the same title.
- A group whose columns are all hidden is not drawn.
- Ids that match no column are ignored. Using the same column id twice, or repeating a group id, throws
invalid-option.
Column menu
Set columnMenu: true to add a ⋮ button at the right of every column header. It opens a menu with the actions available for that column. Right-clicking a header opens it too.
const options: GridOptions<Member> = { columns, rows, columnMenu: true };| Item | What it does |
|---|---|
| Sort ascending, descending, clear | Sorts by this column alone. Hidden for columns with sortable: false |
| Autofit width | Fits the longest text among the title and the visible rows (up to 500). Respects minWidth and maxWidth |
| Pin left, pin right, unpin | Same as pinColumn |
| Hide column | Disabled for the last visible column |
| Column list | Every column with a check mark. Use it to show a hidden column again |
| Reset column settings | Returns width, order, hidden, pinned and group collapse to the initial definition |
From the keyboard, press Alt+ArrowDown (or ContextMenu, Shift+F10) on the focused cell's column. Use Up, Down, Home and End to move, Enter or Space to run, Escape to close. It does not clash with column move (Alt+Left/Right) or width (Alt+Shift+Left/Right). It does not open while a cell is being edited.
Actions from the menu have source: 'menu' in the column events. Items carry aria-disabled and aria-checked, and the result is announced to screen readers. Labels follow locale (Korean or English) and can be changed with messages.
Collapse groups and move them as one block
Give a group collapsible: true to add a toggle next to its title. Collapsing keeps only the first visible column of the group. From code, use setHeaderGroupCollapsed.
headerGroups: [
{ id: 'pay', title: 'Pay', collapsible: true, children: ['salary', 'bonus', 'tax'] },
];
api.setHeaderGroupCollapsed('pay', true); // only salary staysDragging the group title moves its columns together. From code, use moveColumnGroup(groupId, toIndex), where toIndex is the position of the group's first column after the move.
- Collapsing is separate from hiding (
hidden). It is not part ofgetColumnState()and does not firecolumnVisibilityChanged. - A group whose columns span different pin zones, or that has a
movable: falsecolumn, cannot be dragged, andmoveColumnGroupthrowsinvalid-option. - Hidden columns do not count as the first column. If you hide the first column of a collapsed group, the next one stays.
- Keyboard (1.6.0): press Up on a cell in the first row to go up to the header, and once more to reach a collapsible group cell. On a group cell, Enter or Space collapses or expands it (
aria-expandedfollows), Left and Right move to the neighbor group on the same level, Down goes to the first column header of the group, and Esc releases the focus. Without a collapsible group, Up works as before.
A collapsed group keeps only its first visible column. If you hide that column, the next visible one takes its place; showing it again brings the original first column back. Expanding restores every column that is not hidden.
Choose which columns stay when a group collapses
Since 1.6.0
collapsedKeep, collapseHeaderGroup, expandHeaderGroup, isHeaderGroupCollapsed and the beforeHeaderGroupToggle hook are available since 1.6.0.
By default a collapsed group keeps only its first visible column, but the columns you list in collapsedKeep stay instead. Ids that are not in the group and columns the user hid are ignored, and if no column would stay, the first column stays.
headerGroups: [
{
id: 'contact',
title: 'Contact',
collapsible: true,
collapsedKeep: ['email'], // only Email stays when collapsed
children: ['email', 'phone', 'city'],
},
];
api.collapseHeaderGroup('contact');
api.isHeaderGroupCollapsed('contact'); // true
api.expandHeaderGroup('contact');collapseHeaderGroup(id) and expandHeaderGroup(id) are the same as setHeaderGroupCollapsed(id, true/false), and an unknown id or a group that is not collapsible fails with invalid-option. isHeaderGroupCollapsed(id) returns false for such a group. Save the folding with getHeaderGroupState() and setHeaderGroupState() (getColumnState() is an array and does not carry it). Every change fires the headerGroupToggled event ({ groupId, collapsed, source }).
If hooks.beforeHeaderGroupToggle({ groupId, collapsed, source }) returns false, the group does not collapse or expand (collapsed is the state it is about to take). Example: Choose which column stays when a group collapses
Read header groups and save their state
You can read how the groups look right now without re-reading your definitions. All of these are read-only and need no layout pass.
| Method | Returns |
|---|---|
getHeaderGroups() | Every group: id, title, collapsed, collapsible, parentId, columnIds (leaf columns in current order) |
getDisplayedHeaderGroups('start' | 'center' | 'end' | 'all') | Groups with at least one visible column on that side (after collapsing) |
getHeaderGroupState() | { id: { collapsed } } for collapsible groups |
setHeaderGroupState(state) | Collapse or expand only the listed groups, in one step |
resetHeaderGroupState() | Expand every group (widths, order, hidden and pinned stay) |
const saved = api.getHeaderGroupState(); // { pay: { collapsed: true } }
api.setHeaderGroupState({ pay: { collapsed: false } });
api.getDisplayedHeaderGroups('center').map((g) => g.title);setHeaderGroupStatechanges nothing and throwsinvalid-optionwhen any id is unknown, any group is not collapsible, or any value is not a boolean.headerGroupToggledfires once per changed group. Nothing fires when the state is the same.getHeaderGroupState()lists only collapsible groups, so you can pass it straight back tosetHeaderGroupState.
Reset to the initial state
resetColumnState() returns width, order, hidden, pinned and group collapse to the column definitions. Each changed property fires its usual column event (source: 'api'), then columnStateReset fires once.
api.resetColumnState();Save and restore the layout
getColumnState() returns only the column layout, without sort or filter. To keep it per user, store the array in localStorage or on a server. If a header title was changed (1.5.0, titleEditable or updateColumn), the entry of a column whose title differs from the initial one also carries title, and setColumnState() applies it too.
// save on every change
const save = () => localStorage.setItem('member-columns', JSON.stringify(api.getColumnState()));
api.on('columnMoved', save);
api.on('columnResized', save);
api.on('columnVisibilityChanged', save);
api.on('columnPinned', save);
// restore on load
const saved = localStorage.getItem('member-columns');
if (saved) api.setColumnState(JSON.parse(saved));Columns missing from the stored array keep their current state, and ids that exist only in the stored array are ignored. Restoring an old layout after the columns changed does not throw.
Save and restore the whole view state
Besides the column state, sort, filter, grouping, page and selection fit in one JSON object. v is always 1.
const saved = JSON.stringify(api.getViewState());
localStorage.setItem('grid-view', saved);
// next time
api.setViewState(JSON.parse(localStorage.getItem('grid-view') ?? '{"v":1}'));
// or once at creation: createGrid(el, { columns, rows, initialState: JSON.parse(saved) })| Part | Content | Feature bundle |
|---|---|---|
columns | Order, width, hidden and pinned like getColumnState() | columns |
sort | The sort model | none |
filter | The filter model or null | none |
groupBy | Group column ids | hierarchy |
page | { index, size } (pages start at 1) | pagination |
selection | Selected row keys (when selection is on) | none |
getViewState()holds only the parts you can use. Scroll position and tree expansion are not included (usegetScrolland the expansion API).setViewState(state)checks the shape of every part first. A wrong part throwsinvalid-optionnaming that part and nothing changes. Whether columns and rows exist is checked while applying; if a later part fails, the parts already applied are rolled back. A part of a missing feature bundle throws the error that names the bundle.- The order is columns, sort, filter, groupBy, page, selection. Parts you leave out stay as they are.
initialStateapplies once at creation. Selection and page need the rows to exist then. NostateChangedfires for it.stateChanged { part }fires after the matching change event (sortChanged,filterChangedand so on).setViewStatefires one per changed part after everything is applied. Use it to decide when to save.
api.on('stateChanged', () => localStorage.setItem('grid-view', JSON.stringify(api.getViewState())));Measure and fit column widths
Methods and column or option settings let you measure widths or fit them in one go. With none of them set, behavior is unchanged.
api.measureColumn('title'); // content width in px; 0 for an unknown id
api.measureColumns(); // every visible column as { id: width }
api.autoSizeColumns(); // fit all to content (or only the listed columns)
api.fitColumnsToWidth(); // share the spare width oncemeasureColumn(s)measures the widest of the header title and the displayed text of the visible rows, clamped to the column'sminWidthandmaxWidth. Without a layout (width 0) it returns the current width.autoSizeColumnsapplies the measured width (or the column'sfitWidth) in one go (columnResizedper changed column, then onecolumnsChanged), and the columns it touches keep their width undercolumnFit: 'fill'. Columns withautoSize: falseare skipped.fitColumnsToWidthshares the spare width among columns that are not pinned orfixed: true(weight isflex, otherwise the current width ratio). A share a column cannot take because of itsmaxWidthgoes to the others. With no spare width nothing happens.- Column settings:
fitWidth(30-2000px or'content', default'content') is the width used by the header-edge double-click and the menu's auto fit;autoSize: falsemakes the double-click, the menu andautoSizeColumnsskip the column;flex(0.1-100) is the weightcolumnFit: 'fill'uses instead of the width ratio. If any column that takes spare width hasflex, columns without it count as weight 1. - Option
autoSize: { padding, header, sampleRows }:padding(0-40px) is added on both sides (default is the theme padding),header: falseignores the header title and icon room,sampleRows(20-5000, default 500) caps the rows measured; with more rows they are sampled evenly from top to bottom.
Gallery example: column-auto-size-api
Buttons and checkboxes in the header
Putting a button or a checkbox in a column header, editing the title in place and merging header cells are covered in Header renderers and renaming.
Wrapping columns and headers
A column with wrap: true wraps cell text, and one with wrapHeader: true wraps its header title. Rows grow only with rowHeight: 'auto' and the header only with headerHeight: 'auto'.
| Option or method | Description |
|---|---|
headerLayerHeights | Height in px per header layer, as an array. The length must equal the number of layers (group nesting depth + 1). |
summary.rowHeight | Height of summary lines in px. Default is rowHeight. |
autoGridHeight | true or { maxRows }. Sets the grid height to header + rows and scrolls from maxRows rows (default 50). Not allowed with the server row model or autoPageSize. |
api.remeasureRows(keys?) | Drops the row heights measured by rowHeight: 'auto' and measures again. All rows when keys are omitted. |
With rowHeight: 'auto' horizontal column virtualization is turned off and the wrapping of every column counts toward the row height (scrolling sideways never changes a height). For the full details see Row height.
Resize rows by dragging
With rowsResizable on, drag the bottom edge of a row-number cell to change that row's height. The row number column (showRowNumbers) is required.
| Item | Description |
|---|---|
rowsResizable | true or { min, max } (px, default 20 to 600). Not allowed with the server row model or autoPageSize. |
| Drag | The bottom 6px of a row-number cell is the handle (the cursor changes). A guide line follows the pointer and the height is committed on release. Esc cancels. |
| Double click | Clears that row's user height. |
| Keyboard | On the focused row, Alt+Up or Alt+Down changes the height by 8px and announces it to screen readers. |
setRowHeight(key, px | null) | Sets the height (clamped to min and max). null clears it. |
resetRowHeights() | Clears all user heights. |
getRowHeights() | User heights by key (String(key)). |
rowResizeStarted, rowResizeEnded | Fired by dragging and the keyboard only (API calls fire nothing). rowResizeEnded carries { key, height, previous }; after an Esc cancel height equals previous. |
- A user height wins over a numeric or function
rowHeightand over heights measured by'auto'. - It follows the row through sorting and filtering, and is dropped when the row is removed or
setRowsreplaces the data. - Pinned rows and full-width rows cannot be resized.
- In a scaled container, set the
scaleoption so the drag distance is right.
Draw one row on several lines (band body)
bodyLayout splits each data row into 2 to 4 lines (bands). It gathers the information of a row without horizontal scrolling when there are many columns or a long memo.
createGrid(el, {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'team', title: 'Team', width: 110 },
{ id: 'amount', title: 'Amount', kind: 'number', width: 110 },
{ id: 'memo', title: 'Memo', bandSpan: 3 },
],
bodyLayout: { bands: [['name', 'team', 'amount'], ['memo']], heights: [30, 26] },
rows,
rowKey: 'id',
});| Item | Description |
|---|---|
bodyLayout.bands | An array of column ids per line (2 to 4 lines). Every visible column appears exactly once. |
bodyLayout.heights | Height in px per line. Default is rowHeight per line. The row height is the sum and rowHeight is not used (only group and summary lines keep the default height). |
ColumnDef.bandSpan | Slots the cell spans in its line (integer >= 1, default 1). |
- Slots: The slot count is the sum of
bandSpanof the first line, and every line must add up to the same number. Slot widths come from the widths of the first-line columns (withbandSpann, n slots share that width equally). Thewidthof columns on later lines is ignored. Resize by dragging a first-line header. - Header: One layer per line, placed on the same slots. Sorting, filter buttons, menus and header renderers work on each header cell as usual.
- Keyboard: Left and Right move along a line; Up and Down move to the cell covering the same slot in the previous or next line. Up from the first line goes to the last line of the previous row, Down from the last line to the first line of the next row. Tab follows the line order.
- Selection and editing: A single cell and row selection work, and the editor opens over the cell's own line and slots. Full-width rows and group lines are drawn on one line (a group line shows only first-line columns).
- Not allowed together (
invalid-option): pinned columns (pinned), cell merge (merge,mergeCols),rowHeight: 'auto',autoPageSize,cellSelection: 'multiple',cellDrag,cellFill, pinned rows (pinnedRows), row resizing (rowsResizable) and the filter row (filterRow). AlsobandSpanwithoutbodyLayout, unknown, duplicate or missing column ids, and lines whosebandSpansums differ. - Horizontal column virtualization is turned off automatically and dragging columns (
columnsMovable) is off too (the order comes frombands).rowHeightis ignored even when it is a number (line heights come fromheights) and no error is raised. - Tree, summary lines and
autoGridHeightcan be used together (a summary line is one line, andautoGridHeightadds the header layers and the line heights). Hiding a column at runtime makes its slot width 0 and the other slots are not re-flowed.
On touch screens
Fixed in 1.7.2
Up to 1.7.1, on touch devices dragging a column edge, moving a column, dragging a row and dragging a cell could be cancelled right after they started (the mouse was fine). In 1.7.2 all of them can be dragged to the end by touch.
- Width: drag the handle on the right edge of the header (24 px on touch screens).
- Column order: press the header for about 0.4 seconds, then drag. A short press sorts.
- Row drag: press the drag handle for about 0.4 seconds, then drag.
- Column menu and filter buttons: on touch screens they are finger sized (32 px) and sit inside the width handle, so the handle no longer covers the menu button. The filter input uses 16 px text so iOS does not zoom the page.
Options
| Option | Default | Meaning |
|---|---|---|
columnsResizable | true | Whether users can resize. Both this and the column's resizable must be true |
columnsMovable | true | Whether users can reorder. Both this and the column's movable must be true |
columnFit | 'fill' | When column widths add up to less than the grid, columns share the leftover width in proportion to width. 'none' leaves it empty. Pinned, fixed: true and user-resized columns keep their width |
columnMenu | false | Adds the ⋮ menu button and menu to column headers |
headerGroups | none | Multi-level header groups |
columnToolbar | false | A strip of column chips above or below the grid (1.6.0). Column toolbar |
responsiveColumns | false | Hides columns that have hideBelow on narrow widths (1.6.0). Hide columns when narrow |
On a column definition, width, minWidth, maxWidth, hidden, pinned, resizable and movable apply. width, hidden and pinned are initial values. Once a user or the API changes one, the changed value wins.
Events
Column events have a source of 'pointer', 'keyboard', 'menu' or 'api'. Use it to leave 'api' changes out of your saving logic.
| Event | Payload |
|---|---|
columnResized | columnId, width, previousWidth, source. Once when a drag ends, once per resizeColumn call, and once per changed column for autoSizeColumns (source: 'api') |
columnMoved | columnId, fromIndex, toIndex, order (the new order), source |
columnVisibilityChanged | columnId, hidden, source |
columnPinned | columnId, pinned, previousPinned, source |
headerGroupToggled | groupId, collapsed, source |
columnsResponsiveChanged | hidden (array of column ids hidden by width). 1.6.0 |
columnStateReset | source. Fires once when resetColumnState() finishes (the same idea as columnsReset in other grids) |
Common pitfalls
I passed new column definitions to setOptions and the width did not change. A width the user already changed wins over the definition. The width in a definition is only the initial value. Call resizeColumn to change it.
columnsMovable: false is set but moveColumn still works. The option blocks only user input. API calls stay available so that restoring a saved layout keeps working. A per-column movable: false rejects moveColumn too.
I try to move a pinned column into the regular zone and nothing happens. moveColumn stays inside the column's zone. Call pinColumn(id, null) first.
Hiding the last column throws. At least one column has to stay visible.
I cannot drag columns while editing. User gestures are blocked during cell editing and Korean text composition. API calls still work during editing.
In the modular bundle, moveColumn() throws "a "columns" feature is required". Column operations live in the columns bundle. Add features: [columns] (Pick features).
I cannot see the column menu button. Set columnMenu: true. In the modular bundle you also need features: [columns].
A collapsed group is missing from the saved layout. Collapsing is separate from hiding, so getColumnState() does not include it. Store headerGroupToggled yourself if you need it.
I leave out 'api' changes but menu actions are saved too. Menu actions have source: 'menu'. They are user actions, so saving them is correct.