# DataSource Props

> Props Reference page for your DataSource in Infinite Table - with complete examples

Canonical page: https://infinite-table.com/angular/docs/reference/datasource-props/

In the API Reference below we'll use **`DATA_TYPE`** to refer to the TypeScript type that represents the data the component is bound to.

The props are listed with the names you use in an Angular template: `[(sortInfo)]` is a model (bind it two-way to a signal), `(sortInfoChange)` is an output, `[onRowSelectionChange]` is a function input. The other inputs keep their names. The examples are written for Angular.

### primaryKey (`string | (data: DATA_TYPE) => string`)

> The name of the id/primary key property of an item in the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) array. The value of this property needs to be unique.

This is probably one of the most important properties of the `<DataSource />` component, as it is used to identify items in the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) array.

Unlike with other DataGrid components, with `InfiniteTable` you don't need to have a column mapped to the primary key field.

The primary key is used internally by the component and is not displayed in the grid if you don't explicitly have a column bound to that field.

If the primary key is not unique, Infinite Table DataGrid won't work properly.

**Example: Simple demo of using primaryKey**

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type { InfiniteTablePropColumns } from '@infinite-table/infinite-angular';

type Employee = {
  id: string | number;
  name: string;
  salary: number;
  department: string;
  company: string;
};

const employees: Employee[] = [
  {
    id: 1,
    name: 'Bob',
    salary: 10_000,
    department: 'IT',
    company: 'Bobsons',
  },
  {
    id: 2,
    name: 'Alice',
    salary: 20_000,
    department: 'IT',
    company: 'Bobsons',
  },
  {
    id: 3,
    name: 'John',
    salary: 30_000,
    department: 'IT',
    company: 'Bobsons',
  },
  {
    id: 4,
    name: 'Jane',
    salary: 35_000,
    department: 'Marketing',
    company: 'Janies',
  },
  {
    id: 5,
    name: 'Mary',
    salary: 40_000,
    department: 'Marketing',
    company: 'Janies',
  },
];

// this can be an array, a promise or a function returning array/promise
const data = new Promise<Employee[]>((resolve) => {
  setTimeout(() => {
    resolve(employees);
  }, 100);
});

const columns: InfiniteTablePropColumns<Employee> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 80,
  },
  name: {
    field: 'name',
  },
  salary: { field: 'salary', type: 'number' },
  department: { field: 'department', header: 'Dep.' },
  company: { field: 'company' },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source [data]="data" primaryKey="id">
      <infinite-table
        debugId="data-example"
        [columnDefaultWidth]="130"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly columns = columns;
}
```

The primary key can be either a string (the name of a property in the data object), or a function that returns a string.

Using functions (for more dynamic primary keys) is supported, but hasn't been tested extensively - so please report any issues you might encounter.

### treeExpandState (`TreeExpandStateValue`)

> Specifies the expand/collapse state of the tree nodes. See [`TreeExpandStateValue`](https://infinite-table.com/docs/reference/type-definitions/index.md#TreeExpandStateValue) for the shape of this object. For the uncontrolled version, see [`defaultTreeExpandState`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultTreeExpandState).

If no `treeExpandState` prop is specified, the tree will be rendered as fully expanded by default.

When using the controlled version, make sure to update the `treeExpandState` prop by using the [`(treeExpandStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onTreeExpandStateChange) callback.

**Example: Using controlled tree expand state**

```ts
import { Component, signal } from '@angular/core';
import { JsonPipe } from '@angular/common';

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type {
  InfiniteTableColumn,
  TreeExpandStateValue,
} from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  extension?: string;
  mimeType?: string;
  sizeInKB: number;
  children?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: { field: 'name', header: 'Name', renderTreeIcon: true },
  type: { field: 'type', header: 'Type' },
  extension: { field: 'extension', header: 'Extension' },
  mimeType: { field: 'mimeType', header: 'Mime Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};

const dataSource = () => {
  const nodes: FileSystemNode[] = [
    {
      id: '1',
      name: 'Documents',
      sizeInKB: 1200,
      type: 'folder',
      children: [
        {
          id: '10',
          name: 'Private',
          sizeInKB: 100,
          type: 'folder',
          children: [
            {
              id: '100',
              name: 'Report.docx',
              sizeInKB: 210,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '101',
              name: 'Vacation.docx',
              sizeInKB: 120,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '102',
              name: 'CV.pdf',
              sizeInKB: 108,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '20',
          name: 'unknown.txt',
          sizeInKB: 100,
          type: 'file',
        },
      ],
    },
    {
      id: '3',
      name: 'Media',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '30',
          name: 'Music',
          sizeInKB: 0,
          type: 'folder',
          children: [],
        },
        {
          id: '31',
          name: 'Videos',
          sizeInKB: 5400,
          type: 'folder',
          children: [
            {
              id: '310',
              name: 'Vacation.mp4',
              sizeInKB: 108,
              type: 'file',
              extension: 'mp4',
              mimeType: 'video/mp4',
            },
          ],
        },
      ],
    },
  ];
  return Promise.resolve(nodes);
};

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid, JsonPipe],
  template: `
    <infinite-tree-data-source
      nodesKey="children"
      primaryKey="id"
      [data]="dataSource"
      [(treeExpandState)]="treeExpandState"
    >
      <div style="color: var(--infinite-cell-color); padding: 10px">
        <button
          (click)="
            treeExpandState.set({ defaultExpanded: true, collapsedPaths: [] })
          "
        >
          Expand all
        </button>
        <button
          (click)="
            treeExpandState.set({
              defaultExpanded: false,
              expandedPaths: [],
            })
          "
        >
          Collapse all
        </button>
        <div>
          Current tree expand state:
          <pre>{{ treeExpandState() | json }}</pre>
        </div>
      </div>

      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;

  
  protected readonly treeExpandState = signal<TreeExpandStateValue>({
    defaultExpanded: true,
    collapsedPaths: [['1', '10'], ['3']],
  });
}
```

### onTreeExpandStateChange (`(treeExpandState: TreeExpandStateValue, {dataSourceApi,nodePath, nodeState}) => void`)

> Called when the tree expand state changes.

When the user interacts with the tree (by expanding or collapsing a node), this callback is called with the new tree state.

The first parameter is the new tree state, and the second parameter is an object with the following properties:

- `dataSourceApi` - the [DataSource API](https://infinite-table.com/docs/reference/type-definitions/index.md#DataSourceApi) instance
- `nodePath` - the path of the node that changed state. If the state was produced by an [`expandAll`](https://infinite-table.com/docs/reference/tree-api/index.md#expandAll) or [`collapseAll`](https://infinite-table.com/docs/reference/tree-api/index.md#collapseAll) call, this will be `null`.
- `nodeState` - the new state of the node (`"collapsed"` or `"expanded"`)

**Example: Using the onTreeExpandStateChange callback**

```ts
import { Component, signal } from '@angular/core';
import { JsonPipe } from '@angular/common';

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type {
  InfiniteTableColumn,
  TreeExpandStateValue,
} from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  extension?: string;
  mimeType?: string;
  sizeInKB: number;
  children?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: { field: 'name', header: 'Name', renderTreeIcon: true },
  type: { field: 'type', header: 'Type' },
  extension: { field: 'extension', header: 'Extension' },
  mimeType: { field: 'mimeType', header: 'Mime Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};

const dataSource = () => {
  const nodes: FileSystemNode[] = [
    {
      id: '1',
      name: 'Documents',
      sizeInKB: 1200,
      type: 'folder',
      children: [
        {
          id: '10',
          name: 'Private',
          sizeInKB: 100,
          type: 'folder',
          children: [
            {
              id: '100',
              name: 'Report.docx',
              sizeInKB: 210,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '101',
              name: 'Vacation.docx',
              sizeInKB: 120,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '102',
              name: 'CV.pdf',
              sizeInKB: 108,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '20',
          name: 'unknown.txt',
          sizeInKB: 100,
          type: 'file',
        },
      ],
    },
    {
      id: '3',
      name: 'Media',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '30',
          name: 'Music',
          sizeInKB: 0,
          type: 'folder',
          children: [],
        },
        {
          id: '31',
          name: 'Videos',
          sizeInKB: 5400,
          type: 'folder',
          children: [
            {
              id: '310',
              name: 'Vacation.mp4',
              sizeInKB: 108,
              type: 'file',
              extension: 'mp4',
              mimeType: 'video/mp4',
            },
          ],
        },
      ],
    },
  ];
  return Promise.resolve(nodes);
};

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid, JsonPipe],
  template: `
    <infinite-tree-data-source
      nodesKey="children"
      primaryKey="id"
      [data]="dataSource"
      [(treeExpandState)]="treeExpandState"
    >
      <div style="color: var(--infinite-cell-color); padding: 10px">
        <button
          (click)="
            treeExpandState.set({ defaultExpanded: true, collapsedPaths: [] })
          "
        >
          Expand all
        </button>
        <button
          (click)="
            treeExpandState.set({
              defaultExpanded: false,
              expandedPaths: [],
            })
          "
        >
          Collapse all
        </button>
        <div>
          Current tree expand state:
          <pre>{{ treeExpandState() | json }}</pre>
        </div>
      </div>

      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;

  
  protected readonly treeExpandState = signal<TreeExpandStateValue>({
    defaultExpanded: true,
    collapsedPaths: [['1', '10'], ['3']],
  });
}
```

### onNodeExpand (`(nodePath: NodePath, {dataSourceApi}) => void`)

