Dynamic Columns
Grid columns can be dynamically generated based on user selection or other runtime conditions.
<div controller={PageController}>
<div class="mb-4 flex items-center gap-2">
<span>Visible Columns:</span>
<LookupField
values={m.visibleColumns}
options={columnOptions}
multiple
style="width: 300px"
/>
</div>
<Grid
records={m.records}
style="width: 100%"
border
columnParams={m.visibleColumns}
onGetColumns={(visibleColumns: string[]) =>
allColumns.filter((c) => visibleColumns.includes(c.field))
}
/>
</div> | Name | Continent | Browser | Visits |
|---|---|---|---|
| Alice Johnson | Europe | Chrome | 45 |
| Bob Smith | Asia | Firefox | 23 |
| Carol White | North America | Safari | 67 |
| David Brown | Europe | Chrome | 12 |
| Eva Green | Asia | Edge | 89 |
Use the dropdown to select which columns are visible.
Why Use Dynamic Columns?
The columns property is not bindable, so you cannot simply bind it to store data. Using columnParams and onGetColumns allows:
- Dynamic column visibility based on user preferences
- Preserving grid state (scroll position, column widths) when columns change
- Generating columns from runtime data
Using columnParams and onGetColumns
Pass your column configuration data to columnParams and generate columns in onGetColumns:
<Grid
records={m.records}
columnParams={m.visibleColumns}
onGetColumns={(visibleColumns: string[]) =>
allColumns.filter((c) => visibleColumns.includes(c.field))
}
/>
When columnParams changes, onGetColumns is called to regenerate the column list. The grid preserves its internal state during this update.
Column Definition
Define all possible columns in an array:
const allColumns = [
{ header: "Name", field: "fullName", sortable: true },
{ header: "Continent", field: "continent", sortable: true },
{ header: "Browser", field: "browser", sortable: true },
{ header: "Visits", field: "visits", sortable: true, align: "right" },
];
The onGetColumns callback filters or transforms this array based on columnParams.
Configuration
| Property | Type | Description |
|---|---|---|
columnParams | any | Data passed to onGetColumns. Changes trigger column regeneration. |
onGetColumns | function | Callback that receives columnParams and returns the columns array. |
Alternative: ContentResolver
For more complex scenarios, you can use ContentResolver to regenerate the entire grid. However, this approach loses grid state (scroll position, resized column widths) on each change.
See also: Column Reordering, Grid