#Loading data
The data prop accepts an array, a Promise, or a fetch function.
You either pass the data directly in the <adaptable-provider>
<adaptable-provider
[data]="data"
adaptableId="app"
primaryKey="id"
[defaultState]="state"
>
<adaptable-workspace /> <!-- or <adaptable-ui /> -->
</adaptable-provider>or use the dedicated <adaptable-data-source> for that.
<adaptable-data-source [data]="data">
<adaptable-provider
adaptableId="app"
primaryKey="id"
[defaultState]="state"
>
<adaptable-workspace /> <!-- or <adaptable-ui /> -->
</adaptable-provider>
</adaptable-data-source>#Using local data
Without additional configuration, Adaptable will use data in client mode. This means data is loaded at startup and then kept in the browser memory and all operations happen in the browser. This includes sorting, filtering, grouping, aggregations and pivoting.
Local data can be used in multiple ways, as detailed below.
#Using a data array or a Promise
The simplest form of data you can feed into the Adaptable DataGrid is an array.
When passing an array, Adaptable is not concerned how you retrieve that data. Once you have it and pass it to the component, Adaptable will manage sorting, filtering, grouping, aggregations and pivoting. All data operations will be handled inside the component. You will still be able to listen to any of those events.
You can update this array with another one at any moment and Adaptable will take care to re-execute the needed data operations.
import { Component } from '@angular/core';
import {
AdaptableDataSource,
AdaptableProvider,
AdaptableWorkspace,
type AdaptableUserState,
} from '@adaptabletools/datagrid-angular';
type Developer = {
id: number;
name: string;
language: string;
repos: number;
};
const data: Developer[] = [
{ id: 1, name: 'John', language: 'JavaScript', repos: 100 },
{ id: 2, name: 'Jane', language: 'TypeScript', repos: 200 },
{ id: 3, name: 'John', language: 'Python', repos: 300 },
{ id: 4, name: 'Jane', language: 'Java', repos: 400 },
{ id: 5, name: 'John', language: 'JavaScript', repos: 500 },
{ id: 6, name: 'Jane', language: 'TypeScript', repos: 600 },
{ id: 7, name: 'John', language: 'Python', repos: 700 },
{ id: 8, name: 'Jane', language: 'Java', repos: 800 },
{ id: 9, name: 'John', language: 'JavaScript', repos: 900 },
];
const state: AdaptableUserState = {
globalEntities: {
availableColumns: {
name: {
field: 'name',
dataType: 'text',
},
language: {
field: 'language',
dataType: 'text',
},
repos: {
field: 'repos',
dataType: 'number',
},
},
},
view: {
currentViewId: 'default',
views: [
{
id: 'default',
label: 'Default',
},
],
},
};
@Component({
selector: 'demo-root',
imports: [AdaptableDataSource, AdaptableProvider, AdaptableWorkspace],
template: `
<adaptable-data-source [data]="data">
<adaptable-provider adaptableId="app" primaryKey="id" [defaultState]="state">
<adaptable-workspace />
</adaptable-provider>
</adaptable-data-source>
`,
})
export default class App {
protected readonly data = data;
protected readonly state = state;
}If you use a Promise, it will work very similarly, but we'll show a loading UI while the Promise is pending. At any time, you can pass in a new Promise and we'll reload the data.
This example uses a Promise that resolves in 2 seconds.
Click the toggle button - it will update the data to a new Promise (this one resolves in 1 second).
#Using a function
In addition to an array or Promise, you can also use a function to load data initially and then let Adaptable do the rest.
The function must return an array or a Promise that resolves to a data array or an object with a data property that's an array.
It receives a single params object describing what the grid needs — sortInfo, groupBy, pivotBy, filterValue, and in server mode the group being loaded (groupKeys) and the batch (batchStartIndex / batchSize) — plus the view (the object describing the current table or pivot view), and dataSourceMode. Use view when different views load from different endpoints, or to send view metadata to your server.
In this demo, we load the data once via a function, and then Adaptable handles all the data operations internally (sorting, filtering, grouping, aggregations, pivoting).
In order to trigger a data refetch, you can pass a new function reference.
#Using remote data
When you want the server to run the data operations, specify the mode prop as "server" - the data prop must then be a function.
In addition, you can configure the batchSize to control the size of the batches loaded into Adaptable as the user is scrolling (if no batchSize is configured, each call to the data function returns the whole dataset (or a whole level - when grouped): all the rows when the view isn't grouped, and when it's grouped, the top-level groups first, then all the children of a group when that group is expanded).
<adaptable-data-source mode="server" [batchSize]="200"
[data]="fetchRows"
>
<adaptable-provider
adaptableId="app"
primaryKey="id"
[defaultState]="state"
>
<adaptable-workspace /> <!-- or <adaptable-ui /> -->
</adaptable-provider>
</adaptable-data-source>Two modes are available in the data-source:
client(default) — the grid loads all rows and runs every operation in the browser. Great up to tens of thousands of rows.server— the server runs every operation; the grid calls your data function for the rows it has to show, one level at a time (and in batches ofbatchSizerows, when configured), as the user scrolls or expands groups.
- Sorting, filtering, grouping, aggregations and pivoting are done by the server. The rows your function returns are shown as they are.
- Any change to the sorting, filtering,
groupByorpivotBy, and every switch to another view, calls thedatafunction again. - When in a view that has grouping, the grid only loads the levels it shows. A level is what one call returns: the top level (
groupKeys: []), or the children of one group (groupKeysis the path of that group, eg['Europe', 'Italy']). Groups are initially rendered as collapsed.
#Loading with no batching
Without a batchSize, every call returns all the rows of a level. In this case,no batchStartIndex / batchSize properties are available to the params object the data function is called with:
- Flat view (not grouped, not pivoted) - one call returns every row, already sorted and filtered. When the user is scrolling, the data function is not being called.
- Grouped view - the first call returns all the top-level groups. Expanding a group makes one call with that group's
groupKeys, which returns all of its children (subgroups or leaf rows in that group). A group that is expanded in the view's row groups state loads its children as soon as it is shown. - Pivot view without row groups - one call returns a single row with the pivot values (the grand totals). There is nothing to expand.
- Pivot view with row groups - like a grouped view, but every row is a group row with pivot values. The groups of the deepest level have no leaf rows, so they can't be expanded.
The web frameworks dataset, loaded with mode="server" and no batchSize. Each call loads a whole level.
Grouped starts with one call for the three languages. Expand a language and the next call returns every framework in it. Flat is one call for all 25 rows. Scrolling does not call the function again.
#Batching with batchSize
With batchSize set to N, every level is also split into batches of N rows:
- The first call of a level sends
batchStartIndex: 0andbatchSize: N. ThetotalCountyou return sets how many rows the level has (which is used to compute the scroll height). - When the user stops scrolling, the batches in view that aren't loaded yet are requested, each with its
batchStartIndex. - In a grouped view, expanding a group loads its first
Nchildren, and the rest load as they are scrolled into view.batchStartIndexis counted within the level identified bygroupKeys. - A pivot view without row groups has a single row, so it is loaded in one call without
batchStartIndex/batchSize, even withbatchSizeset.
The developers (1k) dataset, loaded with mode="server" and [batchSize]="50". Each call loads 50 rows of one level.
Grouped starts with one call: there are 10 countries, so that level fits in the first batch. Expand a country and the next call returns its first 50 developers; scrolling the group loads the rest. Flat starts with the first 50 of 1,000 rows. Scrolling requests the next batches.
This demo has an artificial delay of 300ms for loading group rows, so it's easier to see group loading feedback.
#Shape of data function response
The shape of the response depends on the level:
// flat view, or the leaf rows of the deepest group
const leafResponse: AdaptableDataResult<Developer> = {
data: rows,
totalCount: 1250,
};
// group rows (a grouped or pivoted view)
const groupResponse: AdaptableDataResult = {
data: [
{
keys: ['Europe'], // the group path
data: { region: 'Europe' }, // the group values
aggregations: { salary: 82000 }, // keyed by column id
totalChildrenCount: 410, // leaf rows in the group
pivot: { totals: {}, values: {} }, // pivot views only
},
],
totalCount: 5, // groups in this level
};totalCount is the number of rows (or groups) of the level - with batching, of the whole level, not of the batch.
#The DataGrid Protocol — server-side out of the box
If your backend speaks TDGP (the open DataGrid Protocol), server mode is a two-liner — the client is built in:
import { createTdgpDataSource } from '@adaptabletools/datagrid-angular';
const tdgpData = createTdgpDataSource<Developer>({
url: 'https://data.thedatagrid.com',
dataset: 'developers-10k',
});
@Component({
selector: 'tdgp-grid',
imports: [AdaptableDataSource, AdaptableProvider, AdaptableWorkspace],
template: `
<adaptable-data-source mode="server" [batchSize]="200"
[data]="tdgpData"
>
<adaptable-provider
adaptableId="app"
primaryKey="id"
[defaultState]="state"
>
<adaptable-workspace /> <!-- or <adaptable-ui /> -->
</adaptable-provider>
</adaptable-data-source>
`,
})
export class TdgpGrid {
protected readonly tdgpData = tdgpData;
protected readonly state = state;
}Need auth headers, a custom fetch, or one client shared across grids? Pass
headers/fetch, or create the client once with createTdgpClient (also
exported from the package) and pass { client, dataset } instead of url.
That is exactly what the home page demo does — 10,000 rows, grouped and aggregated by the server, fetched 200 at a time.
#Data loading waits for state hydration
Loading persisted state is always asynchronous — from localStorage by default, or via your custom loadState (typically a remote call). When data is a function, the grid waits for that state to be applied before invoking it, with the correct DataGrid information on grouping, sorting, filtering, etc that comes from your state.
This guarantees exactly one initial fetch, built from the state the user actually configured — their current view, sorting, grouping — never a wasted request for a soon-to-be-replaced initial view. It also means params.view is always the view the user ends up seeing.
Arrays and Promises are not held back — they were produced by your code before the grid saw them, so there is no request to save by waiting. The grid renders them right away and re-applies the persisted view state once it arrives.
If you want data to start loading as early as possible, fetch the state yourself before mounting the grid and pass it synchronously via the controlled state (or defaultState) prop.
#Refetching
In client mode, the data function is called once. To call it again when something changes, use the refetchOn prop — true, or an array of sort / filter / groupBy / pivotBy / viewChange values. The function is called again whenever any of the listed operations change.
<adaptable-data-source [refetchOn]="['sort', 'filter']"
[data]="fetchRows"
>
<adaptable-provider
adaptableId="app"
primaryKey="id"
[defaultState]="state"
>
<adaptable-workspace /> <!-- or <adaptable-ui /> -->
</adaptable-provider>
</adaptable-data-source>refetchOn only calls the function again - it never changes who runs the operations. The grid still sorts, filters, groups and pivots the rows the function returns, in the browser.
false(the default) - the function is only called initially.['sort', 'filter', 'groupBy', 'pivotBy', 'viewChange']- any of these;filtercovers the column filters and the grid filter (including edits to the named queries it uses),viewChangemeans switching to another view.true- all of the above.
When the current view switches, the refetchOn of the view switched to applies. The function is called once, even when the switch changes several of the listed operations (eg the view and its sorting), and not at all when none of them change.
This is how a server can pre-filter the data while the grid does the rest: with refetchOn: ['filter'], the function gets filterValue and gridFilterExpression on every filter change and can return only the matching rows; the grid filters them again and sorts, groups and pivots them. The grid shows the rows that pass both the server's filtering and its own, so the two only agree when the server filters the way the grid does (eg the grid compares text ignoring case).
In server mode, refetchOn does not apply: every change to the sorting, filtering, grouping or pivoting, and every view switch, loads the data again.
With createTdgpDataSource in client mode, every call - including the ones refetchOn triggers - fetches the full dataset.
Using TanStack Query? Keep it: pass a function that calls
queryClient.fetchQuery(...) as data and you get caching and deduplication for
every batch the grid requests.
#Filtering with a data function
The data function gets both kinds of filters:
filterValue- the column filters, one item per filtered column:field,id(the column id) andfilter, withtype(the column's filter type:text,number,values, or a custom one),operator(an AQL operator name such asEQ,CONTAINSorIN) andvalue. Filters still waiting for a value are left out.gridFilterExpression- the grid filter of the view, as an AQL boolean expression that can run outside the grid: everyQUERY("name")is replaced by the expression of that named query, and every column reference[columnId]by the column's data field. It is absent when there is no grid filter, or when the grid filter is paused.
For example, with a points column that shows the score field, the grid filter [points] < 50 OR [name] = "Dan" reaches the function as [score] < 50 OR [name] = 'Dan'. With a HighScore named query of [points] > 100, the grid filter QUERY("HighScore") reaches it as [score] > 100.
#In client mode
The grid applies both filters to the rows the function returns, so gridFilterExpression only tells the function what the grid filters by. Changing a filter doesn't call the function again, unless refetchOn includes filter.
#In server mode
The server must apply both filters: the grid shows the rows it gets as they are, and never filters them itself. Every change to the column filters, to the grid filter, or to a named query the grid filter uses calls the function again.
To get the same rows as in client mode, the server has to filter the way the grid does: for example, the grid compares text ignoring case, and a date column filter matches the whole day, whatever the time of the value. createTdgpDataSource sends date column filters as day ranges.
A server that can't apply a filter can say so in processed. The load then fails (see When a data call fails), instead of showing rows that aren't filtered:
return {
data: rows,
totalCount,
processed: { columnFilters: true, gridFilter: false },
};processed is optional - without it, the filters that were sent count as applied. A filter that wasn't sent (no grid filter, or a paused one) doesn't need to be applied.
With createTdgpDataSource, the grid filter is compiled into the filter of the TDGP request, combined (AND) with the column filters. It can use AND, OR and NOT, and comparisons of a column with literal values that use the TDGP operators: comparisons, BETWEEN, IN (negated with NOT, eg NOT([country] IN ("USA", "Japan"))), CONTAINS, STARTS_WITH, ENDS_WITH, IS_BLANK and IS_NOT_BLANK. A grid filter with anything else - a function such as IS_TODAY or REGEX, or a comparison of two columns - fails the load before any request is sent.
#When a data call fails
A call of the data function fails when the function throws or rejects, or when it returns a payload with an error message:
return { data: [], error: 'The reports service is down' };In server mode, a call also fails when the function reports a filter it was sent as not applied (see processed above), and when the grid filter can't be prepared for the server - eg it uses a named query that doesn't exist, or a column without a data field. In that last case the function isn't called.
The grid then shows the error, with a Retry button:
- over the top of the rows it showed before the failed call - they stay on screen;
- over the body, when there are no rows to show - the first load failed, or a grouped server-mode view lost its rows when it reloaded;
- in the group row, when loading the children of an expanded group failed.
A later call that loads what failed clears its error: a batch scrolled into view again, a group expanded again, or a new load of the data (eg after a sort change). Retry clears every error and calls the function again for the rows the grid shows, including the children of the expanded groups. Closing the banner only hides the error. Every failed call is also logged to the console.
#Showing data errors yourself
To replace how the grid shows data errors, pass components.DataError to <adaptable-provider>: a component with the inputs error, variant (how it is shown: mask over the body, banner over the rows, or group in a group row), retry and dismiss. The grid positions the mask and the banner; the component renders what goes in them.
import {
type AdaptableDataErrorInfo,
type AdaptableDataErrorVariant,
type AdaptableProps,
} from '@adaptabletools/datagrid-angular';
// the props of AdaptableDataErrorComponentProps are its inputs
@Component({
selector: 'data-error',
host: { '[class]': "'data-error data-error--' + variant()" },
template: `
{{ error().message }}
<button (click)="retry()()">Retry</button>
@if (variant() === 'banner') {
<button (click)="dismiss()()">Close</button>
}
`,
})
class DataError {
readonly error = input.required<AdaptableDataErrorInfo>();
readonly variant = input.required<AdaptableDataErrorVariant>();
readonly retry = input.required<() => void>();
readonly dismiss = input.required<() => void>();
}
@Component({
selector: 'custom-data-error',
imports: [AdaptableProvider, AdaptableWorkspace],
template: `
<adaptable-provider [components]="components"
[data]="fetchRows"
adaptableId="app"
primaryKey="id"
[defaultState]="state"
>
<adaptable-workspace />
</adaptable-provider>
`,
})
export class CustomDataError {
protected readonly components: AdaptableProps<Developer>['components'] = { DataError };
protected readonly fetchRows = fetchRows;
protected readonly state = state;
}To show the error outside the grid too (eg in a status bar), call injectDataError() in a component inside <adaptable-provider>. It returns a signal of an object with the error of the top level (the rows, the top-level groups, or a batch of them), and the retry and dismiss functions. The same is available through dataSourceApi: getDataError(), getGroupDataError(groupKeys), retryDataLoad() and dismissDataError(groupKeys?).
The first load fails, so the custom DataError component is shown as a mask over the empty body. Click Retry to load the rows.
Then click Reload with an error - the rows stay on screen and the error is shown as a banner over them. The status line above the grid reads the same error through injectDataError().
Each error is an AdaptableDataErrorInfo: the message, the error the function threw or rejected with, the kind of load that failed (load, batch or group) and the params of the failed call.