> Called when a node is expanded. See related [`(nodeCollapse)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onNodeCollapse) and [`(treeExpandStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onTreeExpandStateChange) props.

The [`(nodeExpand)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onNodeExpand) and [`(nodeCollapse)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onNodeCollapse) callbacks are called when a node is expanded or collapsed, respectively - either via user interaction or by an API call. However, they will not be called when the [`expandAll`](https://infinite-table.com/docs/reference/tree-api/index.md#expandAll) or [`collapseAll`](https://infinite-table.com/docs/reference/tree-api/index.md#collapseAll) methods are called.

### isNodeExpanded (`(rowInfo: InfiniteTable_Tree_RowInfoParentNode<DATA_TYPE>, treeExpandState: TreeExpandState) => boolean`)

> Decides if the current (non-leaf) node is expanded. 

The inverse prop, [`isNodeCollapsed`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#isNodeCollapsed) is also available. Only one of these props can be specified.

If this prop is specified, [`treeSelectionState`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeSelectionState) is ignored.

### isNodeCollapsed (`(rowInfo: InfiniteTable_Tree_RowInfoParentNode<DATA_TYPE>, treeExpandState: TreeExpandState) => boolean`)

> Decides if the current (non-leaf) node is collapsed. See related [`[(treeExpandState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeExpandState) prop.

The inverse prop, [`isNodeExpanded`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#isNodeExpanded) is also available. Only one of these props can be specified.

If this prop is specified, [`treeSelectionState`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeSelectionState) is ignored.

### isNodeReadOnly (`(rowInfo: InfiniteTable_Tree_RowInfoParentNode<DATA_TYPE>) => boolean`)

> Decides if the current (non-leaf) node can be expanded or collapsed and if the tree icon is disabled.

By default, parent nodes with `children: []` are read-only, meaning they won't respond to expand/collapse clicks.

However, if you specify a custom `isNodeReadOnly` function, you can change this behavior.

When a node is read-only, the [`expandNode`](https://infinite-table.com/docs/reference/tree-api/index.md#expandNode) and [`collapseNode`](https://infinite-table.com/docs/reference/tree-api/index.md#collapseNode) methods need the `options.force` flag to be set to `true` in order to override the read-only restriction.

However, [`expandAll`](https://infinite-table.com/docs/reference/tree-api/index.md#expandAll) and [`collapseAll`](https://infinite-table.com/docs/reference/tree-api/index.md#collapseAll) will work regardless of the `isNodeReadOnly` setting.

For full control over the expand/collapse state of read-only nodes, you can use the [`isNodeExpanded`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#isNodeExpanded)/[`isNodeCollapsed`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#isNodeCollapsed) props.

**Example: Using a custom isNodeReadOnly function**

```ts
import { Component, signal } from '@angular/core';

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type {
  InfiniteTableColumn,
  TreeExpandStateValue,
} from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  extension?: string;
  mimeType?: string;
  sizeInKB: number;
  children?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: { field: 'name', header: 'Name', renderTreeIcon: true },
  type: { field: 'type', header: 'Type' },
  extension: { field: 'extension', header: 'Extension' },
  mimeType: { field: 'mimeType', header: 'Mime Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};

const defaultTreeExpandState: TreeExpandStateValue = {
  defaultExpanded: true,
  collapsedPaths: [['1', '10']],
};

const returnFalse = () => false;

const dataSource = () => {
  const nodes: FileSystemNode[] = [
    {
      id: '1',
      name: 'Documents',
      sizeInKB: 1200,
      type: 'folder',
      children: [
        {
          id: '10',
          name: 'Private',
          sizeInKB: 100,
          type: 'folder',
          children: [
            {
              id: '100',
              name: 'Report.docx',
              sizeInKB: 210,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '101',
              name: 'Vacation.docx',
              sizeInKB: 120,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '102',
              name: 'CV.pdf',
              sizeInKB: 108,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop - empty',
      sizeInKB: 1000,
      type: 'folder',
      children: [],
    },
    {
      id: '3',
      name: 'Media',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '30',
          name: 'Music - empty',
          sizeInKB: 0,
          type: 'folder',
          children: [],
        },
        {
          id: '31',
          name: 'Videos',
          sizeInKB: 5400,
          type: 'folder',
          children: [
            {
              id: '310',
              name: 'Vacation.mp4',
              sizeInKB: 108,
              type: 'file',
              extension: 'mp4',
              mimeType: 'video/mp4',
            },
          ],
        },
      ],
    },
  ];
  return Promise.resolve(nodes);
};

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid],
  template: `
    <infinite-tree-data-source
      nodesKey="children"
      primaryKey="id"
      [data]="dataSource"
      [defaultTreeExpandState]="defaultTreeExpandState"
      [isNodeReadOnly]="allowEmptyNodesExpand() ? returnFalse : undefined"
    >
      <div style="color: var(--infinite-cell-color); padding: 10px">
        <pre>Empty parent nodes {{ allowEmptyNodesExpand() ? 'can' : 'cannot' }} be expanded.</pre>
        <button (click)="allowEmptyNodesExpand.set(!allowEmptyNodesExpand())">
          Toggle read-only for empty nodes
        </button>
      </div>

      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly defaultTreeExpandState = defaultTreeExpandState;
  protected readonly returnFalse = returnFalse;

  protected readonly allowEmptyNodesExpand = signal(false);
}
```

### onNodeCollapse (`(nodePath: NodePath, {dataSourceApi}) => void`)

> Called when a node is collapsed. See related [`(nodeExpand)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onNodeExpand) and [`(treeExpandStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onTreeExpandStateChange) props.

The [`(nodeExpand)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onNodeExpand) and [`(nodeCollapse)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onNodeCollapse) callbacks are called when a node is expanded or collapsed, respectively - either via user interaction or by an API call. However, they will not be called when the [`expandAll`](https://infinite-table.com/docs/reference/tree-api/index.md#expandAll) or [`collapseAll`](https://infinite-table.com/docs/reference/tree-api/index.md#collapseAll) methods are called.

### nodesKey (`string`)

> The name of the property in the data object that contains the child nodes for each tree node.

Only available when you're using the `<TreeDataSource />` component.

If not specified, it defaults to `"children"`.

Each node gets a `nodePath` property, which is the array with the ids of all the parent nodes leading down to the current node. The node path includes the id of the current node

```tsx
const data = [
  { id: '1', name: 'Documents',                // path: ['1']
    children: [
      { id: '10', name: 'Private',             // path: ['1', '10']
        children: [
          { id: '100', name: 'Report.docx' },  // path: ['1', '10', '100']
          { id: '101', name: 'Vacation.docx' },// path: ['1', '10', '101']
        ],
      },
    ]
  },
  {
    id: '2',
    name: 'Downloads',                        // path: ['2']
    children: [
      {
        id: '20',
        name: 'cat.jpg',                      // path: ['2', '20']
      },
    ],
  },
];
```

**Example: Using a custom nodesKey prop**

```ts
import { Component } from '@angular/core';

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type { InfiniteTableColumn } from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  extension?: string;
  mimeType?: string;
  sizeInKB: number;
  nodes?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: { field: 'name', header: 'Name', renderTreeIcon: true },
  type: { field: 'type', header: 'Type' },
  extension: { field: 'extension', header: 'Extension' },
  mimeType: { field: 'mimeType', header: 'Mime Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};

const dataSource = () => {
  const nodes: FileSystemNode[] = [
    {
      id: '1',
      name: 'Documents',
      sizeInKB: 1200,
      type: 'folder',
      nodes: [
        {
          id: '10',
          name: 'Private',
          sizeInKB: 100,
          type: 'folder',
          nodes: [
            {
              id: '100',
              name: 'Report.docx',
              sizeInKB: 210,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '101',
              name: 'Vacation.docx',
              sizeInKB: 120,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '102',
              name: 'CV.pdf',
              sizeInKB: 108,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop',
      sizeInKB: 1000,
      type: 'folder',
      nodes: [
        {
          id: '20',
          name: 'unknown.txt',
          sizeInKB: 100,
          type: 'file',
        },
      ],
    },
    {
      id: '3',
      name: 'Media',
      sizeInKB: 1000,
      type: 'folder',
      nodes: [
        {
          id: '30',
          name: 'Music',
          sizeInKB: 0,
          type: 'folder',
          nodes: [],
        },
        {
          id: '31',
          name: 'Videos',
          sizeInKB: 5400,
          type: 'folder',
          nodes: [
            {
              id: '310',
              name: 'Vacation.mp4',
              sizeInKB: 108,
              type: 'file',
              extension: 'mp4',
              mimeType: 'video/mp4',
            },
          ],
        },
      ],
    },
  ];
  return Promise.resolve(nodes);
};

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid],
  template: `
    <infinite-tree-data-source
      nodesKey="nodes"
      primaryKey="id"
      [data]="dataSource"
    >
      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
}
```

### defaultTreeExpandState (`TreeExpandStateValue`)

> Specifies the expand/collapse state of the tree nodes. See [`TreeExpandStateValue`](https://infinite-table.com/docs/reference/type-definitions/index.md#TreeExpandStateValue) for the shape of this object. For the controlled version, see [`[(treeExpandState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeExpandState).

**Example: Using uncontrolled tree expand state**

```ts
import { Component } from '@angular/core';

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type {
  DataSourceApi,
  InfiniteTableColumn,
  TreeExpandStateValue,
} from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  extension?: string;
  mimeType?: string;
  sizeInKB: number;
  children?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: { field: 'name', header: 'Name', renderTreeIcon: true },
  type: { field: 'type', header: 'Type' },
  extension: { field: 'extension', header: 'Extension' },
  mimeType: { field: 'mimeType', header: 'Mime Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};

const defaultTreeExpandState: TreeExpandStateValue = {
  defaultExpanded: true,
  collapsedPaths: [['1', '10'], ['3']],
};

const dataSource = () => {
  const nodes: FileSystemNode[] = [
    {
      id: '1',
      name: 'Documents',
      sizeInKB: 1200,
      type: 'folder',
      children: [
        {
          id: '10',
          name: 'Private',
          sizeInKB: 100,
          type: 'folder',
          children: [
            {
              id: '100',
              name: 'Report.docx',
              sizeInKB: 210,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '101',
              name: 'Vacation.docx',
              sizeInKB: 120,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '102',
              name: 'CV.pdf',
              sizeInKB: 108,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '20',
          name: 'unknown.txt',
          sizeInKB: 100,
          type: 'file',
        },
      ],
    },
    {
      id: '3',
      name: 'Media',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '30',
          name: 'Music',
          sizeInKB: 0,
          type: 'folder',
          children: [],
        },
        {
          id: '31',
          name: 'Videos',
          sizeInKB: 5400,
          type: 'folder',
          children: [
            {
              id: '310',
              name: 'Vacation.mp4',
              sizeInKB: 108,
              type: 'file',
              extension: 'mp4',
              mimeType: 'video/mp4',
            },
          ],
        },
      ],
    },
  ];
  return Promise.resolve(nodes);
};

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid],
  template: `
    <infinite-tree-data-source
      (ready)="dataSourceApi = $event"
      nodesKey="children"
      primaryKey="id"
      [data]="dataSource"
      [defaultTreeExpandState]="defaultTreeExpandState"
    >
      <div style="color: var(--infinite-cell-color); padding: 10px">
        <button (click)="dataSourceApi!.treeApi.expandAll()">Expand all</button>
        <button (click)="dataSourceApi!.treeApi.collapseAll()">
          Collapse all
        </button>
      </div>

      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly columns = columns;
  protected readonly dataSource = dataSource;
  protected readonly defaultTreeExpandState = defaultTreeExpandState;

  protected dataSourceApi: DataSourceApi<FileSystemNode> | null = null;
}
```

### isRowDisabled (`(rowInfo: InfiniteTableRowInfo<T>) => boolean`)

> This function ultimately decides the disabled state of a row. It overrides both [`defaultRowDisabledState`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultRowDisabledState)/[`[(rowDisabledState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#rowDisabledState) props.

It's called with a single argument - the [row info object](https://infinite-table.com/docs/reference/type-definitions/index.md#InfiniteTableRowInfo) for the row in question.

It should return `true` if the row is disabled, and `false` otherwise.

When this prop is used, [`(rowDisabledStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onRowDisabledStateChange) will not be called.

### defaultRowDisabledState (`{enabledRows,disabledRows}`)

> The uncontrolled prop for managing row enabled/disabled state. For the controlled version see [`[(rowDisabledState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#rowDisabledState). For listening to row disabled state changes, see [`(rowDisabledStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onRowDisabledStateChange).

The value for this prop is an object with two properties:

- `enabledRows` - either `true` or an array of row ids that are enabled. When `true` is passed, `disabledRows` should be an array of row ids that are disabled.
- `disabledRows` - either `true` or an array of row ids that are disabled. When `true` is passed, `enabledRows` should be an array of row ids that are enabled.

The values in the `enabledRows`/`disabledRows` arrays are row ids, and not indexes.

This prop can be overriden by using the [`isRowDisabled`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#isRowDisabled) prop.

Here's an example of how to use the `defaultRowDisabledState` prop:

Rows with ids `1`, `3`, `4` and `5` are disabled.

**Example: Using uncontrolled row disabled state**

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;

  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';

  salary: number;
};

const data: DataSourceData<Developer> = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql?`)
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 100,
  },
  salary: {
    defaultFilterable: true,
    field: 'salary',
    type: 'number',
  },

  firstName: {
    field: 'firstName',
  },
  stack: { field: 'stack' },
  currency: { field: 'currency' },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="data"
      primaryKey="id"
      [defaultRowDisabledState]="{
        enabledRows: true,
        disabledRows: [1, 3, 4, 5],
      }"
    >
      <infinite-table
        debugId="defaultRowDisabledState-example"
        keyboardNavigation="row"
        [columnDefaultWidth]="120"
        [columnMinWidth]="50"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly columns = columns;
}
```

### rowDisabledState (`{enabledRows,disabledRows}`)

> Manages row enabled/disabled state. For the uncontrolled version see [`defaultRowDisabledState`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultRowDisabledState). For listening to row disabled state changes, see [`(rowDisabledStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onRowDisabledStateChange).

The value for this prop is an object with two properties:

- `enabledRows` - either `true` or an array of row ids that are enabled. When `true` is passed, `disabledRows` should be an array of row ids that are disabled.
- `disabledRows` - either `true` or an array of row ids that are disabled. When `true` is passed, `enabledRows` should be an array of row ids that are enabled.

When using this controlled prop, you will need to update the `rowDisabledState` prop by using the [`(rowDisabledStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onRowDisabledStateChange) callback.

This prop can be overriden by using the [`isRowDisabled`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#isRowDisabled) prop.

Rows with ids `1`, `3`, `4` and `5` are disabled initially.

Right click rows and use the context menu to enable/disable rows.

**Example: Using controlled row disabled state**

```ts
import { Component, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  DataSourceProps,
  InfiniteTablePropColumns,
  InfiniteTablePropGetCellContextMenuItems,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;

  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';

  salary: number;
};

const data: DataSourceData<Developer> = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql?`)
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 100,
  },
  salary: {
    defaultFilterable: true,
    field: 'salary',
    type: 'number',
  },

  firstName: {
    field: 'firstName',
  },
  stack: { field: 'stack' },
  currency: { field: 'currency' },
};

const getCellContextMenuItems: InfiniteTablePropGetCellContextMenuItems<
  Developer
> = ({ rowInfo }, { dataSourceApi }) => {
  const rowDisabled = dataSourceApi.isRowDisabledAt(rowInfo.indexInAll);
  return {
    columns: [{ name: 'label' }],
    items: [
      {
        label: 'Disable row',
        disabled: rowDisabled,
        key: 'disable-row',
        onAction: ({ hideMenu }) => {
          dataSourceApi.setRowEnabledAt(rowInfo.indexInAll, false);
          hideMenu();
        },
      },
      {
        label: 'Enable row',
        disabled: !rowDisabled,
        key: 'enable-row',
        onAction: ({ hideMenu }) => {
          dataSourceApi.setRowEnabled(rowInfo.id, true);
          hideMenu();
        },
      },
      {
        label: 'Toggle row enable/disable',
        key: 'toggle-row',
        onAction: ({ hideMenu }) => {
          dataSourceApi.setRowEnabled(
            rowInfo.id,
            dataSourceApi.isRowDisabled(rowInfo.id),
          );
          hideMenu();
        },
      },
    ],
  };
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="data"
      primaryKey="id"
      [(rowDisabledState)]="rowDisabledState"
    >
      <infinite-table
        debugId="rowDisabledState-example"
        [getCellContextMenuItems]="getCellContextMenuItems"
        keyboardNavigation="row"
        [columnDefaultWidth]="120"
        [columnMinWidth]="50"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly columns = columns;
  protected readonly getCellContextMenuItems = getCellContextMenuItems;

  
  protected readonly rowDisabledState = signal<
    DataSourceProps<Developer>['rowDisabledState']
  >({
    enabledRows: true,
    disabledRows: [1, 3, 4, 5],
  });
}
```

### treeSelection (`TreeSelectionValue`)

> Determines what nodes are selected and deselected. For the uncontrolled version see [`defaultTreeSelection`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultTreeSelection).

The value of this prop determines if a node is selected or not.

See [`TreeSelectionValue`](https://infinite-table.com/docs/reference/type-definitions/index.md#TreeSelectionValue) for details on the shape of this object.

**Example: Using controlled tree selection**

```ts
import { Component, signal } from '@angular/core';
import { JsonPipe } from '@angular/common';

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type {
  InfiniteTableColumn,
  TreeSelectionValue,
} from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  extension?: string;
  mimeType?: string;
  sizeInKB: number;
  children?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: {
    field: 'name',
    header: 'Name',
    renderTreeIcon: true,
    renderSelectionCheckBox: true,
  },
  type: { field: 'type', header: 'Type' },
  extension: { field: 'extension', header: 'Extension' },
  mimeType: { field: 'mimeType', header: 'Mime Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};

const dataSource = () => {
  const nodes: FileSystemNode[] = [
    {
      id: '1',
      name: 'Documents',
      sizeInKB: 1200,
      type: 'folder',
      children: [
        {
          id: '10',
          name: 'Private',
          sizeInKB: 100,
          type: 'folder',
          children: [
            {
              id: '100',
              name: 'Report.docx',
              sizeInKB: 210,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '101',
              name: 'Vacation.docx',
              sizeInKB: 120,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '102',
              name: 'CV.pdf',
              sizeInKB: 108,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '20',
          name: 'unknown.txt',
          sizeInKB: 100,
          type: 'file',
        },
      ],
    },
    {
      id: '3',
      name: 'Media',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '31',
          name: 'Videos',
          sizeInKB: 5400,
          type: 'folder',
          children: [
            {
              id: '310',
              name: 'Vacation.mp4',
              sizeInKB: 108,
              type: 'file',
              extension: 'mp4',
              mimeType: 'video/mp4',
            },
          ],
        },
      ],
    },
  ];
  return Promise.resolve(nodes);
};

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid, JsonPipe],
  template: `
    <infinite-tree-data-source
      nodesKey="children"
      primaryKey="id"
      [data]="dataSource"
      [(treeSelection)]="treeSelection"
    >
      <div style="color: var(--infinite-cell-color); padding: 10px">
        <button
          (click)="
            treeSelection.set({
              defaultSelection: false,
              selectedPaths: [],
            })
          "
        >
          Deselect all
        </button>
        <button
          (click)="
            treeSelection.set({
              defaultSelection: true,
              deselectedPaths: [],
            })
          "
        >
          Select all
        </button>
        <div style="overflow: auto; height: 10vh; min-height: 200px">
          Current tree selection:
          <pre>{{ treeSelection() | json }}</pre>
        </div>
      </div>

      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;

  
  protected readonly treeSelection = signal<TreeSelectionValue>({
    defaultSelection: false,
    selectedPaths: [['1', '10'], ['3']],
  });
}
```

### onTreeSelectionChange (`(treeSelection: TreeSelectionValue, context) => void`)

> Called when the tree selection changes. See [`[(treeSelection)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeSelection).

**Example: Reacting to tree selection changes**

```ts
import { Component, signal } from '@angular/core';
import { JsonPipe } from '@angular/common';

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type {
  InfiniteTableColumn,
  TreeSelectionValue,
} from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  extension?: string;
  mimeType?: string;
  sizeInKB: number;
  children?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: {
    field: 'name',
    header: 'Name',
    renderTreeIcon: true,
    renderSelectionCheckBox: true,
  },
  type: { field: 'type', header: 'Type' },
  extension: { field: 'extension', header: 'Extension' },
  mimeType: { field: 'mimeType', header: 'Mime Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};

const dataSource = () => {
  const nodes: FileSystemNode[] = [
    {
      id: '1',
      name: 'Documents',
      sizeInKB: 1200,
      type: 'folder',
      children: [
        {
          id: '10',
          name: 'Private',
          sizeInKB: 100,
          type: 'folder',
          children: [
            {
              id: '100',
              name: 'Report.docx',
              sizeInKB: 210,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '101',
              name: 'Vacation.docx',
              sizeInKB: 120,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '102',
              name: 'CV.pdf',
              sizeInKB: 108,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '20',
          name: 'unknown.txt',
          sizeInKB: 100,
          type: 'file',
        },
      ],
    },
    {
      id: '3',
      name: 'Media',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '31',
          name: 'Videos',
          sizeInKB: 5400,
          type: 'folder',
          children: [
            {
              id: '310',
              name: 'Vacation.mp4',
              sizeInKB: 108,
              type: 'file',
              extension: 'mp4',
              mimeType: 'video/mp4',
            },
          ],
        },
      ],
    },
  ];
  return Promise.resolve(nodes);
};

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid, JsonPipe],
  template: `
    <infinite-tree-data-source
      nodesKey="children"
      primaryKey="id"
      [data]="dataSource"
      [(treeSelection)]="treeSelection"
    >
      <div style="color: var(--infinite-cell-color); padding: 10px">
        <button
          (click)="
            treeSelection.set({
              defaultSelection: false,
              selectedPaths: [],
            })
          "
        >
          Deselect all
        </button>
        <button
          (click)="
            treeSelection.set({
              defaultSelection: true,
              deselectedPaths: [],
            })
          "
        >
          Select all
        </button>
        <div style="overflow: auto; height: 10vh; min-height: 200px">
          Current tree selection:
          <pre>{{ treeSelection() | json }}</pre>
        </div>
      </div>

      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;

  
  protected readonly treeSelection = signal<TreeSelectionValue>({
    defaultSelection: false,
    selectedPaths: [['1', '10'], ['3']],
  });
}
```

When using `multi-row` [`selectionMode`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#selectionMode), the signature of this callback is:

 - `treeSelection` - the new [tree selection state](https://infinite-table.com/docs/reference/type-definitions/index.md#TreeSelectionValue)
 - `context` - an object with the following properties:
   - `selectionMode` - will be `"multi-row"`
   - `lastUpdatedNodePath` - the path of the node that was last updated (either via user action or api call). Will be `null` of the action that triggered this callback was [`selectAll`](https://infinite-table.com/docs/reference/tree-api/index.md#selectAll) or [`deselectAll`](https://infinite-table.com/docs/reference/tree-api/index.md#deselectAll).
   - `dataSourceApi` - the [DataSource API](https://infinite-table.com/angular/docs/reference/datasource-api/index.md) instance

### defaultTreeSelection (`TreeSelectionValue`)

> Determines what nodes are selected and deselected. For the controlled version see [`[(treeSelection)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeSelection).

The value of this prop determines if a node is selected or not.

See [`TreeSelectionValue`](https://infinite-table.com/docs/reference/type-definitions/index.md#TreeSelectionValue) for details on the shape of this object.

**Example: Using uncontrolled tree selection**

```ts
import { Component } from '@angular/core';

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type {
  DataSourceApi,
  InfiniteTableColumn,
  TreeSelectionValue,
} from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  extension?: string;
  mimeType?: string;
  sizeInKB: number;
  children?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: {
    field: 'name',
    header: 'Name',
    renderTreeIcon: true,
    renderSelectionCheckBox: true,
  },
  type: { field: 'type', header: 'Type' },
  extension: { field: 'extension', header: 'Extension' },
  mimeType: { field: 'mimeType', header: 'Mime Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};
const defaultTreeSelection: TreeSelectionValue = {
  defaultSelection: false,
  selectedPaths: [['1', '10'], ['3']],
};

const dataSource = () => {
  const nodes: FileSystemNode[] = [
    {
      id: '1',
      name: 'Documents',
      sizeInKB: 1200,
      type: 'folder',
      children: [
        {
          id: '10',
          name: 'Private',
          sizeInKB: 100,
          type: 'folder',
          children: [
            {
              id: '100',
              name: 'Report.docx',
              sizeInKB: 210,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '101',
              name: 'Vacation.docx',
              sizeInKB: 120,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '102',
              name: 'CV.pdf',
              sizeInKB: 108,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '20',
          name: 'unknown.txt',
          sizeInKB: 100,
          type: 'file',
        },
      ],
    },
    {
      id: '3',
      name: 'Media',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '31',
          name: 'Videos',
          sizeInKB: 5400,
          type: 'folder',
          children: [
            {
              id: '310',
              name: 'Vacation.mp4',
              sizeInKB: 108,
              type: 'file',
              extension: 'mp4',
              mimeType: 'video/mp4',
            },
          ],
        },
      ],
    },
  ];
  return Promise.resolve(nodes);
};

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid],
  template: `
    <infinite-tree-data-source
      (ready)="dataSourceApi = $event"
      nodesKey="children"
      primaryKey="id"
      [data]="dataSource"
      [defaultTreeSelection]="defaultTreeSelection"
    >
      <div style="color: var(--infinite-cell-color); padding: 10px">
        <button (click)="dataSourceApi!.treeApi.deselectAll()">
          Deselect all
        </button>
        <button (click)="dataSourceApi!.treeApi.selectAll()">Select all</button>
      </div>

      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly columns = columns;
  protected readonly dataSource = dataSource;
  protected readonly defaultTreeSelection = defaultTreeSelection;

  protected dataSourceApi: DataSourceApi<FileSystemNode> | null = null;
}
```

### onRowDisabledStateChange (`(rowDisabledState) => void`)

> Called when the row disabled state changes.

It's called with just 1 argument (`rowDisabledState`), which is an instance of the `RowDisabledState` class. To get a literal object that represents the row disabled state, call the `rowDisabledState.getState()` method.

```ts
import { Component, signal } from '@angular/core';
import {
  DataSource,
  RowDisabledState,
  type DataSourceProps,
  type RowDisabledStateObject,
} from '@infinite-table/infinite-angular';

@Component({
  selector: 'app-root',
  imports: [DataSource],
  template: `
    <infinite-data-source
      [data]="data"
      primaryKey="id"
      [rowDisabledState]="rowDisabledState()"
      (rowDisabledStateChange)="onRowDisabledStateChange($event)"
    />
  `,
})
export class App {
  protected readonly data = data;

  protected readonly rowDisabledState = signal<RowDisabledStateObject<number>>({
    enabledRows: true,
    disabledRows: [1, 3, 4, 5],
  });

  protected onRowDisabledStateChange(
    rowState: DataSourceProps<Developer>['rowDisabledState'],
  ) {
    // called with a RowDisabledState instance
    if (rowState instanceof RowDisabledState) {
      this.rowDisabledState.set(rowState.getState());
    }
  }
}
```

When using the controlled [`[(rowDisabledState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#rowDisabledState) prop, you will need to update the `rowDisabledState` by using this callback.

Rows with ids `1`, `3`, `4` and `5` are disabled initially.

Right click rows and use the context menu to enable/disable rows.

**Example: Using the onRowDisabledStateChange callback to update row disabled state**

```ts
import { Component, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  DataSourceProps,
  InfiniteTablePropColumns,
  InfiniteTablePropGetCellContextMenuItems,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;

  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';

  salary: number;
};

const data: DataSourceData<Developer> = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql?`)
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 100,
  },
  salary: {
    defaultFilterable: true,
    field: 'salary',
    type: 'number',
  },

  firstName: {
    field: 'firstName',
  },
  stack: { field: 'stack' },
  currency: { field: 'currency' },
};

const getCellContextMenuItems: InfiniteTablePropGetCellContextMenuItems<
  Developer
> = ({ rowInfo }, { dataSourceApi }) => {
  const rowDisabled = dataSourceApi.isRowDisabledAt(rowInfo.indexInAll);
  return {
    columns: [{ name: 'label' }],
    items: [
      {
        label: 'Disable row',
        disabled: rowDisabled,
        key: 'disable-row',
        onAction: ({ hideMenu }) => {
          dataSourceApi.setRowEnabledAt(rowInfo.indexInAll, false);
          hideMenu();
        },
      },
      {
        label: 'Enable row',
        disabled: !rowDisabled,
        key: 'enable-row',
        onAction: ({ hideMenu }) => {
          dataSourceApi.setRowEnabled(rowInfo.id, true);
          hideMenu();
        },
      },
      {
        label: 'Toggle row enable/disable',
        key: 'toggle-row',
        onAction: ({ hideMenu }) => {
          dataSourceApi.setRowEnabled(
            rowInfo.id,
            dataSourceApi.isRowDisabled(rowInfo.id),
          );
          hideMenu();
        },
      },
    ],
  };
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="data"
      primaryKey="id"
      [(rowDisabledState)]="rowDisabledState"
    >
      <infinite-table
        debugId="rowDisabledState-example"
        [getCellContextMenuItems]="getCellContextMenuItems"
        keyboardNavigation="row"
        [columnDefaultWidth]="120"
        [columnMinWidth]="50"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly columns = columns;
  protected readonly getCellContextMenuItems = getCellContextMenuItems;

  
  protected readonly rowDisabledState = signal<
    DataSourceProps<Developer>['rowDisabledState']
  >({
    enabledRows: true,
    disabledRows: [1, 3, 4, 5],
  });
}
```

### aggregationReducers (`Record<string, DataSourceAggregationReducer>`)

> Specifies the functions to use for aggregating data. The object is a map where the keys are ids for aggregations and values are object of the shape described below.

The `DataSourceAggregationReducer` type can have the following properties

- `initialValue` - type `any`, mandatory for client-side aggregations. It can be a function, in which case, it will be called to compute the initial value for the aggregation. Otherwise, the initial value will be used as is.
- `field` - the field to aggregate on. Optional - if not specified, make sure you specify `getter`
- `getter`: `(data:T)=> any` - a getter function, called with the current `data` object.
- `reducer`: `string | (accumulator, value, data: T) => any` - either a string (for server-side aggregations) or a mandatory aggregation function for client-side aggregations.
- `done`: `(accumulator, arr: T[]) => any` - a function that is called to finish the aggregation after all values have been accumulated. The function should return the final value of the aggregation. Only used for client-side aggregations.
- `name` - useful especially in combination with [`[(pivotBy)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#pivotBy), as it will be used as the pivot column header.
- `pivotColumn` - if specified, will configure the pivot column generated for this aggregation. This object has the same shape as a normal [column](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns), but supports some extra props like `inheritFromColumn` See [`aggregationReducers.pivotColumn`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#aggregationReducers.pivotColumn).

**Example: Aggregation demo - see `salary` column**
```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropAggregationReducers,
  DataSourcePropGroupBy,
} from '@infinite-table/infinite-angular';

import { columns } from './columns.angular';
import type { Employee } from './columns.angular';

const columnSizing: Record<string, { width: number }> = {
  'country-group': { width: 250 },
};

const groupBy: DataSourcePropGroupBy<Employee> = [
  {
    field: 'country',
    column: {
      id: 'country-group',
      renderValue: ({ data, isGroupRow, value }) =>
        isGroupRow ? value : `Country: ${data?.country}!`,
      style: {
        color: 'tomato',
      },
    },
  },
];

const reducers: DataSourcePropAggregationReducers<Employee> = {
  avgSalary: {
    reducer: (acc, value) => acc + value,
    done: (sum, arr) => Math.floor(arr.length ? sum / arr.length : 0),
    field: 'salary',
    initialValue: 0,
  },
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/employees1k')
    .then((r) => r.json())
    .then((data: Employee[]) => data);
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [aggregationReducers]="reducers"
      [groupBy]="groupBy"
    >
      <infinite-table
        debugId="groupBy-example"
        [columns]="columns"
        [defaultColumnSizing]="columnSizing"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly columnSizing = columnSizing;
  protected readonly groupBy = groupBy;
  protected readonly reducers = reducers;
}
```

Aggregation reducers can be used in combination with grouping and pivoting. The example below shows aggregations used with server-side pivoting

**Example: Aggregations used together with server-side pivoting**

```ts
import { Component } from '@angular/core';

import {
  InfiniteTable,
  DataSource,
  GroupRowsState,
} from '@infinite-table/infinite-angular';
import type {
  InfiniteTablePropColumns,
  InfiniteTablePropColumnPinning,
  DataSourceData,
  DataSourcePropAggregationReducers,
  DataSourceGroupBy,
  DataSourcePivotBy,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const DATA_SOURCE_SIZE = '10k';

const dataSource: DataSourceData<Developer> = ({
  pivotBy,
  aggregationReducers,
  groupBy,

  groupKeys = [],
}) => {
  const args = [
    pivotBy
      ? 'pivotBy=' + JSON.stringify(pivotBy.map((p) => ({ field: p.field })))
      : null,
    `groupKeys=${JSON.stringify(groupKeys)}`,
    groupBy
      ? 'groupBy=' + JSON.stringify(groupBy.map((p) => ({ field: p.field })))
      : null,
    aggregationReducers
      ? 'reducers=' +
        JSON.stringify(
          Object.keys(aggregationReducers).map((key) => ({
            field: aggregationReducers[key].field,
            id: key,
            name: aggregationReducers[key].reducer,
          })),
        )
      : null,
  ]
    .filter(Boolean)
    .join('&');
  return fetch(
    process.env.NEXT_PUBLIC_BASE_URL +
      `/developers${DATA_SOURCE_SIZE}-sql?` +
      args,
  )
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const aggregationReducers: DataSourcePropAggregationReducers<Developer> = {
  salary: {
    // the aggregation name will be used as the column header
    name: 'Salary (avg)',
    field: 'salary',
    reducer: 'avg',
  },
  age: {
    name: 'Age (avg)',
    field: 'age',
    reducer: 'avg',
  },
};

const columns: InfiniteTablePropColumns<Developer> = {
  preferredLanguage: { field: 'preferredLanguage' },
  age: { field: 'age' },

  salary: {
    field: 'salary',
    type: 'number',
  },
  canDesign: { field: 'canDesign' },
  country: { field: 'country' },
  firstName: { field: 'firstName' },
  stack: { field: 'stack' },
  id: { field: 'id' },
  hobby: { field: 'hobby' },
  city: { field: 'city' },
  currency: { field: 'currency' },
};

// make the row labels column (id: 'labels') be pinned
const defaultColumnPinning: InfiniteTablePropColumnPinning = {
  // make the generated group columns pinned to start
  'group-by-country': 'start',
  'group-by-stack': 'start',
};

// make all rows collapsed by default
const groupRowsState = new GroupRowsState({
  expandedRows: [],
  collapsedRows: true,
});

const groupBy: DataSourceGroupBy<Developer>[] = [
  {
    field: 'country',
    column: {
      // give the group column for the country prop a custom id
      id: 'group-by-country',
    },
  },
  {
    field: 'stack',
    column: {
      // give the group column for the stack prop a custom id
      id: 'group-by-stack',
    },
  },
];

const pivotBy: DataSourcePivotBy<Developer>[] = [
  { field: 'preferredLanguage' },
  {
    field: 'canDesign',
    // customize the column group
    columnGroup: ({ columnGroup }) => {
      return {
        ...columnGroup,
        header: `${
          columnGroup.pivotGroupKey === 'yes' ? 'Designer' : 'Non-designer'
        }`,
      };
    },
    // customize columns generated under this column group
    column: ({ column }) => ({
      ...column,
      header: `🎉 ${column.header}`,
    }),
  },
];

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      #ds="infiniteDataSource"
      primaryKey="id"
      [data]="dataSource"
      [groupBy]="groupBy"
      [pivotBy]="pivotBy"
      [aggregationReducers]="aggregationReducers"
      [defaultGroupRowsState]="groupRowsState"
      [lazyLoad]="true"
    >
      <infinite-table
        debugId="remote-pivoting-example"
        [defaultColumnPinning]="defaultColumnPinning"
        [columns]="columns"
        [hideEmptyGroupColumns]="true"
        [pivotColumns]="ds.pivotColumns()"
        [pivotColumnGroups]="ds.pivotColumnGroups()"
        [columnDefaultWidth]="220"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly aggregationReducers = aggregationReducers;
  protected readonly columns = columns;
  protected readonly dataSource = dataSource;
  protected readonly defaultColumnPinning = defaultColumnPinning;
  protected readonly groupBy = groupBy;
  protected readonly groupRowsState = groupRowsState;
  protected readonly pivotBy = pivotBy;
}
```

Pivot columns generated for aggregations will inehrit from initial columns - the example shows how to leverage this behavior and how to extend it

**Example: Pivot columns inherit from original columns bound to the same field**

```ts
import { Component } from '@angular/core';

import {
  InfiniteTable,
  DataSource,
  GroupRowsState,
} from '@infinite-table/infinite-angular';
import type {
  DataSourcePropAggregationReducers,
  InfiniteTableColumnAggregator,
  InfiniteTablePropColumns,
  DataSourceGroupBy,
  DataSourcePivotBy,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers100')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const avgReducer: InfiniteTableColumnAggregator<Developer, any> = {
  initialValue: 0,
  reducer: (acc, sum) => acc + sum,
  done: (sum, arr) => (arr.length ? sum / arr.length : 0),
};

const columnAggregations: DataSourcePropAggregationReducers<Developer> = {
  avgSalary: {
    field: 'salary',
    name: 'Average salary',
    ...avgReducer,
  },
  avgAge: {
    field: 'age',
    ...avgReducer,
    pivotColumn: {
      defaultWidth: 500,
      inheritFromColumn: 'firstName',
    },
  },
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: { field: 'id' },
  firstName: {
    field: 'firstName',
    style: {
      fontWeight: 'bold',
    },
    renderValue: ({ value }) => [value, '!'],
  },
  preferredLanguage: { field: 'preferredLanguage' },
  stack: { field: 'stack' },
  country: { field: 'country' },
  canDesign: { field: 'canDesign' },
  hobby: { field: 'hobby' },

  city: { field: 'city' },
  age: { field: 'age' },
  salary: {
    field: 'salary',
    type: 'number',
    header: 'Salary',
    style: { color: 'red' },
  },
  currency: { field: 'currency' },
};

const groupRowsState = new GroupRowsState({
  expandedRows: [],
  collapsedRows: true,
});

const groupBy: DataSourceGroupBy<Developer>[] = [
  {
    field: 'preferredLanguage',
  },
  { field: 'stack' },
];

const pivotBy: DataSourcePivotBy<Developer>[] = [
  { field: 'country' },
  {
    field: 'canDesign',
  },
];

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      #ds="infiniteDataSource"
      primaryKey="id"
      [data]="dataSource"
      [groupBy]="groupBy"
      [pivotBy]="pivotBy"
      [aggregationReducers]="columnAggregations"
      [defaultGroupRowsState]="groupRowsState"
    >
      <infinite-table
        debugId="pivot-column-inherit-example"
        [columns]="columns"
        [hideEmptyGroupColumns]="true"
        [pivotColumns]="ds.pivotColumns()"
        [pivotColumnGroups]="ds.pivotColumnGroups()"
        [columnDefaultWidth]="180"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly columnAggregations = columnAggregations;
  protected readonly columns = columns;
  protected readonly dataSource = dataSource;
  protected readonly groupBy = groupBy;
  protected readonly groupRowsState = groupRowsState;
  protected readonly pivotBy = pivotBy;
}
```

### aggregationReducers.pivotColumn (`Partial<InfiniteTableColumn<T>> | (({ column }) => Partial<InfiniteTableColumn<T>>)`)

> Configures the generated pivot columns for this aggregation only.

Has the same shape as a normal [column](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns) (or a function that returns one). Use it when you want a setting — [defaultSortable](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.defaultSortable), `header`, `defaultWidth`,`style` - to apply to columns generated for this reducer, and not to other aggregations.

Also supports [`aggregationReducers.pivotColumn.inheritFromColumn`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#aggregationReducers.pivotColumn.inheritFromColumn) to control which original column (if any) the generated columns inherit from.

```ts
const aggregationReducers: DataSourcePropAggregationReducers<Developer> = {
  salary: {
    field: 'salary',
    initialValue: 0,
    reducer: (acc, sum) => acc + sum,
    pivotColumn: {
      defaultSortable: true,
    },
  },
  license: {
    field: 'license',
    initialValue: 0,
    reducer: (acc) => acc + 1,
  },
};
```

In the example above, only the `salary` pivot columns are sortable. See [customizing pivot columns](https://infinite-table.com/angular/docs/learn/grouping-and-pivoting/pivoting/customizing-pivot-columns.md) for the other override points ([`pivotColumn`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#pivotColumn) and [`pivotBy.column`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#pivotBy.column)).

### aggregationReducers.pivotColumn.inheritFromColumn (`string | boolean`)

> Controls which original [column](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns) the generated pivot columns inherit from.

By default, pivot columns inherit the configuration of the initial column bound to the same `field` as the aggregation. `inheritFromColumn` lets you change that:

- a `string` — the id of another column to inherit from
- `false` — do not inherit from any column
- `true` or omitted — inherit from the column bound to the aggregator's `field` (the default)

```ts
const aggregationReducers = {
  avgSalary: { field: 'salary', ...avgReducer },
  avgAge: {
    field: 'age',
    ...avgReducer,
    pivotColumn: {
      inheritFromColumn: 'preferredLanguage',
      defaultWidth: 500,
    },
  },
};
```

**Example: Pivot columns inherit from original columns bound to the same field**

```ts
import { Component } from '@angular/core';

import {
  InfiniteTable,
  DataSource,
  GroupRowsState,
} from '@infinite-table/infinite-angular';
import type {
  DataSourcePropAggregationReducers,
  InfiniteTableColumnAggregator,
  InfiniteTablePropColumns,
  DataSourceGroupBy,
  DataSourcePivotBy,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers100')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const avgReducer: InfiniteTableColumnAggregator<Developer, any> = {
  initialValue: 0,
  reducer: (acc, sum) => acc + sum,
  done: (sum, arr) => (arr.length ? sum / arr.length : 0),
};

const columnAggregations: DataSourcePropAggregationReducers<Developer> = {
  avgSalary: {
    field: 'salary',
    name: 'Average salary',
    ...avgReducer,
  },
  avgAge: {
    field: 'age',
    ...avgReducer,
    pivotColumn: {
      defaultWidth: 500,
      inheritFromColumn: 'firstName',
    },
  },
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: { field: 'id' },
  firstName: {
    field: 'firstName',
    style: {
      fontWeight: 'bold',
    },
    renderValue: ({ value }) => [value, '!'],
  },
  preferredLanguage: { field: 'preferredLanguage' },
  stack: { field: 'stack' },
  country: { field: 'country' },
  canDesign: { field: 'canDesign' },
  hobby: { field: 'hobby' },

  city: { field: 'city' },
  age: { field: 'age' },
  salary: {
    field: 'salary',
    type: 'number',
    header: 'Salary',
    style: { color: 'red' },
  },
  currency: { field: 'currency' },
};

const groupRowsState = new GroupRowsState({
  expandedRows: [],
  collapsedRows: true,
});

const groupBy: DataSourceGroupBy<Developer>[] = [
  {
    field: 'preferredLanguage',
  },
  { field: 'stack' },
];

const pivotBy: DataSourcePivotBy<Developer>[] = [
  { field: 'country' },
  {
    field: 'canDesign',
  },
];

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      #ds="infiniteDataSource"
      primaryKey="id"
      [data]="dataSource"
      [groupBy]="groupBy"
      [pivotBy]="pivotBy"
      [aggregationReducers]="columnAggregations"
      [defaultGroupRowsState]="groupRowsState"
    >
      <infinite-table
        debugId="pivot-column-inherit-example"
        [columns]="columns"
        [hideEmptyGroupColumns]="true"
        [pivotColumns]="ds.pivotColumns()"
        [pivotColumnGroups]="ds.pivotColumnGroups()"
        [columnDefaultWidth]="180"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly columnAggregations = columnAggregations;
  protected readonly columns = columns;
  protected readonly dataSource = dataSource;
  protected readonly groupBy = groupBy;
  protected readonly groupRowsState = groupRowsState;
  protected readonly pivotBy = pivotBy;
}
```

### data (`DATA_TYPE[]|Promise<DATA_TYPE[]|(params:DataSourceDataParams) => DATA_TYPE[]|Promise<DATA_TYPE[]>`)

> Specifies the data the component is bound to.

Can be one of the following:

- an array of the bound type - eg: `Employee[]`
- a Promise tha resolves to an array like the above
- a function that returns an any of the above

If the `data` prop is a function, it will be called with an object of type [`DataSourceDataParams`](https://infinite-table.com/docs/reference/type-definitions/index.md#DataSourceDataParams). [Click to see more details.](https://infinite-table.com/docs/reference/type-definitions/index.md#DataSourceDataParams)

**Example: Data loading example with promise**

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type { InfiniteTablePropColumns } from '@infinite-table/infinite-angular';

type Employee = {
  id: string | number;
  name: string;
  salary: number;
  department: string;
  company: string;
};

const employees: Employee[] = [
  {
    id: 1,
    name: 'Bob',
    salary: 10_000,
    department: 'IT',
    company: 'Bobsons',
  },
  {
    id: 2,
    name: 'Alice',
    salary: 20_000,
    department: 'IT',
    company: 'Bobsons',
  },
  {
    id: 3,
    name: 'John',
    salary: 30_000,
    department: 'IT',
    company: 'Bobsons',
  },
  {
    id: 4,
    name: 'Jane',
    salary: 35_000,
    department: 'Marketing',
    company: 'Janies',
  },
  {
    id: 5,
    name: 'Mary',
    salary: 40_000,
    department: 'Marketing',
    company: 'Janies',
  },
];

// this can be an array, a promise or a function returning array/promise
const data = new Promise<Employee[]>((resolve) => {
  setTimeout(() => {
    resolve(employees);
  }, 100);
});

const columns: InfiniteTablePropColumns<Employee> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 80,
  },
  name: {
    field: 'name',
  },
  salary: { field: 'salary', type: 'number' },
  department: { field: 'department', header: 'Dep.' },
  company: { field: 'company' },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source [data]="data" primaryKey="id">
      <infinite-table
        debugId="data-example"
        [columnDefaultWidth]="130"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly columns = columns;
}
```

It's important to note you can re-fetch data by changing the reference you pass as the `data` prop to the `<DataSource/>` component. Passing another `data` function, will cause the component to re-execute the function and thus load new data.

**Example: Re-fetching data**

```ts
import { Component, computed, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';

import { columns } from './columns.angular';
import type { Employee } from './columns.angular';

const getDataSourceFor = (size: string) => {
  if (size === '0') {
    return () => Promise.resolve([]);
  }
  return () => {
    return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/employees' + size)
      .then((r) => r.json())
      .then((data: Employee[]) => data);
  };
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <div
      style="display: flex; flex: 1; flex-flow: column; color: var(--infinite-cell-color); background: var(--infinite-background)"
    >
      <p style="padding: 10px">Please select the size of the datasource:</p>
      <div style="padding: 10px">
        <select
          style="margin: 10px 0; display: inline-block; background: var(--infinite-background); color: currentColor; padding: var(--infinite-space-3)"
          [value]="dataSourceSize()"
          (change)="onSizeChange($event)"
        >
          <option value="0">no items</option>
          <option value="10">10 items</option>
          <option value="100">100 items</option>
          <option value="1k">1k items</option>
          <option value="10k">10k items</option>
        </select>
      </div>
      <infinite-data-source [data]="dataSource()" primaryKey="id">
        <infinite-table
          debugId="refetch-example"
          [columns]="columns"
          [columnDefaultWidth]="150"
        />
      </infinite-data-source>
    </div>
  `,
})
export default class App {
  protected readonly columns = columns;

  protected readonly dataSourceSize = signal('10');

  protected readonly dataSource = computed(() =>
    getDataSourceFor(this.dataSourceSize()),
  );

  protected onSizeChange(event: Event) {
    this.dataSourceSize.set((event.target as HTMLSelectElement).value);
  }
}
```

### defaultFilterValue (`{field?, id?, filter: {type, operator, value}[]`)

> Uncontrolled prop used for filtering. Can be used for both [client-side](https://infinite-table.com/angular/docs/learn/filtering/filtering-client-side.md) and [server-side](https://infinite-table.com/angular/docs/learn/filtering/filtering-server-side.md) filtering.

If you want to show the column filter editors, you have to either specify this property, or the controlled [`[(filterValue)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterValue) - even if you have no initial filters. For no initial filters, use `defaultFilterValue=[]`.

For the controlled version, and more details on the shape of the objects in the array, see [`[(filterValue)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterValue).

**Example: Initial filtering applied via defaultFilterValue**

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  DataSourceProps,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;

  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';

  salary: number;
};

const data: DataSourceData<Developer> = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql?`)
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 100,
  },
  salary: {
    defaultFilterable: true,
    field: 'salary',
    type: 'number',
  },

  firstName: {
    field: 'firstName',
  },
  stack: { field: 'stack' },
  currency: { field: 'currency' },
};

const domProps = {
  style: {
    height: '100%',
  },
};

const defaultFilterValue: DataSourceProps<Developer>['filterValue'] = [
  {
    field: 'salary',
    filter: {
      operator: 'gt',
      value: 50000,
      type: 'number',
    },
  },
];

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <p style="color: var(--infinite-cell-color)">
      By default, only showing records with salary &gt; 50000
    </p>
    <infinite-data-source
      [data]="data"
      primaryKey="id"
      [defaultFilterValue]="defaultFilterValue"
      [filterDelay]="0"
    >
      <infinite-table
        debugId="defaultFilterValue-example"
        [domProps]="domProps"
        [columnDefaultWidth]="150"
        [columnMinWidth]="50"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly domProps = domProps;
  protected readonly columns = columns;
  protected readonly defaultFilterValue = defaultFilterValue;
}
```

You can control the visibility of the column filters by using the [`showColumnFilters`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#showColumnFilters) prop.

### defaultRowSelection (`string|number|null|object`)

> Describes the selected row(s) in the `DataSource`

See more docs in the controlled version of this prop, [`rowSelection`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowSelection)

For single selection, the prop will be of type: `number | string | null`. Use `null` for empty selection in single selection mode.

For multiple selection, the prop will have the following shape:

```ts
rowSelection = {
  selectedRows: [3, 6, 100, 23], // those specific rows are selected
  defaultSelection: false, // all rows deselected by default
};

// or
rowSelection = {
  deselectedRows: [3, 6, 100, 23], // those specific rows are deselected
  defaultSelection: true, // all other rows are selected
};

// or, for grouped data - this example assumes groupBy=continent,country,city
rowSelection = {
  selectedRows: [
    45, // row with id 45 is selected, no matter the group
    ['Europe', 'France'], // all rows in Europe/France are selected
    ['Asia'], // all rows in Asia are selected
  ],
  deselectedRows: [
    ['Europe', 'France', 'Paris'], // all rows in Paris are deselected
  ],
  defaultSelection: false, // all other rows are selected
};
```

For using group keys in the selection value, see related [`useGroupKeysForMultiRowSelection`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#useGroupKeysForMultiRowSelection)

**Example: Uncontrolled, multiple row selection with checkbox column**

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropRowSelection,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  email: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
    renderSelectionCheckBox: true,
  },
  firstName: {
    field: 'firstName',
  },
  stack: {
    field: 'stack',
  },
  age: { field: 'age' },
  id: { field: 'id' },
  salary: {
    field: 'salary',
    type: 'number',
  },
  canDesign: { field: 'canDesign' },
};

const defaultRowSelection: DataSourcePropRowSelection = {
  selectedRows: [3, 5],
  defaultSelection: false,
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers100')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="dataSource"
      [defaultRowSelection]="defaultRowSelection"
      primaryKey="id"
    >
      <infinite-table
        debugId="uncontrolled-multiple-row-selection-example"
        [columns]="columns"
        [columnDefaultWidth]="150"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly defaultRowSelection = defaultRowSelection;
}
```

### defaultSortInfo (`DataSourceSingleSortInfo<T>|DataSourceSingleSortInfo<T>[]|null`)

> Information for sorting the data. This is an uncontrolled prop.

For detailed explanations, see [`[(sortInfo)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortInfo) (controlled property).

When you provide a `defaultSortInfo` prop and the sorting information uses a custom [sortType](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortTypes), make sure you specify that as the `type` property of the sorting info object.

```ts
// <infinite-data-source [defaultSortInfo]="defaultSortInfo" />
protected readonly defaultSortInfo: DataSourceSingleSortInfo<Developer> = {
  field: 'color',
  dir: 1,
  // note this custom sort type
  type: 'color',
};
```

You will need to have a property for that type in your [`sortTypes`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortTypes) object as well.

```ts
// <infinite-data-source [sortTypes]="sortTypes" />
protected readonly sortTypes: DataSourcePropSortTypes = {
  color: (a, b) => colorOrder.indexOf(a) - colorOrder.indexOf(b),
};
```

**Example: Local uncontrolled single sorting**

```ts
import { Component } from '@angular/core';

import { InfiniteTable, DataSource } from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const dataSource: DataSourceData<Developer> = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers100-sql?`)
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  preferredLanguage: { field: 'preferredLanguage' },
  salary: {
    field: 'salary',
    type: 'number',
  },
  age: { field: 'age' },

  canDesign: { field: 'canDesign' },
  country: { field: 'country' },
  firstName: { field: 'firstName' },
  stack: { field: 'stack' },
  id: { field: 'id' },
  hobby: { field: 'hobby' },
  city: { field: 'city' },
  currency: { field: 'currency' },
};
const shouldReloadData = {
  sortInfo: false,
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      primaryKey="id"
      [data]="dataSource"
      [defaultSortInfo]="{ field: 'salary', dir: -1 }"
      [shouldReloadData]="shouldReloadData"
    >
      <infinite-table
        debugId="local-uncontrolled-single-sorting-example-with-remote-data"
        [columns]="columns"
        [columnDefaultWidth]="220"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly shouldReloadData = shouldReloadData;
  protected readonly columns = columns;
}
```

**Example: Custom sort by color - magenta will come first**

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type { InfiniteTableColumn } from '@infinite-table/infinite-angular';

type CarSale = {
  id: number;

  make: string;
  model: string;
  year: number;

  sales: number;
  color: string;
};

const carsales: CarSale[] = [
  {
    make: 'Volkswagen',
    model: 'GTI',
    year: 2009,
    sales: 6,
    color: 'red',
    id: 0,
  },
  {
    make: 'Honda',
    model: 'Element 2WD',
    year: 2009,
    sales: 739,
    color: 'red',
    id: 1,
  },
  {
    make: 'Acura',
    model: 'RDX 4WD',
    year: 2008,
    sales: 2,
    color: 'magenta',
    id: 2,
  },
  {
    make: 'Honda',
    model: 'Fit',
    year: 2009,
    sales: 211,
    color: 'blue',
    id: 3,
  },
  {
    make: 'Mazda',
    model: '6',
    year: 2009,
    sales: 31,
    color: 'blue',

    id: 4,
  },
  {
    make: 'Acura',
    model: 'TSX',
    year: 2009,
    sales: 14,
    color: 'yellow',
    id: 5,
  },
  {
    make: 'Acura',
    model: 'TSX',
    year: 2010,
    sales: 14,
    color: 'red',
    id: 6,
  },
  {
    make: 'Audi',
    model: 'A3',
    year: 2009,
    sales: 2,
    color: 'magenta',
    id: 7,
  },
];

const columns: Record<string, InfiniteTableColumn<CarSale>> = {
  color: { field: 'color', sortType: 'color' },
  make: { field: 'make' },
  model: { field: 'model' },

  sales: {
    field: 'sales',
    sortType: 'number',
  },
  year: {
    field: 'year',
    sortType: 'number',
  },
};
const newSortTypes = {
  color: (one: string, two: string) => {
    if (one === 'magenta') {
      // magenta comes first
      return -1;
    }
    if (two === 'magenta') {
      // magenta comes first
      return 1;
    }
    return one.localeCompare(two);
  },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="carsales"
      primaryKey="id"
      [defaultSortInfo]="{
        field: 'color',
        dir: 1,
        type: 'color',
      }"
      [sortTypes]="newSortTypes"
    >
      <infinite-table
        debugId="customSortType-with-uncontrolled-sortInfo-example"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly carsales = carsales;
  protected readonly columns = columns;
  protected readonly newSortTypes = newSortTypes;
}
```

### filterDelay (`number`)

> The delay in milliseconds before the filter is applied. This is useful when you want to wait for the user to finish typing before applying the filter.

This is especially useful in order to reduce the number of requests sent to the server, when [remote filtering](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#shouldReloadData.filterValue) is used.

If not specified, defaults to `200` milliseconds. This means, any changes to the column filters, that happen inside a 200ms window (or the current value of [`filterDelay`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterDelay)), will be debounced and only the last value will be sent to the server.

If you want to prevent debouncing/batching filter values, you can set [`filterDelay`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterDelay) to `0`.

### batchOperationDelay (`number`)

> The delay in milliseconds to wait before mutations are applied. This is useful to batch multiple mutations together.

If not specified, a `requestAnimationFrame` will be used to batch mutations.

The following mutative operations are batched:
 
 - [`addData`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#addData)
 - [`addDataArray`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#addDataArray)
 - [`insertData`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#insertData)
 - [`insertDataArray`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#insertDataArray)
 - [`updateData`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#updateData)
 - [`updateDataArray`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#updateDataArray)
 - [`removeData`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#removeData)
 - [`removeDataArray`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#removeDataArray)
 - [`removeDataByPrimaryKey`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#removeDataByPrimaryKey)
 - [`removeDataArrayByPrimaryKeys`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#removeDataArrayByPrimaryKeys)
 - [`replaceAllData`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#replaceAllData)
 - [`clearAllData`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#clearAllData)

### treeFilterFunction (`({ data, isLeafNode, filterTreeNode, filterValue, filterTypes, primaryKey }) => DATA_TYPE | boolean`)

> A function to be used for filtering a `TreeDataSource` in the browser. It replaces the built-in column filtering.

The function is called for the nodes of the top level, and should return a boolean value or a data object.

- when returning `false` the current data object will be filtered out.
- when returning `true`, the current data object will be included in the filtered data, with no changes.
- when returning a data object, the object will be used instead of the current data object for the row. This means that you can modify the data object to only include some of its children (which match a specific criteria)

The param also has:

- `isLeafNode` - whether the current node is a leaf node.
- `filterValue` and `filterTypes` - the current column filters (see [`[(filterValue)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterValue)), so you can apply them with `defaultFilterFunction`.

The `treeFilterFunction` is called with an object that has a `filterTreeNode` function property. This function is a helper function you can use to continue the filtering further down the tree on the current (non-leaf) node.

This function will call the filtering function for each child of the current node. If all the children are filtered out, the current node will be filtered out as well. If there are any children that match the criteria, a clone of the current node will be returned with only the matching children.

You can opt to not use this helper function, and instead implement your own filtering logic. In this case, make sure you don't mutate data objects but rather return cloned versions of them.

When there is no `treeFilterFunction`, the column filters are applied with `defaultTreeFilterFunction`, which you can also import and call from your own function:

```ts
import {
  defaultFilterFunction,
  defaultTreeFilterFunction,
} from '@infinite-table/infinite-angular';

// the built-in tree filtering: leaf nodes are matched against the column filters,
// a parent node is kept when at least one of its descendants is kept
// <infinite-tree-data-source [treeFilterFunction]="defaultTreeFilterFunction" />

// also keep the parent nodes that match the column filters themselves
const treeFilterFunction: DataSourcePropTreeFilterFunction<FileSystemNode> = (
  param,
) =>
  param.isLeafNode
    ? defaultFilterFunction(param)
    : defaultFilterFunction(param) || param.filterTreeNode(param.data);
// <infinite-tree-data-source [treeFilterFunction]="treeFilterFunction" />
```

`defaultTreeFilterFunction` matches only the leaf nodes against the column filters - the fields of a parent node are not matched.

A `treeFilterFunction` has no effect with [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad).

**Example: Tree filtering via treeFilterFunction**

```ts
import { Component, computed, signal } from '@angular/core';

import { TreeDataSource, TreeGrid } from '@infinite-table/infinite-angular';
import type { InfiniteTableColumn } from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  extension?: string;
  mimeType?: string;
  sizeInKB: number;
  children?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: { field: 'name', header: 'Name', renderTreeIcon: true },
  type: { field: 'type', header: 'Type' },
  extension: { field: 'extension', header: 'Extension' },
  mimeType: { field: 'mimeType', header: 'Mime Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};

const dataSource = () => {
  const nodes: FileSystemNode[] = [
    {
      id: '1',
      name: 'Documents',
      sizeInKB: 1200,
      type: 'folder',
      children: [
        {
          id: '10',
          name: 'Private',
          sizeInKB: 100,
          type: 'folder',
          children: [
            {
              id: '100',
              name: 'Report.docx',
              sizeInKB: 210,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '101',
              name: 'Vacation.docx',
              sizeInKB: 120,
              type: 'file',
              extension: 'docx',
              mimeType: 'application/msword',
            },
            {
              id: '102',
              name: 'CV John Doe.pdf',
              sizeInKB: 108,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
            {
              id: '103',
              name: 'resume mary.pptx',
              sizeInKB: 210,
              type: 'file',
              extension: 'pptx',
              mimeType: 'application/presentation',
            },
            {
              id: '104',
              name: 'resume bob.pdf',
              sizeInKB: 1210,
              type: 'file',
              extension: 'pdf',
              mimeType: 'application/pdf',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: 'Desktop',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '20',
          name: 'unknown.txt',
          sizeInKB: 100,
          type: 'file',
        },
        {
          id: '21',
          name: 'resume.docx',
          sizeInKB: 210,
          type: 'file',
          extension: 'docx',
          mimeType: 'application/msword',
        },
      ],
    },
    {
      id: '3',
      name: 'Media',
      sizeInKB: 1000,
      type: 'folder',
      children: [
        {
          id: '31',
          name: 'Videos',
          sizeInKB: 5400,
          type: 'folder',
          children: [
            {
              id: '310',
              name: 'Vacation.mp4',
              sizeInKB: 108,
              type: 'file',
              extension: 'mp4',
              mimeType: 'video/mp4',
            },
          ],
        },
      ],
    },
  ];
  return Promise.resolve(nodes);
};

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid],
  template: `
    <infinite-tree-data-source
      nodesKey="children"
      primaryKey="id"
      [data]="dataSource"
      [treeFilterFunction]="filterFunction()"
    >
      <div style="color: var(--infinite-cell-color); padding: 10px">
        <input
          type="text"
          name="filter"
          style="padding: 10px; border: 1px solid black; border-radius: 5px; min-width: 250px"
          placeholder="Type to filter by name"
          [value]="filter()"
          (input)="onFilterChange($event)"
        />
      </div>

      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;

  protected readonly filter = signal('');

  
  protected readonly filterFunction = computed(() => {
    const filter = this.filter();

    return ({
      data,
      filterTreeNode,
    }: {
      data: FileSystemNode;
      filterTreeNode: (data: FileSystemNode) => FileSystemNode | boolean;
    }) => {
      if (!Array.isArray(data.children)) {
        return data.name.toLowerCase().includes(filter.toLowerCase());
      }

      return filterTreeNode(data);
    };
  });

  protected onFilterChange(event: Event) {
    this.filter.set((event.target as HTMLInputElement).value);
  }
}
```

### filterFunction (`({ data, dataArray, index, primaryKey, filterValue, filterTypes }) => boolean`)

> A function to be used for filtering in the browser - you decide how the rows are filtered.

The function is called for every row, and returns whether the row is kept. Its param also has the current column filters ([`[(filterValue)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterValue), as `filterValue` and `filterTypes`), so the function can filter in any way you want:

- call `defaultFilterFunction`, which Infinite Table exports, to filter by the column filters the same way the built-in filtering does;
- use your own logic;
- or combine the two.

```ts
import { defaultFilterFunction } from '@infinite-table/infinite-angular';

// the built-in column filtering
// <infinite-data-source [filterFunction]="defaultFilterFunction" />

// your own logic only
const olderThan30: DataSourcePropFilterFunction<Developer> = (param) =>
  param.data.age > 30;
// <infinite-data-source [filterFunction]="olderThan30" />

// the column filters, and your own condition
const filteredAndOlderThan30: DataSourcePropFilterFunction<Developer> = (
  param,
) => defaultFilterFunction(param) && param.data.age > 30;
// <infinite-data-source [filterFunction]="filteredAndOlderThan30" />
```

A `filterFunction` makes the filtering happen in the browser. Combine it with [shouldReloadData.filterValue: true](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#shouldReloadData.filterValue) when the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function should also be called again on every filter change - the returned rows are then filtered in the browser.

A `filterFunction` has no effect with [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad): the rows that are not loaded yet can't be filtered in the browser.

For filtering when using a `TreeGrid`, see [`treeFilterFunction`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#treeFilterFunction). When both are specified for tree data, only the `treeFilterFunction` is used.

Loads data from remote location but will only show rows that have `id > 100`.

**Example: Custom filterFunction example**

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  DataSourcePropFilterFunction,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;

  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';

  salary: number;
};

const data: DataSourceData<Developer> = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql?`)
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 100,
  },
  salary: {
    defaultFilterable: true,
    field: 'salary',
    type: 'number',
    filterType: 'salary',
  },

  firstName: {
    field: 'firstName',
  },
  stack: { field: 'stack' },
  currency: { field: 'currency', defaultFilterable: false },
};

const filterFunction: DataSourcePropFilterFunction<Developer> = ({ data }) => {
  return data.id > 100;
};

const domProps = {
  style: {
    height: '100%',
  },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source [data]="data" primaryKey="id" [filterFunction]="filterFunction">
      <infinite-table
        debugId="custom-filter-function-example"
        [domProps]="domProps"
        [columnDefaultWidth]="150"
        [columnMinWidth]="50"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly filterFunction = filterFunction;
  protected readonly domProps = domProps;
  protected readonly columns = columns;
}
```

### shouldReloadData.filterValue (`boolean`)

> Specifies if changes in the [`[(filterValue)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterValue) should trigger a reload of the data source - and so, that the data is filtered by whoever provides it.

- `false` - filtering is done in the browser and the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function is not called again. This is the default - for both controlled and uncontrolled filtering - unless [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad) or [`livePagination`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePagination) is used.
- `true` - the data is filtered by whoever provides it. When [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) is a function, it's called again on every filter change, with the `filterValue` in its params, so it can be sent to the server. When [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) is an array, you pass a new, filtered array (eg from [`(filterValueChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onFilterValueChange)). The rows are shown as they come in - unless a [`filterFunction`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterFunction) is specified, in which case they are filtered again in the browser. This is the default with [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad) and [`livePagination`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePagination).

See [Sorting and filtering the data yourself](https://infinite-table.com/angular/docs/learn/working-with-data/sorting-and-filtering-the-data-yourself.md).

### filterTypes (`Record<string,{operators,emptyValues, defaultOperator}>`)

> Specifies the available types of filters for the columns.

A filter type is a concept that defines how a certain type of data is to be filtered.
A filter type will have a key, used to define the filter in the `filterTypes` object, and also the following properties:

- `label`
- `emptyValues` - an array of values considered to be empty values - when any of these values is used in the filter, the filter will match all records.
- `operators` - an array of operator this filter type supports
- `defaultOperator` - the default operator for the filter type
- `components` - an object that describes the custom components to be used for the filter type
  - `FilterEditor` - a custom filter editor component for this filter type
  - `FilterOperatorSwitch` - a custom component that is displayed at the left of the `FilterEditor` and can be used for switching between operators - only needed for very very advanced use-cases.

Let's imagine you have a `DataSource` with developers, each with a `salary` column, and for that column you want to allow `>`, `>=`, `<` and `<=` comparisons (operators).

For this, you would define the following filter type:

```tsx
const filterTypes: DataSourcePropFilterTypes<Developer> = {
  income: {
    label: 'Income',
    emptyValues: ['', null, undefined],
    defaultOperator: 'gt',
    operators: [
      {
        name: 'gt',
        label: 'Greater than',
        fn: ({ currentValue, filterValue }) => {
          return currentValue > filterValue;
        },
      },
      {
        name: 'gte',
        fn: ({ currentValue, filterValue }) => currentValue >= filterValue,
        //...
      },
      {
        name: 'lt',
        fn: ({ currentValue, filterValue }) => currentValue < filterValue,
        //...
      },
      {
        name: 'lte',
        fn: ({ currentValue, filterValue }) => currentValue <= filterValue,
        //...
      },
    ],
  },
};
```

Each operator for a certain filter type needs to at least have a `name` and `fn` defined. The `fn` property is a function that will be called when client-side filtering is enabled, with an object that has the following properties:

- `currentValue` - the cell value of the current row for the column being filtered
- `filterValue` - the value of the filter editor
- `emptyValues` - the array of values considered to be empty values for the filter type
- `data` - the current row data object - `typeof DATA_TYPE`
- `index` - the index of the current row in the table - `number`
- `dataArray` - the array of all rows originally in the table - `typeof DATA_TYPE[]`
- `field?` - the field the current column is bound to (can be undefined if the column is not bound to a field)

The `salary` column has a custom filter type, with the following operators: `gt`, `gte`, `lt` and `lte`.

**Example: Custom filter type used for the salary column**

```ts
import { Component, input } from '@angular/core';

import {
  DataSource,
  InfiniteTable,
  renderComponent,
} from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  DataSourcePropFilterTypes,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;

  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';

  salary: number;
};

const data: DataSourceData<Developer> = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql?`)
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 100,
  },
  salary: {
    defaultFilterable: true,
    field: 'salary',
    type: 'number',
    filterType: 'salary',
  },

  firstName: {
    field: 'firstName',
  },
  stack: { field: 'stack' },
  currency: { field: 'currency', defaultFilterable: false },
};

@Component({
  selector: 'operator-icon',
  host: {
    style:
      'width: 20px; display: flex; justify-content: center; flex-flow: row',
  },
  template: `{{ icon() }}`,
})
class OperatorIcon {
  readonly icon = input.required<string>();
}

function getIcon(icon: string) {
  return () => renderComponent(OperatorIcon, { inputs: { icon } });
}

const filterTypes: DataSourcePropFilterTypes<Developer> = {
  salary: {
    defaultOperator: 'gt',
    emptyValues: ['', null, undefined],
    operators: [
      {
        name: 'gt',
        label: 'Greater Than',
        components: {
          Icon: getIcon('>'),
        },
        fn: ({ currentValue, filterValue }) => {
          return currentValue > filterValue;
        },
      },
      {
        name: 'gte',
        components: {
          Icon: getIcon('>='),
        },
        label: 'Greater Than or Equal',
        fn: ({ currentValue, filterValue }) => {
          return currentValue >= filterValue;
        },
      },
      {
        name: 'lt',
        components: {
          Icon: getIcon('<'),
        },
        label: 'Less Than',
        fn: ({ currentValue, filterValue }) => {
          return currentValue < filterValue;
        },
      },
      {
        name: 'lte',
        components: {
          Icon: getIcon('<='),
        },
        label: 'Less Than or Equal',
        fn: ({ currentValue, filterValue }) => {
          return currentValue <= filterValue;
        },
      },
    ],
  },
};

const domProps = {
  style: {
    height: '100%',
  },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="data"
      primaryKey="id"
      [defaultFilterValue]="[]"
      [filterDelay]="0"
      [filterTypes]="filterTypes"
    >
      <infinite-table
        debugId="filter-types-example"
        [domProps]="domProps"
        [columnDefaultWidth]="150"
        [columnMinWidth]="50"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly filterTypes = filterTypes;
  protected readonly domProps = domProps;
  protected readonly columns = columns;
}
```

By default, the `string` and `number` filter types are available. You can import the default filter types like this:

```ts
import { defaultFilterTypes } from '@infinite-table/infinite-angular';
```

If you want to make all your instances of `InfiniteTable` have new operators for those filter types, you can simply mutate the exported `defaultFilterTypes` object.

The `string` columns have a new `Not includes` operator.

**Example: Enhanced string filter type - new 'Not includes' operator**

```ts
import { Component } from '@angular/core';

import {
  InfiniteTable,
  DataSource,
  defaultFilterTypes,
} from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;

  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';

  salary: number;
};

defaultFilterTypes.string.operators.push({
  name: 'Not includes',
  label: 'Not Includes',
  fn: ({ currentValue, filterValue }) => {
    return (
      typeof currentValue === 'string' &&
      typeof filterValue == 'string' &&
      !currentValue.toLowerCase().includes(filterValue.toLowerCase())
    );
  },
});

const data: DataSourceData<Developer> = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql?`)
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 100,
  },
  salary: {
    field: 'salary',
    type: 'number',
  },

  firstName: {
    field: 'firstName',
  },
  stack: { field: 'stack' },
  currency: { field: 'currency', defaultFilterable: false },
};

const domProps = {
  style: {
    height: '100%',
  },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="data"
      primaryKey="id"
      [defaultFilterValue]="[]"
      [filterDelay]="0"
    >
      <infinite-table
        debugId="default-filter-types-example"
        [domProps]="domProps"
        [columnDefaultWidth]="150"
        [columnMinWidth]="50"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly domProps = domProps;
  protected readonly columns = columns;
}
```

When you specify new [`filterTypes`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterTypes), the default filter types of `string` and `number` are still available - unless the new object contains those keys and overrides them explicitly.

The current implementation of the default filter types is the following:

```ts
export const defaultFilterTypes: Record<string, DataSourceFilterType<T>> = {
  string: {
    label: 'Text',
    emptyValues: [''],
    defaultOperator: 'includes',
    components: {
      FilterEditor: () => renderComponent(StringFilterEditor),
    },
    operators: [
      {
        name: 'includes',
        components: {
          // custom icon as an Angular component ...
          Icon: () => renderComponent(IncludesOperatorIcon),
        },
        label: 'includes',
        fn: ({ currentValue, filterValue }) => {
          return (
            typeof currentValue === 'string' &&
            typeof filterValue == 'string' &&
            currentValue.toLowerCase().includes(filterValue.toLowerCase())
          );
        },
      },
      {
        label: 'Equals',
        components: {
          // custom icon as an Angular component ...
          Icon: () => renderComponent(EqualOperatorIcon),
        },
        name: 'eq',
        fn: ({ currentValue: value, filterValue }) => {
          return typeof value === 'string' && value === filterValue;
        },
      },
      {
        name: 'startsWith',
        components: {
          // custom icon as an Angular component ...
          Icon: () => renderComponent(StartsWithOperatorIcon),
        },
        label: 'Starts With',
        fn: ({ currentValue: value, filterValue }) => {
          return value.startsWith(filterValue);
        },
      },
      {
        name: 'endsWith',
        components: {
          // custom icon as an Angular component ...
          Icon: () => renderComponent(EndsWithOperatorIcon),
        },
        label: 'Ends With',
        fn: ({ currentValue: value, filterValue }) => {
          return value.endsWith(filterValue);
        },
      },
    ],
  },
  number: {
    label: 'Number',
    emptyValues: ['', null, undefined],
    defaultOperator: 'eq',
    components: {
      FilterEditor: () => renderComponent(NumberFilterEditor),
    },
    operators: [
      {
        label: 'Equals',
        components: {
          // custom icon as an Angular component ...
          Icon: () => renderComponent(EqualOperatorIcon),
        },
        name: 'eq',
        fn: ({ currentValue, filterValue }) => {
          return currentValue == filterValue;
        },
      },
      {
        label: 'Not Equals',
        components: {
          // custom icon as an Angular component ...
          Icon: () => renderComponent(NotEqualOperatorIcon),
        },
        name: 'neq',
        fn: ({ currentValue, filterValue }) => {
          return currentValue != filterValue;
        },
      },
      {
        name: 'gt',
        label: 'Greater Than',
        components: {
          // custom icon as an Angular component ...
          Icon: () => renderComponent(GTOperatorIcon),
        },
        fn: ({ currentValue, filterValue, emptyValues }) => {
          if (emptyValues.includes(currentValue)) {
            return true;
          }
          return currentValue > filterValue;
        },
      },
      {
        name: 'gte',
        components: {
          // custom icon as an Angular component ...
          Icon: () => renderComponent(GTEOperatorIcon),
        },
        label: 'Greater Than or Equal',
        fn: ({ currentValue, filterValue, emptyValues }) => {
          if (emptyValues.includes(currentValue)) {
            return true;
          }
          return currentValue >= filterValue;
        },
      },
      {
        name: 'lt',
        components: {
          // custom icon as an Angular component ...
          Icon: () => renderComponent(LTOperatorIcon),
        },
        label: 'Less Than',
        fn: ({ currentValue, filterValue, emptyValues }) => {
          if (emptyValues.includes(currentValue)) {
            return true;
          }
          return currentValue < filterValue;
        },
      },
      {
        name: 'lte',
        components: {
          // custom icon as an Angular component ...
          Icon: () => renderComponent(LTEOperatorIcon),
        },
        label: 'Less Than or Equal',
        fn: ({ currentValue, filterValue, emptyValues }) => {
          if (emptyValues.includes(currentValue)) {
            return true;
          }
          return currentValue <= filterValue;
        },
      },
    ],
  },
};
```

### filterTypes.components.FilterEditor

> A custom React component to be used as an editor for the current filter type

Every filter type can define the following `components`

- `FilterEditor` - a React component to be used as an editor for the current filter type
- `FilterOperatorSwitch` - a custom component that is displayed at the left of the `FilterEditor` and can be used for switching between operators - only needed for very very advanced use-cases.

Filter type operators can override the `FilterEditor` component - they can specify the following components:

- `FilterEditor` - if specified, it overrides the `FilterEditor` of the filter type
- `Icon` - a React component to be used as an icon for the operator - displayed by the menu triggered when clicking on the `FilterOperatorSwitch` component

The `canDesign` column is using a custom `bool` filter type with a custom filter editor.

The checkbox has indeterminate state, which will match all values in the data source.

**Example: Demo of a custom filter editor**

```ts
import { Component } from '@angular/core';

import {
  DataSource,
  InfiniteCheckBox,
  InfiniteTable,
  injectColumnFilterEditor,
  renderComponent,
} from '@infinite-table/infinite-angular';
import type {
  DataSourcePropFilterTypes,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  canDesign: boolean;
  stack: string;
  hobby: string;
};
const dataSource: Developer[] = [
  {
    id: 1,
    firstName: 'John',

    canDesign: true,
    stack: 'frontend',
    hobby: 'gaming',
  },
  {
    id: 2,
    firstName: 'Jane',

    canDesign: false,
    stack: 'backend',
    hobby: 'reading',
  },
  {
    id: 3,
    firstName: 'Jack',

    canDesign: true,
    stack: 'frontend',
    hobby: 'gaming',
  },
  {
    id: 4,
    firstName: 'Jill',

    canDesign: false,
    stack: 'backend',
    hobby: 'reading',
  },
  {
    id: 5,
    firstName: 'Seb',

    canDesign: false,
    stack: 'backend',
    hobby: 'reading',
  },
];

const columns: InfiniteTablePropColumns<Developer> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 100,
  },
  canDesign: {
    field: 'canDesign',
    filterType: 'bool',
    renderValue: ({ value }) => (value ? 'Yes' : 'No'),
  },
  firstName: {
    field: 'firstName',
  },
  stack: { field: 'stack' },
};

const domProps = {
  style: {
    height: '100%',
  },
};

@Component({
  selector: 'div[boolFilterEditor]',
  imports: [InfiniteCheckBox],
  host: {
    '[class]': 'editor.className',
    style: 'text-align: center',
  },
  template: `
    <input
      infiniteCheckBox
      [checked]="editor.value()"
      (checkedChange)="onChange($event)"
    />
  `,
})
class BoolFilterEditor {
  protected readonly editor = injectColumnFilterEditor<Developer>();

  protected onChange(newValue: boolean | null) {
    const value = this.editor.value();
    if (value === true) {
      // after the value was true, make it go to indeterminate state
      newValue = null;
    }
    if (value === null) {
      // from indeterminate, goto false
      newValue = false;
    }
    this.editor.setValue(newValue);
  }
}

const filterTypes: DataSourcePropFilterTypes<Developer> = {
  bool: {
    defaultOperator: 'eq',
    emptyValues: [null],
    components: {
      FilterEditor: () => renderComponent(BoolFilterEditor),
      FilterOperatorSwitch: () => null,
    },
    operators: [
      {
        name: 'eq',
        label: 'Equals',
        fn: ({ currentValue, filterValue }) => currentValue === filterValue,
      },
    ],
  },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [defaultFilterValue]="[]"
      [filterDelay]="0"
      [filterTypes]="filterTypes"
    >
      <infinite-table
        debugId="custom-filter-editor-hooks-example"
        [domProps]="domProps"
        [columnDefaultWidth]="150"
        [columnMinWidth]="50"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly filterTypes = filterTypes;
  protected readonly domProps = domProps;
  protected readonly columns = columns;
}
```

### filterValue (`{field?, id?, filter: {type, operator, value}[]`)

> Controlled prop used for filtering. Can be used for both [client-side](https://infinite-table.com/angular/docs/learn/filtering/filtering-client-side.md) and [server-side](https://infinite-table.com/angular/docs/learn/filtering/filtering-server-side.md) filtering.

For the uncontrolled version, see [`defaultFilterValue`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultFilterValue)

If you want to show the column filter editors, you have to either specify this property, or the uncontrolled [`defaultFilterValue`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultFilterValue) - even if you have no initial filters. For no initial filters, use `filterValue=[]`.

The objects in this array have the following shape:

- `filter` - an object describing the filter
  - `filter.value` - the value to filter by
  - `filter.type` - the current type of the filter (eg: `string`, `number` or another custom type you specify in the [filterTypes](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterTypes) prop)
  - `filter.operator` - the name of the operator being applied
- `field` - the field being filtered - generally matched with a column. This is optional, as some columns can have no field.
- `id` - the id of the column being filtered. This is optional - for columns bound to a field, the `field` should be used instead of the `id`.
- `disabled` - whether this filter is applied or not

**Example: Controlled filters with onFilterValueChange**

```ts
import { Component, signal } from '@angular/core';
import { JsonPipe } from '@angular/common';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  DataSourceProps,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;

  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';

  salary: number;
};

const data: DataSourceData<Developer> = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql?`)
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 100,
  },
  salary: {
    defaultFilterable: true,
    field: 'salary',
    type: 'number',
  },

  firstName: {
    field: 'firstName',
  },
  stack: { field: 'stack' },
  currency: { field: 'currency' },
};

const domProps = {
  style: {
    height: '100%',
  },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable, JsonPipe],
  template: `
    <div style="color: var(--infinite-cell-color)">
      Current filters:
      <pre><code>{{ filterValue() | json }}</code></pre>
    </div>
    <infinite-data-source
      [data]="data"
      primaryKey="id"
      [(filterValue)]="filterValue"
      [filterDelay]="0"
    >
      <infinite-table
        debugId="onFilterValueChange-example"
        [domProps]="domProps"
        [columnDefaultWidth]="150"
        [columnMinWidth]="50"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly domProps = domProps;
  protected readonly columns = columns;

  
  protected readonly filterValue = signal<
    DataSourceProps<Developer>['filterValue']
  >([
    {
      field: 'salary',
      filter: {
        operator: 'gt',
        value: 50000,
        type: 'number',
      },
    },
  ]);
}
```

You can control the visibility of the column filters by using the [`showColumnFilters`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#showColumnFilters) prop.

### lazyLoad (`boolean|{batchSize:number}`)

> Whether the datasource will load data lazily - useful for server-side grouping and pivoting. If set to `true` or to an object (with `batchSize` property), the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) prop must be a function that returns a promise.

**Example: Server-side pivoting with full lazy load**

```ts
import { Component } from '@angular/core';

import {
  InfiniteTable,
  DataSource,
  GroupRowsState,
} from '@infinite-table/infinite-angular';
import type {
  InfiniteTablePropColumns,
  InfiniteTablePropColumnPinning,
  DataSourceData,
  DataSourcePropAggregationReducers,
  DataSourceGroupBy,
  DataSourcePivotBy,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const DATA_SOURCE_SIZE = '10k';

const dataSource: DataSourceData<Developer> = ({
  pivotBy,
  aggregationReducers,
  groupBy,

  groupKeys = [],
}) => {
  const args = [
    pivotBy
      ? 'pivotBy=' + JSON.stringify(pivotBy.map((p) => ({ field: p.field })))
      : null,
    `groupKeys=${JSON.stringify(groupKeys)}`,
    groupBy
      ? 'groupBy=' + JSON.stringify(groupBy.map((p) => ({ field: p.field })))
      : null,
    aggregationReducers
      ? 'reducers=' +
        JSON.stringify(
          Object.keys(aggregationReducers).map((key) => ({
            field: aggregationReducers[key].field,
            id: key,
            name: aggregationReducers[key].reducer,
          })),
        )
      : null,
  ]
    .filter(Boolean)
    .join('&');
  return fetch(
    process.env.NEXT_PUBLIC_BASE_URL +
      `/developers${DATA_SOURCE_SIZE}-sql?` +
      args,
  )
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const aggregationReducers: DataSourcePropAggregationReducers<Developer> = {
  salary: {
    // the aggregation name will be used as the column header
    name: 'Salary (avg)',
    field: 'salary',
    reducer: 'avg',
  },
  age: {
    name: 'Age (avg)',
    field: 'age',
    reducer: 'avg',
  },
};

const columns: InfiniteTablePropColumns<Developer> = {
  preferredLanguage: { field: 'preferredLanguage' },
  age: { field: 'age' },

  salary: {
    field: 'salary',
    type: 'number',
  },
  canDesign: { field: 'canDesign' },
  country: { field: 'country' },
  firstName: { field: 'firstName' },
  stack: { field: 'stack' },
  id: { field: 'id' },
  hobby: { field: 'hobby' },
  city: { field: 'city' },
  currency: { field: 'currency' },
};

// make the row labels column (id: 'labels') be pinned
const defaultColumnPinning: InfiniteTablePropColumnPinning = {
  // make the generated group columns pinned to start
  'group-by-country': 'start',
  'group-by-stack': 'start',
};

// make all rows collapsed by default
const groupRowsState = new GroupRowsState({
  expandedRows: [],
  collapsedRows: true,
});

const groupBy: DataSourceGroupBy<Developer>[] = [
  {
    field: 'country',
    column: {
      // give the group column for the country prop a custom id
      id: 'group-by-country',
    },
  },
  {
    field: 'stack',
    column: {
      // give the group column for the stack prop a custom id
      id: 'group-by-stack',
    },
  },
];

const pivotBy: DataSourcePivotBy<Developer>[] = [
  { field: 'preferredLanguage' },
  {
    field: 'canDesign',
    // customize the column group
    columnGroup: ({ columnGroup }) => {
      return {
        ...columnGroup,
        header: `${
          columnGroup.pivotGroupKey === 'yes' ? 'Designer' : 'Non-designer'
        }`,
      };
    },
    // customize columns generated under this column group
    column: ({ column }) => ({
      ...column,
      header: `🎉 ${column.header}`,
    }),
  },
];

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      #ds="infiniteDataSource"
      primaryKey="id"
      [data]="dataSource"
      [groupBy]="groupBy"
      [pivotBy]="pivotBy"
      [aggregationReducers]="aggregationReducers"
      [defaultGroupRowsState]="groupRowsState"
      [lazyLoad]="true"
    >
      <infinite-table
        debugId="remote-pivoting-example"
        [defaultColumnPinning]="defaultColumnPinning"
        [columns]="columns"
        [hideEmptyGroupColumns]="true"
        [pivotColumns]="ds.pivotColumns()"
        [pivotColumnGroups]="ds.pivotColumnGroups()"
        [columnDefaultWidth]="220"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly aggregationReducers = aggregationReducers;
  protected readonly columns = columns;
  protected readonly dataSource = dataSource;
  protected readonly defaultColumnPinning = defaultColumnPinning;
  protected readonly groupBy = groupBy;
  protected readonly groupRowsState = groupRowsState;
  protected readonly pivotBy = pivotBy;
}
```

### groupRowsState (`{collapsedRows:true|[][], expandedRows:true|[][]}`)

> Controls the expand/collapse state of group rows, when [`[(groupBy)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy) is used

See related [`defaultGroupRowsState`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultGroupRowsState), [`(groupRowsStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onGroupRowsStateChange) and [`[(groupBy)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy)

```tsx
const groupRowsState: DataSourcePropGroupRowsStateObject = {
  collapsedRows: true,
  expandedRows: [['Mexico'], ['Mexico', 'backend'], ['India']],
};
```

The two properties in this object are `collapsedRows` and `expandedRows`, and each can have the following values:
 - `true` - meaning that all groups have this state
 - an array of arrays - representing the exceptions to the default value

So if you have `collapsedRows` set to `true` and then `expandedRows` set to `[['Mexico'], ['Mexico', 'backend'], ['India']]` then all rows are collapsed by default, except the rows specified in the `expandedRows`.

**Example: Using controlled expanded/collapsed state for group rows**

```ts
import { Component, signal } from '@angular/core';

import {
  DataSource,
  GroupRowsState,
  InfiniteTable,
} from '@infinite-table/infinite-angular';
import type {
  DataSourcePropGroupBy,
  DataSourcePropGroupRowsStateObject,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  email: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const groupBy: DataSourcePropGroupBy<Developer> = [
  {
    field: 'country',
  },
  {
    field: 'stack',
  },
];

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
  },
  firstName: { field: 'firstName' },
  age: { field: 'age' },
  salary: {
    field: 'salary',
    type: 'number',
  },

  canDesign: { field: 'canDesign' },
  stack: { field: 'stack' },
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers1k')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <button
      (click)="
        groupRowsState.set({
          expandedRows: true,
          collapsedRows: [],
        })
      "
    >
      Expand all
    </button>
    <button
      (click)="
        groupRowsState.set({
          expandedRows: [],
          collapsedRows: true,
        })
      "
    >
      Collapse all
    </button>
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [groupBy]="groupBy"
      [groupRowsState]="groupRowsState()"
      (groupRowsStateChange)="onGroupRowsStateChange($event)"
    >
      <infinite-table
        debugId="group-rows-state-controlled-example"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly groupBy = groupBy;

  
  protected readonly groupRowsState = signal<
    DataSourcePropGroupRowsStateObject<string>
  >({
    collapsedRows: true,
    expandedRows: [['Mexico'], ['Mexico', 'backend'], ['India']],
  });

  // the grid emits a GroupRowsState instance: store its plain object
  protected onGroupRowsStateChange(
    groupRowsState:
      | GroupRowsState<string>
      | DataSourcePropGroupRowsStateObject<string>
      | undefined,
  ) {
    if (groupRowsState instanceof GroupRowsState) {
      this.groupRowsState.set(groupRowsState.getState());
    } else if (groupRowsState) {
      this.groupRowsState.set(groupRowsState);
    }
  }
}
```

### onGroupRowsStateChange (`(state: GroupRowsState) => void`)

> Callback prop when the [`[(groupRowsState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupRowsState) changes.

See related [`[(groupRowsState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupRowsState) and [`[(groupBy)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy)

This function is called with an object that's an instance of [`GroupRowsState`](https://infinite-table.com/docs/reference/type-definitions/index.md#GroupRowsState), when the user interacts with group rows and expands/collapses them.

If you want to get a plain object from this instance, call the `.getState()` method.

See [`GroupRowsState`](https://infinite-table.com/docs/reference/type-definitions/index.md#GroupRowsState) reference to find out all the utility methods this instance gives you.

### defaultGroupRowsState (`{collapsedRows:true|[][], expandedRows:true|[][]}`)

> Specifies the initial expand/collapse state of group rows, when [`[(groupBy)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy) is used

For the controlled version, see related [`[(groupRowsState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupRowsState).

```tsx
const defaultGroupRowsState: DataSourcePropGroupRowsStateObject = {
  expandedRows: true,
  collapsedRows: [['Mexico'], ['Mexico', 'backend'], ['India']],
};
```

The two properties in this object are `collapsedRows` and `expandedRows`, and each can have the following values:
 - `true` - meaning that all groups have this state
 - an array of arrays - representing the exceptions to the default value

So if you have `expandedRows` set to `true` and then `collapsedRows` set to `[['Mexico'], ['Mexico', 'backend'], ['India']]` then all rows are expanded by default, except the rows specified in the `collapsedRows`.

**Example: Specifying initial expanded/collapsed state for group rows**

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropGroupBy,
  DataSourcePropGroupRowsStateObject,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  email: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const groupBy: DataSourcePropGroupBy<Developer> = [
  {
    field: 'country',
  },
  {
    field: 'stack',
  },
];

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
  },
  firstName: { field: 'firstName' },
  age: { field: 'age' },
  salary: {
    field: 'salary',
    type: 'number',
  },

  canDesign: { field: 'canDesign' },
  stack: { field: 'stack' },
};
const defaultGroupRowsState: DataSourcePropGroupRowsStateObject<string> = {
  collapsedRows: true,
  expandedRows: [['Mexico'], ['Mexico', 'backend'], ['India']],
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers1k')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [groupBy]="groupBy"
      [defaultGroupRowsState]="defaultGroupRowsState"
    >
      <infinite-table
        debugId="group-rows-initial-state-example"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly groupBy = groupBy;
  protected readonly defaultGroupRowsState = defaultGroupRowsState;
}
```

### groupBy

> An array of objects with `field` properties, that control how rows are being grouped.

Each item in the array can have the following properties:

- field - `keyof DATA_TYPE`
- column - config object for the group [column](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#column) - see [`groupBy.column`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy.column).

When using [groupRenderStrategy="multi-column"](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupRenderStrategy), it can be very useful for each group to configure it's own column - use [`groupBy.column`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy.column) for this.

See [`DataSourcePropGroupBy`](https://infinite-table.com/docs/reference/type-definitions/index.md#DataSourcePropGroupBy) for the type definition.

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropAggregationReducers,
  DataSourcePropGroupBy,
} from '@infinite-table/infinite-angular';

import { columns } from './columns.angular';
import type { Employee } from './columns.angular';

const columnSizing: Record<string, { width: number }> = {
  'country-group': { width: 250 },
};

const groupBy: DataSourcePropGroupBy<Employee> = [
  {
    field: 'country',
    column: {
      id: 'country-group',
      renderValue: ({ data, isGroupRow, value }) =>
        isGroupRow ? value : `Country: ${data?.country}!`,
      style: {
        color: 'tomato',
      },
    },
  },
];

const reducers: DataSourcePropAggregationReducers<Employee> = {
  avgSalary: {
    reducer: (acc, value) => acc + value,
    done: (sum, arr) => Math.floor(arr.length ? sum / arr.length : 0),
    field: 'salary',
    initialValue: 0,
  },
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/employees1k')
    .then((r) => r.json())
    .then((data: Employee[]) => data);
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [aggregationReducers]="reducers"
      [groupBy]="groupBy"
    >
      <infinite-table
        debugId="groupBy-example"
        [columns]="columns"
        [defaultColumnSizing]="columnSizing"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly columnSizing = columnSizing;
  protected readonly groupBy = groupBy;
  protected readonly reducers = reducers;
}
```

### pivotBy (`DataSourcePivotBy<DATA_TYPE>[]`)

> An array of objects with `field` properties that control how pivoting works. Pivoting is very often associated with aggregations, so see related [`aggregationReducers`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#aggregationReducers) for more details.

Each item in the array can have the following properties:

- field - `keyof DATA_TYPE`
- column - config object or function for generated pivot columns.

For more details on the type of the items in this array prop, see [`DataSourcePivotBy`](https://infinite-table.com/docs/reference/type-definitions/index.md#DataSourcePivotBy).

**Example: Pivoting with customized pivot column**

```ts
import { Component } from '@angular/core';

import {
  InfiniteTable,
  DataSource,
  GroupRowsState,
} from '@infinite-table/infinite-angular';
import type {
  DataSourcePropAggregationReducers,
  InfiniteTableColumnAggregator,
  InfiniteTablePropColumns,
  DataSourceGroupBy,
  DataSourcePivotBy,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers100')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const avgReducer: InfiniteTableColumnAggregator<Developer, any> = {
  initialValue: 0,
  field: 'salary',
  reducer: (acc, sum) => acc + sum,
  done: (sum, arr) => (arr.length ? sum / arr.length : 0),
};

const columnAggregations: DataSourcePropAggregationReducers<Developer> = {
  salary: avgReducer,
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: { field: 'id' },
  firstName: { field: 'firstName' },
  preferredLanguage: { field: 'preferredLanguage' },
  stack: { field: 'stack' },
  country: { field: 'country' },
  canDesign: { field: 'canDesign' },
  hobby: { field: 'hobby' },

  city: { field: 'city' },
  age: { field: 'age' },
  salary: { field: 'salary', type: 'number' },
  currency: { field: 'currency' },
};

const groupRowsState = new GroupRowsState({
  expandedRows: [],
  collapsedRows: true,
});

const groupBy: DataSourceGroupBy<Developer>[] = [
  {
    field: 'preferredLanguage',
  },
  { field: 'stack' },
];

const pivotBy: DataSourcePivotBy<Developer>[] = [
  { field: 'country' },
  {
    field: 'canDesign',
    column: ({ column: pivotCol }) => {
      const lastKey =
        pivotCol.pivotGroupKeys[pivotCol.pivotGroupKeys.length - 1];

      return {
        header: lastKey === 'yes' ? '💅 Designer' : '💻 Non-designer',
      };
    },
  },
];

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      #ds="infiniteDataSource"
      primaryKey="id"
      [data]="dataSource"
      [groupBy]="groupBy"
      [pivotBy]="pivotBy"
      [aggregationReducers]="columnAggregations"
      [defaultGroupRowsState]="groupRowsState"
    >
      <infinite-table
        debugId="pivoting-customize-column-example"
        [columns]="columns"
        [hideEmptyGroupColumns]="true"
        [pivotColumns]="ds.pivotColumns()"
        [pivotColumnGroups]="ds.pivotColumnGroups()"
        [columnDefaultWidth]="180"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly columnAggregations = columnAggregations;
  protected readonly columns = columns;
  protected readonly dataSource = dataSource;
  protected readonly groupBy = groupBy;
  protected readonly groupRowsState = groupRowsState;
  protected readonly pivotBy = pivotBy;
}
```

 
### groupBy.column (`Partial<InfiniteTableColumn<T>>`)

> An object that configures how the column for the current group should look like

If [`groupColumn`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupColumn) is specified, it overrides this property (the objects actually get merged, with `groupColumn` having higher priority and being merged last).

If you are using a [groupRenderStrategy="single-column"](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupRenderStrategy), then using `groupBy.column` should not be used, as you could have many groups with conflicting column configuration.

In this case, use the [`groupColumn`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupColumn) prop.

This example uses `groupBy.column` to configure the generated columns corresponding to each group.

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropAggregationReducers,
  DataSourcePropGroupBy,
} from '@infinite-table/infinite-angular';

import { columns } from './columns.angular';
import type { Employee } from './columns.angular';

const columnSizing: Record<string, { width: number }> = {
  'country-group': { width: 250 },
};

const groupBy: DataSourcePropGroupBy<Employee> = [
  {
    field: 'country',
    column: {
      header: 'Country grouping',
      style: {
        color: 'tomato',
      },
    },
  },
  {
    field: 'city',
    column: {
      field: 'firstName',
      style: {
        color: 'green',
      },
    },
  },
];

const reducers: DataSourcePropAggregationReducers<Employee> = {
  avgSalary: {
    reducer: (acc, value) => acc + value,
    done: (sum, arr) => Math.floor(arr.length ? sum / arr.length : 0),
    field: 'salary',
    initialValue: 0,
  },
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/employees1k')
    .then((r) => r.json())
    .then((data: Employee[]) => data);
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [aggregationReducers]="reducers"
      [groupBy]="groupBy"
    >
      <infinite-table
        debugId="groupBy-multi-with-column-example"
        [columns]="columns"
        [defaultColumnSizing]="columnSizing"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly columnSizing = columnSizing;
  protected readonly groupBy = groupBy;
  protected readonly reducers = reducers;
}
```

### livePagination (`boolean`)

> Whether the component should use live pagination.

Use this in combination with [`livePaginationCursor`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePaginationCursor) and [`(dataParamsChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onDataParamsChange)

**Example: Live pagination - with react-query**

```ts
import { Component, computed, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  InfiniteTableColumn,
  DataSourceSingleSortInfo,
  DataSourceDataParams,
  DataSourceLivePaginationCursorFn,
} from '@infinite-table/infinite-angular';

const columns: Record<string, InfiniteTableColumn<Employee>> = {
  id: { field: 'id' },
  country: {
    field: 'country',
  },
  city: { field: 'city' },
  team: { field: 'team' },
  department: { field: 'department' },
  firstName: { field: 'firstName' },
  lastName: { field: 'lastName' },

  salary: { field: 'salary' },
  age: { field: 'age' },
};

type Employee = {
  id: number;
  companyName: string;
  companySize: string;
  firstName: string;
  lastName: string;
  country: string;
  countryCode: string;
  city: string;
  streetName: string;
  streetNo: number;
  department: string;
  team: string;
  salary: number;
  age: number;
  email: string;
};

type Page = {
  data: Employee[];
  hasMore: boolean;
  page: number;
  nextPageCursor: number;
  prevPageCursor: number;
};

const PAGE_SIZE = 10;

const dataSource = ({
  sortInfo,
  livePaginationCursor = 0,
}: {
  sortInfo: DataSourceSingleSortInfo<Employee> | null;
  livePaginationCursor: number;
}) => {
  return fetch(
    process.env.NEXT_PUBLIC_BASE_URL +
      `/employees10k?_limit=${PAGE_SIZE}&_sort=${sortInfo?.field}&_order=${
        sortInfo?.dir === 1 ? 'asc' : 'desc'
      }&_start=${livePaginationCursor}`,
  )
    .then(async (r) => {
      const data = await r.json();
      // we need the remote count, so we take it from headers
      const total = Number(r.headers.get('X-Total-Count')!);
      return { data, total };
    })
    .then(({ data, total }: { data: Employee[]; total: number }) => {
      const page = livePaginationCursor / PAGE_SIZE + 1;

      const prevPageCursor = Math.max(PAGE_SIZE * (page - 1), 0);
      return {
        data,
        hasMore: total > PAGE_SIZE * page,
        page,
        prevPageCursor,
        nextPageCursor: prevPageCursor + data.length,
      };
    })
    .then((response): Promise<Page> => {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(response);
        }, 150);
      });
    });
};

const livePaginationCursorFn: DataSourceLivePaginationCursorFn<Employee> = ({
  length,
}) => {
  return length;
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <!-- take the data from data(), the rows of all the pages loaded so far -->
    <infinite-data-source
      primaryKey="id"
      [data]="data()"
      [loading]="isFetchingNextPage()"
      (dataParamsChange)="onDataParamsChange($event)"
      [livePagination]="true"
      [livePaginationCursor]="livePaginationCursorFn"
    >
      <infinite-table
        debugId="live-pagination-example"
        [scrollTopKey]="scrollTopId()"
        [columnDefaultWidth]="200"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly columns = columns;
  protected readonly livePaginationCursorFn = livePaginationCursorFn;

  private dataParams: Partial<DataSourceDataParams<Employee>> = {
    groupBy: [],
    sortInfo: undefined,
    livePaginationCursor: null,
  };

  // the pages loaded so far, with the current sorting
  private readonly pages = signal<Page[]>([]);

  // all the rows of those pages - this is the `data` of the DataSource
  protected readonly data = computed(() =>
    this.pages().flatMap((page) => page.data),
  );

  protected readonly isFetchingNextPage = signal(false);
  private isFetchingFirstPage = false;

  // when sorting changes, scroll to the top
  protected readonly scrollTopId = signal(Date.now());

  // incremented with every new query key (sorting and grouping), so a
  // response that arrives after the sorting has changed is dropped
  private queryId = 0;

  constructor() {
    this.fetchFirstPage();
  }

  protected onDataParamsChange(newDataParams: DataSourceDataParams<Employee>) {
    const previous = this.dataParams;
    this.dataParams = {
      groupBy: newDataParams.groupBy,
      sortInfo: newDataParams.sortInfo,
      livePaginationCursor: newDataParams.livePaginationCursor,
    };

    const sortInfoChanged =
      JSON.stringify(previous.sortInfo) !==
      JSON.stringify(this.dataParams.sortInfo);
    if (sortInfoChanged) {
      this.scrollTopId.set(Date.now());
    }
    // when the sorting or the grouping changes, the pages are loaded again, from the first one
    if (
      sortInfoChanged ||
      JSON.stringify(previous.groupBy) !==
        JSON.stringify(this.dataParams.groupBy)
    ) {
      this.fetchFirstPage();
    }
    if (
      previous.livePaginationCursor !== this.dataParams.livePaginationCursor
    ) {
      this.fetchNextPage();
    }
  }

  private fetchFirstPage() {
    const currentQueryId = ++this.queryId;

    this.isFetchingFirstPage = true;
    this.isFetchingNextPage.set(false);

    dataSource({
      livePaginationCursor: 0,
      sortInfo: this.dataParams
        .sortInfo as DataSourceSingleSortInfo<Employee> | null,
    }).then((page) => {
      if (currentQueryId !== this.queryId) {
        return;
      }
      this.isFetchingFirstPage = false;
      // the previous rows stay in the table until the first page with the new sorting arrives
      this.pages.set([page]);
    });
  }

  private fetchNextPage() {
    const pages = this.pages();
    const lastPage = pages[pages.length - 1];

    if (
      this.isFetchingFirstPage ||
      this.isFetchingNextPage() ||
      !lastPage?.hasMore
    ) {
      return;
    }

    const currentQueryId = this.queryId;

    this.isFetchingNextPage.set(true);

    dataSource({
      livePaginationCursor: lastPage.nextPageCursor,
      sortInfo: this.dataParams
        .sortInfo as DataSourceSingleSortInfo<Employee> | null,
    }).then((page) => {
      if (currentQueryId !== this.queryId) {
        return;
      }
      this.isFetchingNextPage.set(false);
      this.pages.update((pages) => [...pages, page]);
    });
  }
}
```

### onDataMutations (`({ mutations, dataArray, primaryKeyField }) => void`)

> Callback prop to be called when the data changes via the DataSource API.

Called when any of the following methods have been called in the `DataSource` api

- [`updateData`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#updateData)
- [`updateDataArray`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#updateDataArray)

- [`removeData`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#removeData)
- [`removeDataArray`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#removeDataArray)

- [`removeDataByPrimaryKey`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#removeDataByPrimaryKey)
- [`removeDataArrayByPrimaryKeys`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#removeDataArrayByPrimaryKeys)

- [`insertData`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#insertData)
- [`insertDataArray`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#insertDataArray)

- [`addData`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#addData)
- [`addDataArray`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md#addDataArray)

This callback is called with an object that has the following properties:

- `primaryKeyField` - the field configured as the primary key for the `<DataSource />`
- `mutations` - a `Map` with mutations. The keys in the map are primary keys of the mutated data

The values in the mutations are object descriptors of mutations, that have the following shape:

- `type`: `'insert'|'update'|'delete'`
- `originalData`: `DATA_TYPE | null` - the original data before the mutation. In case of `insert`, it will be `null`
- `data`: `Partial<DATA_TYPE>` - the updates to be performed on the data. In case of `delete`, it will be `undefined`. This is an object that will contain the primary key, and the updated values for the data (not necessarily the full object, except for `insert`, where it will be of type `DATA_TYPE`).

### livePaginationCursor (`string|number|((params) =>string|number)`)

> A cursor value for live pagination. A good value for this is the id of the last item in the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) array. It can also be defined as a function

Use this in combination with [`livePagination`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePagination) and [`(dataParamsChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onDataParamsChange)

When this is a function, it is called with a parameter object that has the following properties:

- `array` - the current array of data
- `lastItem` - the last item in the array
- `length` - the length of the data array

**Example: Live pagination - with react-query**

```ts
import { Component, computed, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  InfiniteTableColumn,
  DataSourceSingleSortInfo,
  DataSourceDataParams,
  DataSourceLivePaginationCursorFn,
} from '@infinite-table/infinite-angular';

const columns: Record<string, InfiniteTableColumn<Employee>> = {
  id: { field: 'id' },
  country: {
    field: 'country',
  },
  city: { field: 'city' },
  team: { field: 'team' },
  department: { field: 'department' },
  firstName: { field: 'firstName' },
  lastName: { field: 'lastName' },

  salary: { field: 'salary' },
  age: { field: 'age' },
};

type Employee = {
  id: number;
  companyName: string;
  companySize: string;
  firstName: string;
  lastName: string;
  country: string;
  countryCode: string;
  city: string;
  streetName: string;
  streetNo: number;
  department: string;
  team: string;
  salary: number;
  age: number;
  email: string;
};

type Page = {
  data: Employee[];
  hasMore: boolean;
  page: number;
  nextPageCursor: number;
  prevPageCursor: number;
};

const PAGE_SIZE = 10;

const dataSource = ({
  sortInfo,
  livePaginationCursor = 0,
}: {
  sortInfo: DataSourceSingleSortInfo<Employee> | null;
  livePaginationCursor: number;
}) => {
  return fetch(
    process.env.NEXT_PUBLIC_BASE_URL +
      `/employees10k?_limit=${PAGE_SIZE}&_sort=${sortInfo?.field}&_order=${
        sortInfo?.dir === 1 ? 'asc' : 'desc'
      }&_start=${livePaginationCursor}`,
  )
    .then(async (r) => {
      const data = await r.json();
      // we need the remote count, so we take it from headers
      const total = Number(r.headers.get('X-Total-Count')!);
      return { data, total };
    })
    .then(({ data, total }: { data: Employee[]; total: number }) => {
      const page = livePaginationCursor / PAGE_SIZE + 1;

      const prevPageCursor = Math.max(PAGE_SIZE * (page - 1), 0);
      return {
        data,
        hasMore: total > PAGE_SIZE * page,
        page,
        prevPageCursor,
        nextPageCursor: prevPageCursor + data.length,
      };
    })
    .then((response): Promise<Page> => {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(response);
        }, 150);
      });
    });
};

const livePaginationCursorFn: DataSourceLivePaginationCursorFn<Employee> = ({
  length,
}) => {
  return length;
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <!-- take the data from data(), the rows of all the pages loaded so far -->
    <infinite-data-source
      primaryKey="id"
      [data]="data()"
      [loading]="isFetchingNextPage()"
      (dataParamsChange)="onDataParamsChange($event)"
      [livePagination]="true"
      [livePaginationCursor]="livePaginationCursorFn"
    >
      <infinite-table
        debugId="live-pagination-example"
        [scrollTopKey]="scrollTopId()"
        [columnDefaultWidth]="200"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly columns = columns;
  protected readonly livePaginationCursorFn = livePaginationCursorFn;

  private dataParams: Partial<DataSourceDataParams<Employee>> = {
    groupBy: [],
    sortInfo: undefined,
    livePaginationCursor: null,
  };

  // the pages loaded so far, with the current sorting
  private readonly pages = signal<Page[]>([]);

  // all the rows of those pages - this is the `data` of the DataSource
  protected readonly data = computed(() =>
    this.pages().flatMap((page) => page.data),
  );

  protected readonly isFetchingNextPage = signal(false);
  private isFetchingFirstPage = false;

  // when sorting changes, scroll to the top
  protected readonly scrollTopId = signal(Date.now());

  // incremented with every new query key (sorting and grouping), so a
  // response that arrives after the sorting has changed is dropped
  private queryId = 0;

  constructor() {
    this.fetchFirstPage();
  }

  protected onDataParamsChange(newDataParams: DataSourceDataParams<Employee>) {
    const previous = this.dataParams;
    this.dataParams = {
      groupBy: newDataParams.groupBy,
      sortInfo: newDataParams.sortInfo,
      livePaginationCursor: newDataParams.livePaginationCursor,
    };

    const sortInfoChanged =
      JSON.stringify(previous.sortInfo) !==
      JSON.stringify(this.dataParams.sortInfo);
    if (sortInfoChanged) {
      this.scrollTopId.set(Date.now());
    }
    // when the sorting or the grouping changes, the pages are loaded again, from the first one
    if (
      sortInfoChanged ||
      JSON.stringify(previous.groupBy) !==
        JSON.stringify(this.dataParams.groupBy)
    ) {
      this.fetchFirstPage();
    }
    if (
      previous.livePaginationCursor !== this.dataParams.livePaginationCursor
    ) {
      this.fetchNextPage();
    }
  }

  private fetchFirstPage() {
    const currentQueryId = ++this.queryId;

    this.isFetchingFirstPage = true;
    this.isFetchingNextPage.set(false);

    dataSource({
      livePaginationCursor: 0,
      sortInfo: this.dataParams
        .sortInfo as DataSourceSingleSortInfo<Employee> | null,
    }).then((page) => {
      if (currentQueryId !== this.queryId) {
        return;
      }
      this.isFetchingFirstPage = false;
      // the previous rows stay in the table until the first page with the new sorting arrives
      this.pages.set([page]);
    });
  }

  private fetchNextPage() {
    const pages = this.pages();
    const lastPage = pages[pages.length - 1];

    if (
      this.isFetchingFirstPage ||
      this.isFetchingNextPage() ||
      !lastPage?.hasMore
    ) {
      return;
    }

    const currentQueryId = this.queryId;

    this.isFetchingNextPage.set(true);

    dataSource({
      livePaginationCursor: lastPage.nextPageCursor,
      sortInfo: this.dataParams
        .sortInfo as DataSourceSingleSortInfo<Employee> | null,
    }).then((page) => {
      if (currentQueryId !== this.queryId) {
        return;
      }
      this.isFetchingNextPage.set(false);
      this.pages.update((pages) => [...pages, page]);
    });
  }
}
```

### multiRowSelectionTarget (`'all'|'visible'`)

> When some rows are filtered out, decides which rows the header selection checkbox, the group row checkboxes and the select all/deselect all API methods act on. Only used with `selectionMode="multi-row"`.

- `'all'` - they act on all the rows in the data (or in the group, for group rows), including the rows that are filtered out. The header and group checkboxes are only checked when all those rows are selected.
- `'visible'` - they act only on the rows that pass the filter. The rows that are filtered out keep their current selection. The header and group checkboxes are checked when all the visible rows are selected.

When no rows are filtered out, both values behave the same.

This applies to flat, grouped and tree data, both with primary keys and with [`useGroupKeysForMultiRowSelection`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#useGroupKeysForMultiRowSelection). For tree data, it also applies to the parent node checkboxes and to [`selectAll`](https://infinite-table.com/docs/reference/tree-api/index.md#selectAll)/[`deselectAll`](https://infinite-table.com/docs/reference/tree-api/index.md#deselectAll).

With [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad), the server applies the target: the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function receives `multiRowSelectionTarget` in its [parameters](https://infinite-table.com/docs/reference/type-definitions/index.md#DataSourceDataParams), and it should use it when working out which rows a stored selection covers. Changing this prop doesn't reload the data.

**Example: Choosing which rows the selection acts on when the data is filtered**

```ts
import { Component, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropGroupBy,
  DataSourcePropMultiRowSelectionTarget,
  DataSourcePropRowSelection,
  DataSourcePropRowSelection_MultiRow,
  InfiniteTableApi,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

const columns: InfiniteTablePropColumns<Developer> = {
  checkbox: {
    renderSelectionCheckBox: true,
    defaultWidth: 70,
  },
  id: { field: 'id', defaultWidth: 80 },
  firstName: { field: 'firstName' },
  preferredLanguage: { field: 'preferredLanguage' },
  stack: { field: 'stack' },
};

const groupBy: DataSourcePropGroupBy<Developer> = [{ field: 'stack' }];

const filterFunction = ({ data }: { data: Developer }) =>
  data.preferredLanguage === 'TypeScript';

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers100')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <div
      style="
        color: var(--infinite-cell-color);
        padding: 10px;
        display: flex;
        gap: 20px;
        align-items: center;
      "
    >
      <label>
        multiRowSelectionTarget:
        <select [value]="target()" (change)="onTargetChange($event)">
          <option value="all">all</option>
          <option value="visible">visible</option>
        </select>
      </label>
      <label>
        <input
          type="checkbox"
          [checked]="filtered()"
          (change)="filtered.set($any($event.target).checked)"
        />
        Only show TypeScript developers
      </label>
      <button (click)="api?.rowSelectionApi?.selectAll()">Select all</button>
      <span>Selected rows (including filtered out): {{ selectedCount() }}</span>
    </div>
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      selectionMode="multi-row"
      [multiRowSelectionTarget]="target()"
      [groupBy]="groupBy"
      [filterFunction]="filtered() ? filterFunction : undefined"
      (rowSelectionChange)="onRowSelectionChange($event)"
    >
      <infinite-table
        [columns]="columns"
        [columnDefaultWidth]="150"
        (ready)="api = $event.api"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly groupBy = groupBy;
  protected readonly filterFunction = filterFunction;

  protected readonly target =
    signal<DataSourcePropMultiRowSelectionTarget>('visible');
  protected readonly filtered = signal(true);
  protected readonly selectedCount = signal(0);

  protected api: InfiniteTableApi<Developer> | null = null;

  protected onTargetChange(event: Event) {
    this.target.set(
      (event.target as HTMLSelectElement)
        .value as DataSourcePropMultiRowSelectionTarget,
    );
  }

  protected onRowSelectionChange(
    rowSelection: DataSourcePropRowSelection | undefined,
  ) {
    // selectionMode="multi-row": the selection is an object
    this.selectedCount.set(
      this.api?.rowSelectionApi.getSelectedPrimaryKeys(
        rowSelection as DataSourcePropRowSelection_MultiRow,
      ).length ?? 0,
    );
  }
}
```

### onDataParamsChange (`(dataParams: DataSourceDataParams<DATA_TYPE:>)=>void`)

> A function to be called when data-related state changes.

Can be used to implement [`livePagination`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePagination)

The function is called with an object that has the following properties:

- `sortInfo` - current sort information - see [`[(sortInfo)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortInfo) for details
- `groupBy` - current grouping information - see [`[(groupBy)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy) for details
- `filterValue` - current filtering information - see [`[(filterValue)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterValue) for details
- `livePaginationCursor` - the value for the live pagination cursor - see [`livePaginationCursor`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePaginationCursor) for details
- `changes` - an object that can help you figure out what change caused `onDataParamsChange` to be called.

**Example: Live pagination - with react-query**

```ts
import { Component, computed, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  InfiniteTableColumn,
  DataSourceSingleSortInfo,
  DataSourceDataParams,
  DataSourceLivePaginationCursorFn,
} from '@infinite-table/infinite-angular';

const columns: Record<string, InfiniteTableColumn<Employee>> = {
  id: { field: 'id' },
  country: {
    field: 'country',
  },
  city: { field: 'city' },
  team: { field: 'team' },
  department: { field: 'department' },
  firstName: { field: 'firstName' },
  lastName: { field: 'lastName' },

  salary: { field: 'salary' },
  age: { field: 'age' },
};

type Employee = {
  id: number;
  companyName: string;
  companySize: string;
  firstName: string;
  lastName: string;
  country: string;
  countryCode: string;
  city: string;
  streetName: string;
  streetNo: number;
  department: string;
  team: string;
  salary: number;
  age: number;
  email: string;
};

type Page = {
  data: Employee[];
  hasMore: boolean;
  page: number;
  nextPageCursor: number;
  prevPageCursor: number;
};

const PAGE_SIZE = 10;

const dataSource = ({
  sortInfo,
  livePaginationCursor = 0,
}: {
  sortInfo: DataSourceSingleSortInfo<Employee> | null;
  livePaginationCursor: number;
}) => {
  return fetch(
    process.env.NEXT_PUBLIC_BASE_URL +
      `/employees10k?_limit=${PAGE_SIZE}&_sort=${sortInfo?.field}&_order=${
        sortInfo?.dir === 1 ? 'asc' : 'desc'
      }&_start=${livePaginationCursor}`,
  )
    .then(async (r) => {
      const data = await r.json();
      // we need the remote count, so we take it from headers
      const total = Number(r.headers.get('X-Total-Count')!);
      return { data, total };
    })
    .then(({ data, total }: { data: Employee[]; total: number }) => {
      const page = livePaginationCursor / PAGE_SIZE + 1;

      const prevPageCursor = Math.max(PAGE_SIZE * (page - 1), 0);
      return {
        data,
        hasMore: total > PAGE_SIZE * page,
        page,
        prevPageCursor,
        nextPageCursor: prevPageCursor + data.length,
      };
    })
    .then((response): Promise<Page> => {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(response);
        }, 150);
      });
    });
};

const livePaginationCursorFn: DataSourceLivePaginationCursorFn<Employee> = ({
  length,
}) => {
  return length;
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <!-- take the data from data(), the rows of all the pages loaded so far -->
    <infinite-data-source
      primaryKey="id"
      [data]="data()"
      [loading]="isFetchingNextPage()"
      (dataParamsChange)="onDataParamsChange($event)"
      [livePagination]="true"
      [livePaginationCursor]="livePaginationCursorFn"
    >
      <infinite-table
        debugId="live-pagination-example"
        [scrollTopKey]="scrollTopId()"
        [columnDefaultWidth]="200"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly columns = columns;
  protected readonly livePaginationCursorFn = livePaginationCursorFn;

  private dataParams: Partial<DataSourceDataParams<Employee>> = {
    groupBy: [],
    sortInfo: undefined,
    livePaginationCursor: null,
  };

  // the pages loaded so far, with the current sorting
  private readonly pages = signal<Page[]>([]);

  // all the rows of those pages - this is the `data` of the DataSource
  protected readonly data = computed(() =>
    this.pages().flatMap((page) => page.data),
  );

  protected readonly isFetchingNextPage = signal(false);
  private isFetchingFirstPage = false;

  // when sorting changes, scroll to the top
  protected readonly scrollTopId = signal(Date.now());

  // incremented with every new query key (sorting and grouping), so a
  // response that arrives after the sorting has changed is dropped
  private queryId = 0;

  constructor() {
    this.fetchFirstPage();
  }

  protected onDataParamsChange(newDataParams: DataSourceDataParams<Employee>) {
    const previous = this.dataParams;
    this.dataParams = {
      groupBy: newDataParams.groupBy,
      sortInfo: newDataParams.sortInfo,
      livePaginationCursor: newDataParams.livePaginationCursor,
    };

    const sortInfoChanged =
      JSON.stringify(previous.sortInfo) !==
      JSON.stringify(this.dataParams.sortInfo);
    if (sortInfoChanged) {
      this.scrollTopId.set(Date.now());
    }
    // when the sorting or the grouping changes, the pages are loaded again, from the first one
    if (
      sortInfoChanged ||
      JSON.stringify(previous.groupBy) !==
        JSON.stringify(this.dataParams.groupBy)
    ) {
      this.fetchFirstPage();
    }
    if (
      previous.livePaginationCursor !== this.dataParams.livePaginationCursor
    ) {
      this.fetchNextPage();
    }
  }

  private fetchFirstPage() {
    const currentQueryId = ++this.queryId;

    this.isFetchingFirstPage = true;
    this.isFetchingNextPage.set(false);

    dataSource({
      livePaginationCursor: 0,
      sortInfo: this.dataParams
        .sortInfo as DataSourceSingleSortInfo<Employee> | null,
    }).then((page) => {
      if (currentQueryId !== this.queryId) {
        return;
      }
      this.isFetchingFirstPage = false;
      // the previous rows stay in the table until the first page with the new sorting arrives
      this.pages.set([page]);
    });
  }

  private fetchNextPage() {
    const pages = this.pages();
    const lastPage = pages[pages.length - 1];

    if (
      this.isFetchingFirstPage ||
      this.isFetchingNextPage() ||
      !lastPage?.hasMore
    ) {
      return;
    }

    const currentQueryId = this.queryId;

    this.isFetchingNextPage.set(true);

    dataSource({
      livePaginationCursor: lastPage.nextPageCursor,
      sortInfo: this.dataParams
        .sortInfo as DataSourceSingleSortInfo<Employee> | null,
    }).then((page) => {
      if (currentQueryId !== this.queryId) {
        return;
      }
      this.isFetchingNextPage.set(false);
      this.pages.update((pages) => [...pages, page]);
    });
  }
}
```

### onFilterValueChange (`({field?, id?, filter: {type, operator, value}[]) => void`)

> Callback prop called when the [`[(filterValue)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterValue) changes.

This might not be called immediately, as there might be a [`filterDelay`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterDelay) set.

**Example: Controlled filters with onFilterValueChange**

```ts
import { Component, signal } from '@angular/core';
import { JsonPipe } from '@angular/common';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  DataSourceProps,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;

  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';

  salary: number;
};

const data: DataSourceData<Developer> = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql?`)
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 100,
  },
  salary: {
    defaultFilterable: true,
    field: 'salary',
    type: 'number',
  },

  firstName: {
    field: 'firstName',
  },
  stack: { field: 'stack' },
  currency: { field: 'currency' },
};

const domProps = {
  style: {
    height: '100%',
  },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable, JsonPipe],
  template: `
    <div style="color: var(--infinite-cell-color)">
      Current filters:
      <pre><code>{{ filterValue() | json }}</code></pre>
    </div>
    <infinite-data-source
      [data]="data"
      primaryKey="id"
      [(filterValue)]="filterValue"
      [filterDelay]="0"
    >
      <infinite-table
        debugId="onFilterValueChange-example"
        [domProps]="domProps"
        [columnDefaultWidth]="150"
        [columnMinWidth]="50"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly domProps = domProps;
  protected readonly columns = columns;

  
  protected readonly filterValue = signal<
    DataSourceProps<Developer>['filterValue']
  >([
    {
      field: 'salary',
      filter: {
        operator: 'gt',
        value: 50000,
        type: 'number',
      },
    },
  ]);
}
```

### onLivePaginationCursorChange (`(cursor)=> void`)

> A function to be called when the [`livePaginationCursor`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePaginationCursor) changes.

Also see related [`(dataParamsChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onDataParamsChange).

### onReady (`(dataSourceApi: DataSourceApi<DATA_TYPE>) => void`)

> The callback that is called when the `DataSource` is ready. The [`dataSourceApi`](https://infinite-table.com/angular/docs/reference/datasource-api/index.md) is passed as the first argument.

### onCellSelectionChange (`(cellSelection, selectionMode='multi-cell') => void`)

> A function to be called when the [`[(cellSelection)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#cellSelection) changes.

Use your mouse to select/deselect cells.

**Example: Controlled cell selection with onCellSelectionChange**

```ts
import { Component, computed, signal } from '@angular/core';

import { InfiniteTable, DataSource } from '@infinite-table/infinite-angular';
import type {
  InfiniteTablePropColumns,
  DataSourcePropCellSelection_MultiCell,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers1k')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: { field: 'id', defaultWidth: 60 },
  firstName: { field: 'firstName' },
  preferredLanguage: { field: 'preferredLanguage' },
  stack: { field: 'stack' },
  country: { field: 'country' },
  age: { field: 'age', type: 'number' },
  salary: { field: 'salary', type: 'number' },
  currency: { field: 'currency', type: 'number' },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <div
      style="
        display: flex;
        flex: 1;
        color: var(--infinite-cell-color);
        flex-flow: column;
        background: var(--infinite-background);
      "
    >
      <div style="max-height: 200px; overflow: auto; border: 2px solid magenta">
        Current selection:
        <pre>{{ cellSelectionJSON() }}</pre>
      </div>

      <infinite-data-source
        primaryKey="id"
        [data]="dataSource"
        [(cellSelection)]="cellSelection"
        selectionMode="multi-cell"
      >
        <infinite-table
          debugId="controlled-cell-selection-example"
          [columns]="columns"
          [columnDefaultWidth]="100"
        />
      </infinite-data-source>
    </div>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;

  
  protected readonly cellSelection =
    signal<DataSourcePropCellSelection_MultiCell>({
      defaultSelection: false,
      selectedCells: [
        [3, 'stack'],
        [0, 'firstName'],
      ],
    });

  protected readonly cellSelectionJSON = computed(() =>
    JSON.stringify(this.cellSelection(), null, 2),
  );
}
```

### onRowSelectionChange (`(rowSelection, selectionMode='single-row'|'multi-row') => void`)

> A function to be called when the [`[(rowSelection)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#rowSelection) changes.

Use your mouse or keyboard (press the spacebar) to select/deselect a single row.

**Example: Controlled row selection with onRowSelectionChange**

```ts
import { Component, computed, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type { InfiniteTablePropColumns } from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  email: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
  },
  firstName: {
    field: 'firstName',
  },
  stack: {
    field: 'stack',
  },
  age: { field: 'age' },
  id: { field: 'id' },
  salary: {
    field: 'salary',
    type: 'number',
  },
  canDesign: { field: 'canDesign' },
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers100')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <p style="color: var(--infinite-cell-color); padding: 10px">
      Current row selection:
      <code style="display: inline-block">
        <pre> {{ rowSelectionJSON() }}.</pre>
      </code>
    </p>

    <infinite-data-source
      [data]="dataSource"
      [(rowSelection)]="rowSelection"
      primaryKey="id"
    >
      <infinite-table
        debugId="controlled-single-row-selection-example"
        [columns]="columns"
        [columnDefaultWidth]="150"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;

  
  protected readonly rowSelection = signal<number | string | null>(3);

  protected readonly rowSelectionJSON = computed(() =>
    JSON.stringify(this.rowSelection()),
  );
}
```

This example shows how you can use multiple row selection with a predefined controlled value.

Go ahead and select some groups/rows and see the selection value adjust.

The example also shows how you can use the `InfiniteTableApi` to retrieve the actual ids of the selected rows.

**Example: Multi row checkbox selection with grouping**

```ts
import { Component, computed, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropGroupBy,
  DataSourcePropRowSelection_MultiRow,
  InfiniteTableColumn,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  email: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
  },
  firstName: {
    field: 'firstName',
    defaultHiddenWhenGroupedBy: '*',
  },
  stack: {
    field: 'stack',
    renderGroupValue: ({ value }) => `Stack: ${value || ''}`,
  },
  age: { field: 'age' },
  id: { field: 'id' },
  preferredLanguage: {
    field: 'preferredLanguage',
    renderGroupValue: ({ value }) => `Lang: ${value || ''}`,
  },
  canDesign: {
    field: 'canDesign',
    renderGroupValue: ({ value }) => `Can design: ${value || ''}`,
  },
};

const defaultGroupBy: DataSourcePropGroupBy<Developer> = [
  {
    field: 'canDesign',
  },
  {
    field: 'stack',
  },
  {
    field: 'preferredLanguage',
  },
];

const groupColumn: InfiniteTableColumn<Developer> = {
  field: 'firstName',
  renderSelectionCheckBox: true,
  defaultWidth: 300,
};

const domProps = {
  style: {
    flex: 1,
    minHeight: 500,
  },
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers100')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <div
      style="
        display: flex;
        flex: 1;
        overflow: auto;
        color: var(--infinite-cell-color);
        flex-flow: column;
        background: var(--infinite-background);
      "
    >
      <div style="padding: 10px">
        Current row selection:
        <code
          style="
            display: block;
            height: 100px;
            overflow: auto;
            border: 1px dashed currentColor;
          "
        >
          <pre> {{ rowSelectionJSON() }}.</pre>
        </code>
      </div>

      <infinite-data-source
        [data]="dataSource"
        [groupBy]="defaultGroupBy"
        [(rowSelection)]="rowSelection"
        primaryKey="id"
      >
        <infinite-table
          debugId="controlled-multi-row-selection-example"
          [columns]="columns"
          [domProps]="domProps"
          [groupColumn]="groupColumn"
          [columnDefaultWidth]="150"
        />
      </infinite-data-source>
    </div>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly defaultGroupBy = defaultGroupBy;
  protected readonly groupColumn = groupColumn;
  protected readonly domProps = domProps;

  
  protected readonly rowSelection = signal<DataSourcePropRowSelection_MultiRow>(
    {
      selectedRows: [0, 8, 10],
      defaultSelection: false,
    },
  );

  protected readonly rowSelectionJSON = computed(() =>
    JSON.stringify(this.rowSelection()),
  );
}
```

### onSortInfoChange (`(sortInfo | null) => void`)

> Called when sorting changes on the DataSource.

The sorting can change either via a user interaction or by calling an API method (from the [root API](api) or the [Column API](column-api)).

See related [`[(sortInfo)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortInfo) for controlled sorting and [`defaultSortInfo`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultSortInfo) for uncontrolled sorting.

### refetchKey (`string|number|object`)

> A value that can be used to trigger a re-fetch of the data.

By updating the value of this prop (eg: you can use it as a counter, and increment it) the `<DataSource />` component reloads it's [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) if it's defined as a function. More specifically, the `data` function is called again and the result will replace the current data.

This example shows how you can use the `refetchKey` to trigger reloading the data

**Example: Re-fetching data via refetchKey updates**

```ts
import { Component, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type { InfiniteTablePropColumns } from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers1k')
    .then((r) => r.json())
    .then((data) => {
      return new Promise<Developer[]>((resolve) => {
        // add a delay to make "reloading" more visible
        setTimeout(() => {
          resolve(data);
        }, 1000);
      });
    });
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: { field: 'id' },
  firstName: { field: 'firstName' },
  preferredLanguage: { field: 'preferredLanguage' },
  stack: { field: 'stack' },
  country: { field: 'country' },
  age: { field: 'age', type: 'number' },
  salary: { field: 'salary', type: 'number' },
  currency: { field: 'currency', type: 'number' },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <button
      style="color: var(--infinite-cell-color); margin: 10px; padding: 20px; background: var(--infinite-background)"
      (click)="refetchKey.set(refetchKey() + 1)"
    >
      Refetch data
    </button>
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [refetchKey]="refetchKey()"
    >
      <infinite-table
        debugId="refetchKey-example"
        [columns]="columns"
        [columnDefaultWidth]="150"
        [loadingText]="'Refetching with key ' + refetchKey()"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;

  protected readonly refetchKey = signal(0);
}
```
 

### rowSelection (`string|number|null|object`)

> Describes the selected row(s) in the `DataSource`

For single selection, the prop will be of type: `number | string | null`. Use `null` for empty selection in single selection mode.

For multiple selection, the prop will have the following shape:

```ts
rowSelection = {
  selectedRows: [3, 6, 100, 23], // those specific rows are selected
  defaultSelection: false, // all rows deselected by default
};

// or
rowSelection = {
  deselectedRows: [3, 6, 100, 23], // those specific rows are deselected
  defaultSelection: true, // all other rows are selected
};

// or, for grouped data - this example assumes groupBy=continent,country,city
rowSelection = {
  selectedRows: [
    45, // row with id 45 is selected, no matter the group
    ['Europe', 'France'], // all rows in Europe/France are selected
    ['Asia'], // all rows in Asia are selected
  ],
  deselectedRows: [
    ['Europe', 'France', 'Paris'], // all rows in Paris are deselected
  ],
  defaultSelection: false, // all other rows are selected
};
```

For using group keys in the selection value, see related [`useGroupKeysForMultiRowSelection`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#useGroupKeysForMultiRowSelection)

Use your mouse or keyboard (press the spacebar) to select/deselect a single row.

**Example: Single row selection (controlled) with onRowSelectionChange**

```ts
import { Component, computed, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type { InfiniteTablePropColumns } from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  email: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
  },
  firstName: {
    field: 'firstName',
  },
  stack: {
    field: 'stack',
  },
  age: { field: 'age' },
  id: { field: 'id' },
  salary: {
    field: 'salary',
    type: 'number',
  },
  canDesign: { field: 'canDesign' },
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers100')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <p style="color: var(--infinite-cell-color); padding: 10px">
      Current row selection:
      <code style="display: inline-block">
        <pre> {{ rowSelectionJSON() }}.</pre>
      </code>
    </p>

    <infinite-data-source
      [data]="dataSource"
      [(rowSelection)]="rowSelection"
      primaryKey="id"
    >
      <infinite-table
        debugId="controlled-single-row-selection-example"
        [columns]="columns"
        [columnDefaultWidth]="150"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;

  
  protected readonly rowSelection = signal<number | string | null>(3);

  protected readonly rowSelectionJSON = computed(() =>
    JSON.stringify(this.rowSelection()),
  );
}
```

When [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad) is being used - this means not all available groups/rows have actually been loaded yet in the dataset - we need a way to allow you to specify that those possibly unloaded rows/groups are selected or not. In this case, the `rowSelection.selectedRows`/`rowSelection.deselectedRows` arrays should not have row primary keys as strings/numbers, but rather rows/groups specified by their full path (so [`useGroupKeysForMultiRowSelection`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#useGroupKeysForMultiRowSelection) should be set to `true`).

```ts
// this example assumes groupBy=continent,country,city
const rowSelection = {
  selectedRows: [
    // row with id 45 is selected - we need this because in the lazyLoad scenario,
    // not all parents might have been made available yet
    ['Europe','Italy', 'Rome', 45],
    ['Europe','France'], // all rows in Europe/France are selected
    ['Asia'] // all rows in Asia are selected
  ],
  deselectedRows: [
    ['Europe','Italy','Rome'] // all rows in Rome are deselected
    // but note that row with id 45 is selected, so Rome will be rendered with an indeterminate selection state
  ],
  defaultSelection: false // all other rows are selected
}
```

In the example above, we know that there are 3 groups (`continent`, `country`, `city`), so any item in the array that has a 4th element is a fully specified leaf node. While lazy loading, we need this fully specified path for specific nodes, so we know which group rows to render with indeterminate selection.

The [`useGroupKeysForMultiRowSelection`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#useGroupKeysForMultiRowSelection) prop can be used for both lazy and non-lazy `DataSource` components.

This example shows how you can use multiple row selection with a predefined controlled value.

Go ahead and select some groups/rows and see the selection value adjust.

The example also shows how you can use the `InfiniteTableApi` to retrieve the actual ids of the selected rows.

**Example: Multi row checkbox selection with grouping**

```ts
import { Component, computed, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropGroupBy,
  DataSourcePropRowSelection_MultiRow,
  InfiniteTableColumn,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  email: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
  },
  firstName: {
    field: 'firstName',
    defaultHiddenWhenGroupedBy: '*',
  },
  stack: {
    field: 'stack',
    renderGroupValue: ({ value }) => `Stack: ${value || ''}`,
  },
  age: { field: 'age' },
  id: { field: 'id' },
  preferredLanguage: {
    field: 'preferredLanguage',
    renderGroupValue: ({ value }) => `Lang: ${value || ''}`,
  },
  canDesign: {
    field: 'canDesign',
    renderGroupValue: ({ value }) => `Can design: ${value || ''}`,
  },
};

const defaultGroupBy: DataSourcePropGroupBy<Developer> = [
  {
    field: 'canDesign',
  },
  {
    field: 'stack',
  },
  {
    field: 'preferredLanguage',
  },
];

const groupColumn: InfiniteTableColumn<Developer> = {
  field: 'firstName',
  renderSelectionCheckBox: true,
  defaultWidth: 300,
};

const domProps = {
  style: {
    flex: 1,
    minHeight: 500,
  },
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers100')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <div
      style="
        display: flex;
        flex: 1;
        overflow: auto;
        color: var(--infinite-cell-color);
        flex-flow: column;
        background: var(--infinite-background);
      "
    >
      <div style="padding: 10px">
        Current row selection:
        <code
          style="
            display: block;
            height: 100px;
            overflow: auto;
            border: 1px dashed currentColor;
          "
        >
          <pre> {{ rowSelectionJSON() }}.</pre>
        </code>
      </div>

      <infinite-data-source
        [data]="dataSource"
        [groupBy]="defaultGroupBy"
        [(rowSelection)]="rowSelection"
        primaryKey="id"
      >
        <infinite-table
          debugId="controlled-multi-row-selection-example"
          [columns]="columns"
          [domProps]="domProps"
          [groupColumn]="groupColumn"
          [columnDefaultWidth]="150"
        />
      </infinite-data-source>
    </div>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly defaultGroupBy = defaultGroupBy;
  protected readonly groupColumn = groupColumn;
  protected readonly domProps = domProps;

  
  protected readonly rowSelection = signal<DataSourcePropRowSelection_MultiRow>(
    {
      selectedRows: [0, 8, 10],
      defaultSelection: false,
    },
  );

  protected readonly rowSelectionJSON = computed(() =>
    JSON.stringify(this.rowSelection()),
  );
}
```

### selectionMode (`'single-row'|'multi-row'|'multi-cell'|false`)

> Specifies the type of selection that should be enabled.

Read more on row selection (`multi-row` and `single-row`).

Read more on cell selection (`multi-cell` and `single-cell`).

**Example: Choose your selection mode between multi cell or multi row**

```ts
import { Component, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type { InfiniteTablePropColumns } from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers1k')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  id: { field: 'id', defaultWidth: 60 },
  firstName: { field: 'firstName' },
  preferredLanguage: { field: 'preferredLanguage' },
  stack: { field: 'stack' },
  country: { field: 'country' },
  age: { field: 'age', type: 'number' },
  salary: { field: 'salary', type: 'number' },
  currency: { field: 'currency', type: 'number' },
};

const currentColumns: InfiniteTablePropColumns<Developer> = {
  ...columns,
  id: {
    field: 'id',
    defaultWidth: 60,
    renderSelectionCheckBox: true,
  },
};

type SelectionMode = 'multi-cell' | 'multi-row';

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <div
      style="display: flex; flex: 1; color: var(--infinite-cell-color); flex-flow: column; background: var(--infinite-background)"
    >
      <p style="padding: 10px">Please select the selection mode</p>
      <div style="padding: 10px; padding-top: 0">
        <select
          style="margin: 10px 0; display: inline-block; background: var(--infinite-background); color: currentColor; padding: var(--infinite-space-3)"
          [value]="selectionMode()"
          (change)="onSelectionModeChange($event)"
        >
          <option value="multi-cell">multi-cell</option>
          <option value="multi-row">multi-row</option>
        </select>
      </div>
      <infinite-data-source
        primaryKey="id"
        [data]="dataSource"
        [selectionMode]="selectionMode()"
      >
        <infinite-table
          debugId="selectionMode-example"
          [columns]="currentColumns"
          [columnDefaultWidth]="100"
        />
      </infinite-data-source>
    </div>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly currentColumns = currentColumns;

  protected readonly selectionMode = signal<SelectionMode>('multi-cell');

  protected onSelectionModeChange(event: Event) {
    this.selectionMode.set(
      (event.target as HTMLSelectElement).value as SelectionMode,
    );
  }
}
```

### sortFunction (`(sortInfo:DataSourceSingleSortInfo<T>[], arr: T[]) => T[]`)

> Custom sorting function to replace the built-in sorting - `multisort` for flat data, `multisortNested` for tree data.

The function specified in the [`sortFunction`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortFunction) prop is called with the [`[(sortInfo)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortInfo) as the first argument and the data array as the second. It should return a sorted array, as per the [`[(sortInfo)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortInfo) it was called with.

A `sortFunction` makes the sorting happen in the browser, and it is independent from [`shouldReloadData.sortInfo`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#shouldReloadData.sortInfo), which only decides if the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function is called again when the sorting changes. With both, the data is fetched again on every sort change and then sorted in the browser - `sortFunction={multisort}` is the easiest way to get that.

A `sortFunction` has no effect with [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad) or [`livePagination`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePagination).

The `@infinite-table/infinite-angular` package exports a `multisort` function - this is the default function used for local sorting of flat data.

```ts
import { multisort } from '@infinite-table/infinite-angular';

const arr: Developer[] = [
  /*...*/
];
const sortInfo: DataSourceSingleSortInfo<Developer>[] = [
  {
    field: 'age',
    dir: -1,
  },
  {
    field: 'name',
    dir: 1,
  },
];
multisort(sortInfo, arr);
```

If you want to implement your own custom sort function, the `multisort` fn is a good starting point you can use.

**Example: Using a custom sortFunction**

```ts
import { Component } from '@angular/core';

import {
  DataSource,
  InfiniteTable,
  multisort,
} from '@infinite-table/infinite-angular';
import type {
  DataSourceSingleSortInfo,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;

  email: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const columns: InfiniteTablePropColumns<Developer> = {
  preferredLanguage: { field: 'preferredLanguage' },
  salary: {
    field: 'salary',
    type: 'number',
  },
  age: { field: 'age' },
  canDesign: { field: 'canDesign' },
  country: { field: 'country' },
  firstName: { field: 'firstName' },
  stack: { field: 'stack' },
  id: { field: 'id' },
  hobby: { field: 'hobby' },
  city: { field: 'city' },
  currency: { field: 'currency' },
};

const defaultSortInfo: DataSourceSingleSortInfo<Developer> = {
  field: 'stack',
  dir: 1,
};

const sortFunction = (
  sortInfo: DataSourceSingleSortInfo<Developer>[],
  arr: Developer[],
) => {
  // you call the default sorting
  const result = multisort<Developer>(sortInfo, arr);

  // and also apply your custom sorting
  // result.sort((a, b) => {
  // })

  return result;
};

const dataSource: Developer[] = [
  {
    id: 0,

    firstName: 'Nya',
    lastName: 'Klein',
    country: 'India',
    city: 'Unnao',
    age: 24,
    currency: 'JPY',
    preferredLanguage: 'TypeScript',
    stack: 'backend',
    canDesign: 'yes',
    salary: 60000,
    hobby: 'sports',
    email: 'Nya44@gmail.com',
  },
  {
    id: 1,
    firstName: 'Axel',
    lastName: 'Runolfsson',
    country: 'Mexico',
    city: 'Cuitlahuac',
    age: 46,
    currency: 'USD',
    preferredLanguage: 'TypeScript',
    stack: 'backend',
    canDesign: 'no',
    salary: 100000,
    hobby: 'sports',
    email: 'Axel93@hotmail.com',
  },
  {
    id: 2,
    firstName: 'Gonzalo',
    lastName: 'McGlynn',
    country: 'United Arab Emirates',
    city: 'Fujairah',
    age: 54,
    currency: 'JPY',
    preferredLanguage: 'Go',
    stack: 'frontend',
    canDesign: 'yes',
    salary: 120000,
    hobby: 'photography',
    email: 'Gonzalo_McGlynn34@gmail.com',
  },
  {
    id: 3,
    firstName: 'Sherwood',
    lastName: 'McLaughlin',
    country: 'Mexico',
    city: 'Tlacolula de Matamoros',
    age: 43,
    currency: 'CHF',
    preferredLanguage: 'Rust',
    stack: 'backend',
    canDesign: 'no',
    salary: 99000,
    hobby: 'cooking',
    email: 'Sherwood_McLaughlin65@hotmail.com',
  },
  {
    id: 4,
    firstName: 'Alexandre',
    lastName: 'Harber',
    country: 'France',
    city: 'Persan',
    age: 23,
    currency: 'EUR',
    preferredLanguage: 'Go',
    stack: 'backend',
    canDesign: 'yes',
    salary: 97000,
    hobby: 'reading',
    email: 'Alexandre_Harber@hotmail.com',
  },
  {
    id: 5,

    firstName: 'Mariane',
    lastName: 'Schroeder',
    country: 'United States',
    city: 'Hays',
    age: 34,
    currency: 'EUR',
    preferredLanguage: 'TypeScript',
    stack: 'backend',
    canDesign: 'no',
    salary: 58000,
    hobby: 'cooking',
    email: 'Mariane0@hotmail.com',
  },
  {
    id: 6,
    firstName: 'Rosalind',
    lastName: 'Mills',
    country: 'Mexico',
    city: 'Nuevo Casas Grandes',
    age: 33,
    currency: 'AUD',
    preferredLanguage: 'JavaScript',
    stack: 'frontend',
    canDesign: 'no',
    salary: 198000,
    hobby: 'dancing',
    email: 'Rosalind69@gmail.com',
  },
  {
    id: 7,
    firstName: 'Lolita',
    lastName: 'Hayes',
    country: 'Sweden',
    city: 'Delsbo',
    age: 22,
    currency: 'JPY',
    preferredLanguage: 'TypeScript',
    stack: 'full-stack',
    canDesign: 'yes',
    salary: 200000,
    hobby: 'cooking',
    email: 'Lolita.Hayes@hotmail.com',
  },
  {
    id: 8,
    firstName: 'Tre',
    lastName: 'Boyle',
    country: 'Germany',
    city: 'Bad Camberg',
    age: 11,
    currency: 'GBP',
    preferredLanguage: 'TypeScript',
    stack: 'backend',
    canDesign: 'yes',
    salary: 200000,
    hobby: 'sports',
    email: 'Tre28@gmail.com',
  },
  {
    id: 9,
    firstName: 'Lurline',
    lastName: 'Deckow',
    country: 'Canada',
    city: 'Raymore',
    age: 31,
    currency: 'EUR',
    preferredLanguage: 'Rust',
    stack: 'frontend',
    canDesign: 'yes',
    salary: 58000,
    hobby: 'sports',
    email: 'Lurline_Deckow@gmail.com',
  },
];

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      primaryKey="id"
      [data]="dataSource"
      [defaultSortInfo]="defaultSortInfo"
      [sortFunction]="sortFunction"
    >
      <infinite-table
        debugId="local-sortFunction-single-sorting-example-with-local-data-example"
        [columns]="columns"
        [columnDefaultWidth]="220"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly defaultSortInfo = defaultSortInfo;
  protected readonly sortFunction = sortFunction;
}
```

#### Flat data vs tree data: `multisort` and `multisortNested`

- `multisort(sortInfo, array)` sorts a flat array - it's the default for a `DataSource`. It sorts the array in place and returns it.
- `multisortNested(sortInfo, array, { nodesKey, toKey, isLeafNode?, getNodeChildren?, depthFirst?, inplace? })` sorts tree data on every level - it's the default for a `TreeDataSource`. With `inplace: false` (what the `TreeDataSource` uses), the top-level array is copied before sorting, but the sorted children of every parent node are assigned back onto that parent node.

A `sortFunction` is called with the top-level array only, and with no information about the tree. So for tree data, a custom `sortFunction` has to sort the children too - your code knows the `nodesKey` and the primary key, so it can call `multisortNested`:

**Example: A custom sortFunction for tree data, using multisortNested**

```ts
import { Component } from '@angular/core';

import {
  TreeDataSource,
  TreeGrid,
  multisortNested,
} from '@infinite-table/infinite-angular';
import type {
  DataSourceSingleSortInfo,
  InfiniteTableColumn,
} from '@infinite-table/infinite-angular';

type FileSystemNode = {
  id: string;
  name: string;
  type: 'folder' | 'file';
  sizeInKB: number;
  children?: FileSystemNode[];
};

const columns: Record<string, InfiniteTableColumn<FileSystemNode>> = {
  name: { field: 'name', header: 'Name', renderTreeIcon: true },
  type: { field: 'type', header: 'Type' },
  size: { field: 'sizeInKB', type: 'number', header: 'Size (KB)' },
};

const defaultSortInfo: DataSourceSingleSortInfo<FileSystemNode> = {
  field: 'sizeInKB',
  dir: -1,
};

// the sortFunction only gets the top-level nodes - so it calls
// multisortNested, which sorts every level of the tree
function sortFunction(
  sortInfo: DataSourceSingleSortInfo<FileSystemNode>[],
  nodes: FileSystemNode[],
) {
  // folders first, then the sorting the user picked
  const folderFirst = {
    dir: 1 as const,
    valueGetter: (node: FileSystemNode) => (node.type === 'folder' ? 0 : 1),
    type: 'number',
  };

  return multisortNested([folderFirst, ...sortInfo], nodes, {
    nodesKey: 'children',
    toKey: (node) => node.id,
  });
}

const nodes: FileSystemNode[] = [
  {
    id: '1',
    name: 'Documents',
    sizeInKB: 1200,
    type: 'folder',
    children: [
      { id: '10', name: 'Report.docx', sizeInKB: 210, type: 'file' },
      { id: '11', name: 'Vacation.docx', sizeInKB: 120, type: 'file' },
      {
        id: '12',
        name: 'Archive',
        sizeInKB: 600,
        type: 'folder',
        children: [
          { id: '120', name: '2023.zip', sizeInKB: 400, type: 'file' },
          { id: '121', name: '2024.zip', sizeInKB: 200, type: 'file' },
        ],
      },
    ],
  },
  { id: '2', name: 'notes.txt', sizeInKB: 2, type: 'file' },
  {
    id: '3',
    name: 'Pictures',
    sizeInKB: 3000,
    type: 'folder',
    children: [
      { id: '30', name: 'beach.png', sizeInKB: 1800, type: 'file' },
      { id: '31', name: 'mountain.png', sizeInKB: 1200, type: 'file' },
    ],
  },
  { id: '4', name: 'todo.md', sizeInKB: 5, type: 'file' },
];

@Component({
  selector: 'demo-root',
  imports: [TreeDataSource, TreeGrid],
  template: `
    <infinite-tree-data-source
      nodesKey="children"
      primaryKey="id"
      [data]="nodes"
      [defaultSortInfo]="defaultSortInfo"
      [sortFunction]="sortFunction"
    >
      <infinite-tree-grid [columns]="columns" />
    </infinite-tree-data-source>
  `,
})
export default class App {
  protected readonly nodes = nodes;
  protected readonly columns = columns;
  protected readonly defaultSortInfo = defaultSortInfo;
  protected readonly sortFunction = sortFunction;
}
```

### sortInfo (`DataSourceSingleSortInfo<T>|DataSourceSingleSortInfo<T>[]|null`)

> Information for sorting the data. This is a controlled prop.

Also see related [`defaultSortInfo`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultSortInfo) (uncontrolled version), [`shouldReloadData.sortInfo`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#shouldReloadData.sortInfo), [`sortable`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#sortable) and [`columns.sortable`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.sortable).

Sorting can be single (only one field/column can be sorted at a time) or multiple (multiple fields/columns can be sorted at the same time). Therefore, this property an be an array of objects or a single object (or null) - the shape of the objects (of type `DataSourceSingleSortInfo<T>`)is the following.

- `dir` - `1 | -1` - the direction of the sorting
- `field`? - `keyof DATA_TYPE` - the field to sort
- `id`? - `string` - if you don't sort by a field, you can specify an id of the column this sorting is bound to. Note that columns have a [valueGetter](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.valueGetter), which will be used when doing local sorting and the column is not bound to an exact field.
- `type` - the sort type - one of the keys in [`sortTypes`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortTypes) - eg `"string"`, `"number"` - will be used for local sorting, to provide the proper comparison function.

When you want to use multiple sorting, but have no default sort order/information, use `[]` (the empty array) to denote multiple sorting should be enabled.

If no `sortInfo` is provided, by default, when clicking a sortable column, single sorting will be applied.

For configuring if a column is sortable or not, see [`columns.sortable`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.sortable) and [`sortable`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#sortable). By default, all columns are sortable.

**Example: Remote + controlled multi sorting**

```ts
import { Component, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  DataSourcePropSortInfo,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const dataSource: DataSourceData<Developer> = ({ sortInfo }) => {
  if (sortInfo && !Array.isArray(sortInfo)) {
    sortInfo = [sortInfo];
  }
  const args = [
    sortInfo
      ? 'sortInfo=' +
        JSON.stringify(
          sortInfo.map((s) => ({
            field: s.field,
            dir: s.dir,
          })),
        )
      : null,
  ]
    .filter(Boolean)
    .join('&');

  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers100-sql?` + args)
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

const columns: InfiniteTablePropColumns<Developer> = {
  preferredLanguage: { field: 'preferredLanguage' },
  salary: {
    field: 'salary',
    type: 'number',
  },
  age: { field: 'age' },
  canDesign: { field: 'canDesign' },
  country: { field: 'country' },
  firstName: { field: 'firstName' },
  stack: { field: 'stack' },
  id: { field: 'id' },
  hobby: { field: 'hobby' },
  city: { field: 'city' },
  currency: { field: 'currency' },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      primaryKey="id"
      [data]="dataSource"
      [(sortInfo)]="sortInfo"
      [shouldReloadData]="shouldReloadData"
    >
      <infinite-table
        debugId="remote-controlled-multi-sorting-example"
        [columns]="columns"
        [columnDefaultWidth]="220"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;

  
  protected readonly sortInfo = signal<DataSourcePropSortInfo<Developer>>([
    {
      field: 'salary',
      dir: -1,
    },
  ]);

  protected readonly shouldReloadData = {
    sortInfo: true,
  };
}
```

### shouldReloadData.sortInfo (`boolean`)

> Specifies if changes in the [`[(sortInfo)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortInfo) should trigger a reload of the data source - and so, that the data is sorted by whoever provides it.

See related [`[(sortInfo)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortInfo) and [`defaultSortInfo`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultSortInfo).

- `false` - the data is sorted locally (in the browser) and the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function is not called again. This is the default - for both controlled and uncontrolled sorting - unless [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad) or [`livePagination`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePagination) is used.
- `true` - the data is sorted by whoever provides it. When [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) is a function, it's called again on every sort change, with the `sortInfo` in its params. When [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) is an array, you pass a new, sorted array (eg from [`(sortInfoChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onSortInfoChange)). The rows are shown in the order they come in - unless a [`sortFunction`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortFunction) is specified, in which case they are sorted again in the browser. This is the default with [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad) and [`livePagination`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePagination).

See [the Sorting page](https://infinite-table.com/angular/docs/learn/sorting/overview.md) for more details, and [Sorting and filtering the data yourself](https://infinite-table.com/angular/docs/learn/working-with-data/sorting-and-filtering-the-data-yourself.md).

For configuring the sorting behavior when multiple sorting is enabled, see [`multiSortBehavior`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#multiSortBehavior).

### shouldReloadData.groupBy (`boolean`)

> Specifies if changes in the [`[(groupBy)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy) should trigger a reload of the data source - applicable when [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) is a function.

- `true` - when [`[(groupBy)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy) changes, the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function is called again, with the new `groupBy` in its params. This is the default with [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad), where the server does the grouping (lazily loaded rows can only be grouped by the server).
- `false` - the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function is not called again. This is the default without [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad) - also with [`livePagination`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePagination), where the loaded pages are grouped in the browser.

Without [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad), the grouping is always done in the browser - `true` only makes the data reload.

### shouldReloadData.pivotBy (`boolean`)

> Specifies if changes in the [`[(pivotBy)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#pivotBy) should trigger a reload of the data source - applicable when [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) is a function.

- `true` - when [`[(pivotBy)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#pivotBy) changes, the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function is called again, with the new `pivotBy` in its params. This is the default with [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad), where the server does the pivoting.
- `false` - the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function is not called again. This is the default without [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad).

Without [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad), the pivoting is always done in the browser - `true` only makes the data reload.

### shouldReloadData (`{ sortInfo, groupBy, filterValue, pivotBy }`)

> Specifies which changes in the data-related props should trigger a reload of the data source. Can be a boolean (applies to all of them) or an object.

For sorting and filtering, each one is in one of three states:

- done in the browser - `shouldReloadData.X: false`. The default, for any kind of [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data), unless [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad) or [`livePagination`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePagination) is used.
- reloaded, then done in the browser - `shouldReloadData.X: true`, plus a [`sortFunction`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortFunction) or a [`filterFunction`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#filterFunction) (eg `sortFunction={multisort}` or `filterFunction={defaultFilterFunction}`).
- done by whoever provides the data - `shouldReloadData.X: true` and no sort / filter function. The [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function is called again with the new values in its params (or, for array data, you pass the new data yourself). The default with [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad) (and, for sorting and filtering, with [`livePagination`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#livePagination)).

Grouping and pivoting are done in the browser, unless [`lazyLoad`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#lazyLoad) is used.

The params of the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function always include the current `sortInfo` and `filterValue`, even when they don't trigger a reload.

See [`shouldReloadData.sortInfo`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#shouldReloadData.sortInfo).
See [`shouldReloadData.groupBy`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#shouldReloadData.groupBy).
See [`shouldReloadData.filterValue`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#shouldReloadData.filterValue).
See [`shouldReloadData.pivotBy`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#shouldReloadData.pivotBy).

### sortTypes (`Record<string, ((a,b) => number)>`)

> Describes the available sorting functions used for local sorting. The object you provide will be merged into the default sort types.

Currently there are two `sortTypes` available:

- `"string"`
- `"number"`
- `"date"`

Those values can be used for the [column.sortType](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.sortType) and [column.dataType](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.sortType) properties.

```ts
// default implementation
const sortTypes: DataSourcePropSortTypes = {
  string: (a, b) => a.localeCompare(b),
  number: (a, b) => a - b,
  date: (a, b) => a - b,
};
```

When a column does not explicitly specify the [column.sortType](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.sortType), the [column.dataType](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.dataType) will be used instead. And if no [column.dataType](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.dataType) is defined, it will default to `string`.

You can add new sort types to the DataSource and InfiniteTable components by specifying this property - the object will be merged into the default sort types.

**Example: Custom sort by color - magenta will come first**

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type { InfiniteTableColumn } from '@infinite-table/infinite-angular';

type CarSale = {
  id: number;

  make: string;
  model: string;
  year: number;

  sales: number;
  color: string;
};

const carsales: CarSale[] = [
  {
    make: 'Volkswagen',
    model: 'GTI',
    year: 2009,
    sales: 6,
    color: 'red',
    id: 0,
  },
  {
    make: 'Honda',
    model: 'Element 2WD',
    year: 2009,
    sales: 739,
    color: 'red',
    id: 1,
  },
  {
    make: 'Acura',
    model: 'RDX 4WD',
    year: 2008,
    sales: 2,
    color: 'magenta',
    id: 2,
  },
  {
    make: 'Honda',
    model: 'Fit',
    year: 2009,
    sales: 211,
    color: 'blue',
    id: 3,
  },
  {
    make: 'Mazda',
    model: '6',
    year: 2009,
    sales: 31,
    color: 'blue',

    id: 4,
  },
  {
    make: 'Acura',
    model: 'TSX',
    year: 2009,
    sales: 14,
    color: 'yellow',
    id: 5,
  },
  {
    make: 'Acura',
    model: 'TSX',
    year: 2010,
    sales: 14,
    color: 'red',
    id: 6,
  },
  {
    make: 'Audi',
    model: 'A3',
    year: 2009,
    sales: 2,
    color: 'magenta',
    id: 7,
  },
];

const columns: Record<string, InfiniteTableColumn<CarSale>> = {
  color: { field: 'color', sortType: 'color' },
  make: { field: 'make' },
  model: { field: 'model' },

  sales: {
    field: 'sales',
    sortType: 'number',
  },
  year: {
    field: 'year',
    sortType: 'number',
  },
};
const newSortTypes = {
  color: (one: string, two: string) => {
    if (one === 'magenta') {
      // magenta comes first
      return -1;
    }
    if (two === 'magenta') {
      // magenta comes first
      return 1;
    }
    return one.localeCompare(two);
  },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="carsales"
      primaryKey="id"
      [defaultSortInfo]="{
        field: 'color',
        dir: 1,
        type: 'color',
      }"
      [sortTypes]="newSortTypes"
    >
      <infinite-table debugId="sortTypes-example" [columns]="columns" />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly carsales = carsales;
  protected readonly columns = columns;
  protected readonly newSortTypes = newSortTypes;
}
```

In this example, for the `"color"` column, we specified [column.sortType="color"](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.sortType) - we could have passed that as `column.dataType` instead, but if the grid had filtering, it wouldn't know what filters to use for "color" - so we used[column.sortType](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.sortType) to only change how the data is sorted.

### useGroupKeysForMultiRowSelection (`boolean`)

> Specifies whether [`[(rowSelection)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#rowSelection) contains group keys or only row ids/primary keys.

When this is `true`, you might want to use the [getSelectedPrimaryKeys](./selection-api#getSelectedPrimaryKeys) method.

When some rows are filtered out, see [`multiRowSelectionTarget`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#multiRowSelectionTarget) for which rows a selected group covers.

This example shows how you can use have row selection with group keys instead of just the primary keys of rows.

**Example: Multi row checkbox selection using group keys**

```ts
import { Component, computed, signal } from '@angular/core';
import { JsonPipe } from '@angular/common';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropGroupBy,
  DataSourcePropRowSelection_MultiRow,
  InfiniteTableApi,
  InfiniteTableColumn,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

type Developer = {
  id: number;
  firstName: string;
  lastName: string;
  country: string;
  city: string;
  currency: string;
  email: string;
  preferredLanguage: string;
  stack: string;
  canDesign: 'yes' | 'no';
  hobby: string;
  salary: number;
  age: number;
};

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
  },
  firstName: {
    field: 'firstName',
    defaultHiddenWhenGroupedBy: '*',
  },
  stack: {
    field: 'stack',
    renderGroupValue: ({ value }) => `Stack: ${value || ''}`,
  },
  age: { field: 'age' },
  id: { field: 'id' },
  preferredLanguage: {
    field: 'preferredLanguage',
    renderGroupValue: ({ value }) => `Lang: ${value || ''}`,
  },
  canDesign: {
    field: 'canDesign',
    renderGroupValue: ({ value }) => `Can design: ${value || ''}`,
  },
};

const defaultGroupBy: DataSourcePropGroupBy<Developer> = [
  {
    field: 'canDesign',
  },
  {
    field: 'stack',
  },
  {
    field: 'preferredLanguage',
  },
];

const groupColumn: InfiniteTableColumn<Developer> = {
  field: 'firstName',
  renderSelectionCheckBox: true,
  defaultWidth: 300,
};

const domProps = {
  style: {
    flex: 1,
    minHeight: 500,
  },
};

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/developers100')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable, JsonPipe],
  template: `
    <div
      style="
        display: flex;
        flex: 1;
        overflow: auto;
        color: var(--infinite-cell-color);
        flex-flow: column;
        background: var(--infinite-background);
      "
    >
      <div style="padding: 10px">
        Current row selection:
        <code
          style="
            display: block;
            height: 300px;
            overflow: auto;
            border: 1px dashed currentColor;
          "
        >
          <pre> {{ rowSelection() | json }}.</pre>
        </code>
        Current selected ids: {{ selectedIds().join(', ') }}
      </div>

      <infinite-data-source
        [data]="dataSource"
        [groupBy]="defaultGroupBy"
        [(rowSelection)]="rowSelection"
        [useGroupKeysForMultiRowSelection]="true"
        primaryKey="id"
      >
        <infinite-table
          debugId="controlled-multi-row-selection-example-with-group-keys"
          (ready)="onReady($event)"
          [columns]="columns"
          [domProps]="domProps"
          [groupColumn]="groupColumn"
          [columnDefaultWidth]="150"
        />
      </infinite-data-source>
    </div>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly defaultGroupBy = defaultGroupBy;
  protected readonly groupColumn = groupColumn;
  protected readonly domProps = domProps;

  private readonly api = signal<InfiniteTableApi<Developer> | null>(null);

  protected readonly rowSelection = signal<DataSourcePropRowSelection_MultiRow>(
    {
      selectedRows: [
        ['yes', 'backend', 'TypeScript'],
        ['yes', 'backend', 'Go'],
        16,
        26,
        30,
        ['yes', 'frontend'],
      ],
      deselectedRows: [4, 2],
      defaultSelection: false,
    },
  );

  // recomputed when the api is ready and on every selection change
  protected readonly selectedIds = computed(() => {
    const api = this.api();
    if (!api) {
      return [];
    }
    return api.rowSelectionApi.getSelectedPrimaryKeys(
      this.rowSelection(),
    ) as string[];
  });

  protected onReady({ api }: { api: InfiniteTableApi<Developer> }) {
    this.api.set(api);
  }
}
```
