# Grouping rows

Canonical page: https://infinite-table.com/angular/docs/learn/grouping-and-pivoting/grouping-rows

You can use any `field` available in the `DataSource` to do the grouping - it can even be a `field` that is not a column.

When using TypeScript, the types of the inputs are generic and take a `DATA_TYPE` parameter - for example `DataSourcePropGroupBy<DATA_TYPE>` for the `groupBy` input. The `DataSource` and `InfiniteTable` components are generic as well, and the templates are type-checked against the `DATA_TYPE` of the data you bind. The fields in that `DATA_TYPE` can then be used for grouping.

```ts
type Person = {
  name: string;
  age: number;
  country: string;
  id: string;
};

const groupBy: DataSourcePropGroupBy<Person> = [{ field: 'country' }];

@Component({
  selector: 'people-grid',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source primaryKey="id" [data]="data" [groupBy]="groupBy">
      <infinite-table [columns]="columns" />
    </infinite-data-source>
  `,
})
export class PeopleGrid {
  protected readonly data = data;
  protected readonly columns = columns;
  protected readonly groupBy = groupBy;
}
```

In the example above, we're grouping by `country`, which is a field available in the `Person` type. Specifying a field not defined in the `Person` type would be a type error.

Additionally, a `column` object can be used together with the `field` to define how the group column should be rendered.

```tsx
const groupBy: DataSourcePropGroupBy<Person> = [
  {
    field: 'country',
    column: {
      // custom column configuration for group column
      defaultWidth: 150,
      header: 'Country group',
    },
  },
];
```

The example below puts it all together.

Also see the [groupBy API reference](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy) to find out more.

**Example: Simple row grouping**

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

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropGroupBy,
  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',
    column: {
      header: 'Country group',
      renderGroupValue: ({ value }) => `Country: ${value}`,
    },
  },
];

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
    // specifying a style here for the column
    // note: it will also be "picked up" by the group column
    // if you're grouping by the 'country' field
    style: {
      color: 'tomato',
    },
  },
  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: `
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [groupBy]="groupBy"
    >
      <infinite-table debugId="row-grouping-example" [columns]="columns" />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly groupBy = groupBy;
}
```

In `groupBy.column` you can use any column property - so, for example, you can define a custom `renderValue` function to customize the rendering.

```ts
const groupBy: DataSourcePropGroupBy<Person> = [
  {
    field: 'country',
    column: {
      renderValue: ({ value }) => `Country: ${value}`,
    },
  },
];
```

The generated group column(s) - can be one for all groups or one for each group - will inherit the `style`/`className`/renderers from the columns corresponding to the group fields themselves (if those columns exist).

Additionally, there are other ways to override those inherited configurations, in order to configure the group columns:

- use [`groupBy.column`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupBy.column) to specify how each grouping column should look for the respective field (in case of [groupRenderStrateg="multi-column"](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupRenderStrategy))
- use [`groupColumn`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupColumn) prop
  - can be used as an object - ideal for when you have simple requirements and when [groupRenderStrateg="single-column"](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupRenderStrategy)
  - as a function that returns a column configuration - can be used like this in either single or multiple group render strategy

## Controlling the collapse/expand state

When you do grouping, by default, all row groups are expanded. Of course you have full control over this and you do this via the [`[(groupRowsState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupRowsState)/[`defaultGroupRowsState`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultGroupRowsState) props.

If you simply want to specify the initial expanded/collapsed state, you should use the [`defaultGroupRowsState`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultGroupRowsState) prop.

```tsx
const defaultGroupRowsState: 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: Everything is collapsed except a few 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',
    column: {
      header: 'Country group',
      renderGroupValue: ({ value }) => `Country: ${value}`,
    },
  },
  {
    field: 'stack',
  },
];

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
    // specifying a style here for the column
    // note: it will also be "picked up" by the group column
    // if you're grouping by the 'country' field
    style: {
      color: 'tomato',
    },
  },
  firstName: { field: 'firstName' },
  age: { field: 'age' },
  salary: {
    field: 'salary',
    type: 'number',
  },

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

const defaultGroupRowsState: DataSourcePropGroupRowsStateObject = {
  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="row-grouping-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;
}
```

You can specify expand/collapse state at any level of nesting.

Let's suppose by default all rows are collapsed - if you want a node to be visible then you have to specify all its parents as expanded.

So having this
```tsx
const defaultGroupRowsState = {
  collapsedRows: true,
  expandedRows: [['Mexico', 'backend']],
};
```
will show all rows as collapsed, and just as soon as you expand `Mexico` you will see the `backend` group row for Mexico to be expanded.

This data format gives you ultimate flexibility and allows you to easily restore an expand/collpase state at a later time, if you wanted to.

If you use the controlled [`[(groupRowsState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupRowsState), bind it two-way to a signal - it's a model, so the grid writes the new expand/collapse state back to your signal when the user expands or collapses a group. To react to the change, use the [`(groupRowsStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onGroupRowsStateChange) output.

**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,
  DataSourcePropGroupRowsState,
  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',
    column: {
      header: 'Country group',
      renderGroupValue: ({ value }) => `Country: ${value}`,
    },
  },
  {
    field: 'stack',
  },
];

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
    // specifying a style here for the column
    // note: it will also be "picked up" by the group column
    // if you're grouping by the 'country' field
    style: {
      color: 'tomato',
    },
  },
  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)="expandAll()">Expand all</button>
    <button (click)="collapseAll()">Collapse all</button>
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [groupBy]="groupBy"
      [(groupRowsState)]="groupRowsState"
    >
      <infinite-table
        debugId="row-grouping-state-controlled-example"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly groupBy = groupBy;

  // the grid writes the state back here when the user expands or collapses a group
  protected readonly groupRowsState = signal<
    DataSourcePropGroupRowsState<string>
  >(
    new GroupRowsState<string>({
      collapsedRows: true,
      expandedRows: [['Mexico'], ['Mexico', 'backend'], ['India']],
    }),
  );

  protected expandAll() {
    const newState = new GroupRowsState<string>(this.groupRowsState());
    newState.expandAll();
    this.groupRowsState.set(newState);
  }

  protected collapseAll() {
    const newState = new GroupRowsState<string>(this.groupRowsState());
    newState.collapseAll();
    this.groupRowsState.set(newState);
  }
}
```

In addition to simple objects with the shape described above, the [`[(groupRowsState)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupRowsState)/[`defaultGroupRowsState`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultGroupRowsState) can also be instanges of `GroupRowsState` class, which is exported by the Infinite Table package. This class is simply a wrapper around those objects, but it gives you additional utility methods.

The [`(groupRowsStateChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onGroupRowsStateChange) callback gives you an instance of [`GroupRowsState`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#GroupRowsState) back as the single argument. If you're using plain objects, just do `groupRowsState.getState()` and you'll get the corresponding plain object for the current expand/collapse state.

[`GroupRowsState`](https://infinite-table.com/docs/reference/type-definitions/index.md#GroupRowsState) give you some additional helper methods, which you can read about [here](https://infinite-table.com/docs/reference/type-definitions/index.md#GroupRowsState)

Type the signal as `DataSourcePropGroupRowsState`, as the example above does: it's the type of the model, a `GroupRowsState` instance or a plain object, so the grid can write its `GroupRowsState` back to the signal. `new GroupRowsState(state)` accepts both.

## Grouping strategies

Multiple grouping strategies are supported by, `InfiniteTable` DataGrid:

- multi column mode - multiple group columns are generated, one for each specified group field
- single column mode - a single group column is generated, even when there are multiple group fields

You can specify the rendering strategy explicitly by setting the [`groupRenderStrategy`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupRenderStrategy) property to any of the following: `multi-column`, `single-column`. If you don't set it explicitly, it will choose the best default based on your configuration.

### Multiple groups columns

When grouping by multiple fields, by default the component will render a group column for each group field

```ts
const groupBy: DataSourcePropGroupBy<Developer> = [
  {
    field: 'age',
    column: {
      defaultWidth: 100,
      renderValue: ({ value }) => `Age: ${value}`,
    },
  },
  {
    field: 'companyName',
  },
  {
    field: 'country',
  },
];
```

Let's see an example of how the component would render the table with the multi-column strategy.

**Example: Multi-column group render strategy**

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

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropGroupBy,
  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: 'age',
    column: {
      renderGroupValue: ({ value }: { value: any }) => `Age: ${value}`,
    },
  },
  {
    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 + '/developers10k')
    .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"
    >
      <infinite-table
        debugId="row-grouping-multi-column-example"
        [columns]="columns"
        [columnDefaultWidth]="150"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly groupBy = groupBy;
}
```

For the `multi-column` strategy, you can use [`hideEmptyGroupColumns`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#hideEmptyGroupColumns) in order to hide columns for groups which are currently not visible.

**Example: Hide Empty Group Columns**

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

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropGroupBy,
  DataSourcePropGroupRowsState,
  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: 'stack',
  },
  {
    field: 'preferredLanguage',
  },
];

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

const groupRowsState: DataSourcePropGroupRowsState = {
  expandedRows: [],
  collapsedRows: true,
};

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 + '/developers10')
    .then((r) => r.json())
    .then((data: Developer[]) => data);
};

@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="padding: 10px">
        <label>
          <input
            type="checkbox"
            [checked]="hideEmptyGroupColumns()"
            (change)="hideEmptyGroupColumns.set(!hideEmptyGroupColumns())"
          />
          Hide Empty Group Columns (make sure all \`Stack\` groups are
          collapsed to see it in action). Try to expand the group column to see
          the new group column being added on-the-fly.
        </label>
      </div>
      <infinite-data-source
        [data]="dataSource"
        primaryKey="id"
        [defaultGroupRowsState]="groupRowsState"
        [groupBy]="groupBy"
      >
        <infinite-table
          debugId="hideEmptyGroupColumns-example"
          [domProps]="domProps"
          [hideEmptyGroupColumns]="hideEmptyGroupColumns()"
          groupRenderStrategy="multi-column"
          [columns]="columns"
          [columnDefaultWidth]="250"
        />
      </infinite-data-source>
    </div>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly groupBy = groupBy;
  protected readonly groupRowsState = groupRowsState;
  protected readonly domProps = domProps;

  protected readonly hideEmptyGroupColumns = signal(true);
}
```

You can specify an `id` for group columns. This is helpful if you want to size those columns (via [`[(columnSizing)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columnSizing)) or pin them (via [`[(columnPinning)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columnPinning)) or configure them in other ways. If no `id` is specified, it will be generated like this: `"group-by-${field}"`

### Single group column

You can group by multiple fields, yet only render a single group column. To choose this rendering strategy, specify [`groupRenderStrategy`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupRenderStrategy) property to be `single-column` (or specify [`groupColumn`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupColumn) as an object.)

In this case, you can't override the group column for each group field, as there's only one group column being generated. However, you can specify a [`groupColumn`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupColumn) property to customize the generated column.

By default the generated group column will "inherit" many of the properties (the column style or className or renderers) of the columns corresponding to the group fields (if such columns exist, because it's not mandatory that they are defined).

**Example: Single-column group render strategy**

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

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

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

const groupBy: DataSourcePropGroupBy<Employee> = [
  {
    field: 'age',
  },
  {
    field: 'companyName',
  },
];

const groupColumn: InfiniteTableColumn<Employee> = {
  header: 'Grouping',
  defaultWidth: 250,
  // in this function we have access to collapsed info
  // and grouping info about the current row - see rowInfo.groupBy
  renderGroupValue: ({ value, rowInfo }) => {
    const groupBy = rowInfo.groupBy || [];
    const collapsed = rowInfo.collapsed;
    const currentGroupBy = groupBy[groupBy.length - 1];

    if (currentGroupBy?.field === 'age') {
      return `🥳 ${value}${collapsed ? ' 🤷‍♂️' : ''}`;
    }

    return `🎉 ${value}`;
  },
};

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

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

If [`groupColumn`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupColumn) is specified to an object and no [`groupRenderStrategy`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupRenderStrategy) is passed, the render strategy will be `single-column`.

[`groupColumn`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupColumn) can also be a function, which allows you to individually customize each group column - in case the `multi-column` strategy is used.

You can specify an `id` for the single [`groupColumn`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupColumn). This is helpful if you want to size this column (via [`[(columnSizing)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columnSizing)) or pin it (via [`[(columnPinning)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columnPinning)) or configure it in other ways. If no `id` is specified, it will default to `"group-by"`.

## Customizing the group column

There are many ways to customize the group column(s) and we're going to show a few of them below:

### Binding the group column to a `field`

By default, group columns only show values in the group rows - but they are normal columns, so why not bind them to a [field](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.field) of the `DATA_TYPE`?

```tsx
const groupColumn = {
  id: 'the-group', // can specify an id
  style: {
    color: 'tomato',
  },
  field: 'firstName', // non-group rows will render the first name
};
const columns = {
  theFirstName: {
    field: 'firstName',
    style: {
      // this style will also be applied in the group column,
      // since it is bound to this same `field`
      fontWeight: 'bold',
    },
  },
};
```

This makes the column display the value of the `field` in non-group/normal rows, and in nested group rows when using multi-column grouping. Pivoted grids only render group rows, so that nested-row path is how a bound field still shows — indented one extra nesting level, like a leaf. With [`groupRenderStrategy`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupRenderStrategy) set to `single-column`, the deepest (leaf) group rows in a pivot get that same extra indent. The field does not have to be a grouping key: nested rows show it when every item in the group has the same value (aggregators still win when the field is aggregated). Also, if you have another column bound to that `field`, the renderers/styling of that column will be used for the value of the group column, in those rows.

**Example: Bind group column to a field**

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

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

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

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
  },
  theFirstName: {
    field: 'firstName',
    style: {
      color: 'orange',
    },
    renderLeafValue: ({ value }) => {
      return `${value}!`;
    },
  },
  stack: {
    field: 'stack',
    style: {
      color: 'tomato',
    },
  },
  age: { field: 'age' },
  salary: {
    field: 'salary',
    type: 'number',
  },
  canDesign: { field: 'canDesign' },
};

const groupColumn = {
  field: 'firstName' as keyof Developer,
};

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

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;
};

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

### Use `groupColumn` to customize rendering

The [`groupColumn`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupColumn) will inherit its own rendering and styling from the columns that are bound to the fields used in [`groupBy.field`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy.field). However, you can override any of those properties so you have full control over the rendering process.

```tsx
const groupColumn: InfiniteTablePropGroupColumn<Developer> = {
  field: 'firstName',
  renderGroupValue: ({ value }) => {
    return `Group: ${value}`;
  },
  renderLeafValue: ({ value }) => {
    return `First name: ${value}`;
  },
};
```

The column that renders the `firstName` has a custom renderer that adds a `.` at the end.
The group column is bound to the same `firstName` field, but specifies a different renderer, which will be used instead.

**Example: Customize group column renderer**

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

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type {
  DataSourcePropGroupBy,
  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 groupBy: DataSourcePropGroupBy<Developer> = [
  {
    field: 'stack',
  },
  {
    field: 'preferredLanguage',
  },
];

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
  },
  firstName: {
    field: 'firstName',
    style: {
      color: 'orange',
    },
    renderValue: ({ value, rowInfo }) =>
      rowInfo.isGroupRow ? null : `${value}.`,
  },
  stack: {
    field: 'stack',
    style: {
      color: 'tomato',
    },
  },
  age: { field: 'age' },
  salary: {
    field: 'salary',
    type: 'number',
  },
  canDesign: { field: 'canDesign' },
};

const groupColumn: InfiniteTableColumn<Developer> = {
  field: 'firstName',
  renderValue: ({ value }) => {
    return `First name: ${value}`;
  },
};

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">
      <infinite-table
        debugId="group-column-custom-renderers-example"
        [groupColumn]="groupColumn"
        [columns]="columns"
        [columnDefaultWidth]="250"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly groupBy = groupBy;
  protected readonly groupColumn = groupColumn;
}
```

Learn more about customizing column rendering via multiple renderer functions.

## Hiding columns when grouping

When grouping is enabled, you can choose to hide some columns. Here are the two main ways to do this:

- use [`hideColumnWhenGrouped`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#hideColumnWhenGrouped) - this will make columns bound to the group fields be hidden when grouping is active
- use [`columns.defaultHiddenWhenGroupedBy`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.defaultHiddenWhenGroupedBy) (also available on the column types, as [`columnTypes.defaultHiddenWhenGroupedBy`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columnTypes.defaultHiddenWhenGroupedBy)) - this is a column-level property, so you have more fine-grained control over what is hidden and when.

Valid values for [`columns.defaultHiddenWhenGroupedBy`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.defaultHiddenWhenGroupedBy) are:

- `"*"` - when any grouping is active, hide the column that specifies this property
- `true` - when the field this column is bound to is used in grouping, hides this column
- `keyof DATA_TYPE` - specify an exact field that, when grouped by, makes this column be hidden
- `{[k in keyof DATA_TYPE]: true}` - an object that can specify more fields. When there is grouping by any of those fields, the current column gets hidden.

In this example, the column bound to `firstName` field is set to hide when any grouping is active, since the group column is anyways found to the `firstName` field.

In addition, [`hideColumnWhenGrouped`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#hideColumnWhenGrouped) is set to `true`, so the `stack` and `preferredLanguage` columns are also hidden, since they are grouped by.

**Example: Hide columns when grouping**

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

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

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

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
  },
  theFirstName: {
    field: 'firstName',
    style: {
      color: 'orange',
    },
    // hide this column when grouping active
    // as the group column is anyways bound to this field
    defaultHiddenWhenGroupedBy: '*',
  },
  stack: {
    field: 'stack',
    style: {
      color: 'tomato',
    },
  },
  preferredLanguage: { field: 'preferredLanguage' },
  age: { field: 'age' },
  salary: {
    field: 'salary',
    type: 'number',
  },
  canDesign: { field: 'canDesign' },
};

const groupColumn = {
  field: 'firstName' as keyof Developer,
};

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

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;
};

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

## Sorting the group column

When [groupRenderStrategy="single-column"](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupRenderStrategy) is used, the group column is sortable by default if all the columns that are involved in grouping are sortable. Sorting the group column makes the `sortInfo` have a value that looks like this:

```ts
const sortInfo = [
  {
    dir: 1,
    id: 'group-by',
    field: ['stack', 'age'],
    type: ['string', 'number'],
  },
];
```

To start with that sort, `{ id: 'group-by', dir: 1 }` is enough — `field` is filled in from [`[(groupBy)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#groupBy), and the sort type is taken from the [`columns`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns) bound to those fields.

[groupRenderStrategy="multi-column"](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#groupRenderStrategy), each group column is sortable by default if the column with the corresponding field is sortable.

 

The [`columnDefaultSortable`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columnDefaultSortable) property can be used to override the default behavior.

 

**Example: Group column with initial descending sorting**

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

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

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

const columns: InfiniteTablePropColumns<Developer> = {
  country: {
    field: 'country',
  },
  theFirstName: {
    field: 'firstName',
    style: {
      color: 'orange',
    },
    // hide this column when grouping active
    // as the group column is anyways bound to this field
    defaultHiddenWhenGroupedBy: '*',
  },
  stack: {
    field: 'stack',
    style: {
      color: 'tomato',
    },
  },
  preferredLanguage: { field: 'preferredLanguage' },
  age: { field: 'age' },
  salary: {
    field: 'salary',
    type: 'number',
  },
  canDesign: { field: 'canDesign' },
};

const groupColumn = {
  field: 'firstName' as keyof Developer,
};

const defaultSortInfo: DataSourcePropSortInfo<Developer> = [
  {
    field: ['stack', 'preferredLanguage'],
    dir: -1,
    id: 'group-by',
  },
];

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

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;
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [defaultSortInfo]="defaultSortInfo"
      [groupBy]="groupBy"
    >
      <infinite-table
        debugId="group-column-sorted-initially-example"
        [groupColumn]="groupColumn"
        [columns]="columns"
        [hideColumnWhenGrouped]="true"
        [columnDefaultWidth]="250"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly columns = columns;
  protected readonly dataSource = dataSource;
  protected readonly defaultSortInfo = defaultSortInfo;
  protected readonly groupBy = groupBy;
  protected readonly groupColumn = groupColumn;
}
```

When a group column is configured and the `groupBy` fields are not bound to actual columns in the table, the group column will not be sortable by default.

If you want to make it sortable, you have to specify a [`columns.sortType`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#columns.sortType) array, of the same length as the `groupBy` array, that specifies the sort type for each group field.

## Aggregations

When grouping, you can also aggregate the values of the grouped rows. This is done via the [DataSource.aggregationReducers](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#aggregationReducers) property. See the example below

**Example: Grouping with aggregations**

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

import {
  DataSource,
  GroupRowsState,
  InfiniteTable,
} from '@infinite-table/infinite-angular';
import type {
  DataSourceGroupBy,
  DataSourcePropAggregationReducers,
  InfiniteTableColumn,
  InfiniteTableColumnRenderValueParam,
  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 avgReducer = {
  initialValue: 0,
  reducer: (acc: number, sum: number) => acc + sum,
  done: (value: number, arr: any[]) =>
    arr.length ? Math.floor(value / arr.length) : 0,
};
const aggregationReducers: DataSourcePropAggregationReducers<Developer> = {
  salary: {
    field: 'salary',

    ...avgReducer,
  },
  age: {
    field: 'age',
    ...avgReducer,
  },
};

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' },
};
const groupColumn: InfiniteTableColumn<Developer> = {
  header: 'Grouping',
  defaultWidth: 250,

  // in this function we have access to collapsed info
  // and grouping info about the current row - see rowInfo.groupBy
  renderValue: ({
    value,
    rowInfo,
  }: InfiniteTableColumnRenderValueParam<Developer>) => {
    if (!rowInfo.isGroupRow) {
      return value;
    }
    const groupBy = rowInfo.groupBy || [];
    const collapsed = rowInfo.collapsed;
    const currentGroupBy = groupBy[groupBy.length - 1];

    if (currentGroupBy?.field === 'age') {
      return `🥳 ${value}${collapsed ? ' 🤷‍♂️' : ''}`;
    }

    return `🎉 ${value}`;
  },
};

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

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

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

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [defaultGroupRowsState]="defaultGroupRowsState"
      [aggregationReducers]="aggregationReducers"
      [groupBy]="groupBy"
    >
      <infinite-table
        debugId="grouping-with-aggregations-example"
        groupRenderStrategy="single-column"
        [groupColumn]="groupColumn"
        [columns]="columns"
        [columnDefaultWidth]="150"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly groupBy = groupBy;
  protected readonly groupColumn = groupColumn;
  protected readonly aggregationReducers = aggregationReducers;
  protected readonly defaultGroupRowsState = defaultGroupRowsState;
}
```

Each [reducer](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#aggregationReducers) from the `aggregationReducers` map can have the following properties:

- `field` - the field to aggregate on
- `getter(data)` - a value-getter function, if the aggregation values are are not mapped directly to a `field`
- `initialValue` - the initial value to start with when computing the aggregation (for client-side aggregations only)
- `reducer: string | (acc, current, data: DATA_TYPE, index)=>value` - the reducer function to use when computing the aggregation (for client-side aggregations only). For server-side aggregations, this will be a `string`
- `done(value, arr)` - a function that is called when the aggregation is done (for client-side aggregations only) and returns the final value of the aggregation
- `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.

If an aggregation reducer is bound to a `field` in the dataset, and there is a column mapped to the same `field`, that column will show the corresponding aggregation value for each group row, as shown in the example above.

If you want to prevent the user to expand the last level of group rows, you can override the `render` function for the group column

**Example: Customized group expand on last group level**

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

import {
  DataSource,
  GroupRowsState,
  InfiniteTable,
} from '@infinite-table/infinite-angular';
import type {
  DataSourceGroupBy,
  DataSourcePropAggregationReducers,
  InfiniteTableColumnCellContextType,
  InfiniteTableGroupColumnBase,
  InfiniteTableGroupColumnFunction,
  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 avgReducer = {
  initialValue: 0,
  reducer: (acc: number, sum: number) => acc + sum,
  done: (value: number, arr: any[]) =>
    arr.length ? Math.floor(value / arr.length) : 0,
};
const aggregationReducers: DataSourcePropAggregationReducers<Developer> = {
  salary: {
    field: 'salary',

    ...avgReducer,
  },
  age: {
    field: 'age',
    ...avgReducer,
  },
};

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' },
};

const groupColumn: InfiniteTableGroupColumnFunction<Developer> = (arg) => {
  const column = {} as Partial<InfiniteTableGroupColumnBase<Developer>>;

  if (arg.groupIndexForColumn === arg.groupBy.length - 1) {
    column.render = (param: InfiniteTableColumnCellContextType<Developer>) => {
      const { value, rowInfo } = param;
      if (
        rowInfo.isGroupRow &&
        rowInfo.groupBy?.length != rowInfo.rootGroupBy?.length
      ) {
        // we are on a group row that is the last grouping level
        return null;
      }
      return value;
    };
  }
  return column;
};

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

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

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

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [defaultGroupRowsState]="defaultGroupRowsState"
      [aggregationReducers]="aggregationReducers"
      [groupBy]="groupBy"
    >
      <infinite-table
        debugId="grouping-with-aggregations-discard-expand-example"
        groupRenderStrategy="multi-column"
        [groupColumn]="groupColumn"
        [columns]="columns"
        [columnDefaultWidth]="250"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
  protected readonly groupBy = groupBy;
  protected readonly groupColumn = groupColumn;
  protected readonly aggregationReducers = aggregationReducers;
  protected readonly defaultGroupRowsState = defaultGroupRowsState;
}
```

Dive deeper into the aggregation reducers and how they work.

## Server side grouping with lazy loading

Lazy loading becomes all the more useful when working with grouped data.

The `DataSource` [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function is called with an object that has all the information about the current `DataSource` state(grouping/pivoting/sorting/lazy-loading, etc) - see the paragraphs above for details.

Server side grouping needs two kinds of data responses in order to work properly:

- response for **non-leaf row groups** - these are groups that have children. For such groups (including the top-level group), the `DataSource.data` function must return a promise that's resolved to an object with the following properties:
  - `totalCount` - the total number of records in the group
  - `data` - an array of objects that describes non-leaf child groups, each object has the following properties:
    - `keys` - an array of the group keys (usually strings) that uniquely identifies the group, from the root to the current group
    - `data` - an object that describes the common properties of the group
    - `aggregations` - an object that describes the aggregations for the current group
    - `totalChildrenCount` - optional - the number of leaf rows in the group, at any depth. Multiple row selection uses it to render the checkbox of a group whose rows are not loaded.
    - `totalChildrenCountUnfiltered` - optional - the same count, without the filter. See [lazy selection with a filter](https://infinite-table.com/angular/docs/learn/selection/row-selection.md#multi-selection-with-lazy-load-and-grouping).
  - `totalChildrenCount` - optional, for the top-level group - the number of all leaf rows. Multiple row selection uses it for the header checkbox.
  - `totalChildrenCountUnfiltered` - optional, for the top-level group - the number of all leaf rows, without the filter
- response for **leaf rows** - these are normal rows - rows that would have been served in the non-grouped response. The resolved object should have the following properties:
  - `data` - an array of objects that describes the rows
  - `totalCount` - the total number of records on the server, that are part of the current group

Here's an example, that assumes grouping by `country` and `city` and aggregations by `age` and `salary` (average values):

```tsx
//request:
groupKeys: [] // empty keys array, so it's a top-level group
groupBy: [{"field":"country"},{"field":"city"}]
reducers: [{"field":"salary","id":"avgSalary","name":"avg"},{"field":"age","id":"avgAge","name":"avg"}]
// lazyLoadStartIndex: 0, - passed if lazyLoad is configured with a batchSize
// lazyLoadBatchSize: 20 - passed if lazyLoad is configured with a batchSize

//response
const response: DataSourceRemoteData<Developer> = {
  cache: true,
  totalCount: 20,
  data: [
    {
      data: {country: "Argentina"},
      aggregations: {avgSalary: 20000, avgAge: 30},
      keys: ["Argentina"],
    },
    {
      data: {country: "Australia"},
      aggregations: {avgSalary: 25000, avgAge: 35},
      keys: ["Australia"],
    }
    //...
  ]
}
```

Now let's expand the first group and see how the request/response would look like:

```tsx

//request:
groupKeys: ["Argentina"]
groupBy: [{"field":"country"},{"field":"city"}]
reducers: [{"field":"salary","id":"avgSalary","name":"avg"},{"field":"age","id":"avgAge","name":"avg"}]

//response
const response: DataSourceRemoteData<Developer> = {
  totalCount: 4,
  data: [
    {
      data: {country: "Argentina", city: "Buenos Aires"},
      aggregations: {avgSalary: 20000, avgAge: 30},
      keys: ["Argentina", "Buenos Aires"],
    },
    {
      data: {country: "Argentina", city: "Cordoba"},
      aggregations: {avgSalary: 25000, avgAge: 35},
      keys: ["Argentina", "Cordoba"],
    },
    //...
  ]
}
```

Finally, let's have a look at the leaf/normal rows and a request for them:

```tsx

//request
groupKeys: ["Argentina","Buenos Aires"]
groupBy: [{"field":"country"},{"field":"city"}]
reducers: [{"field":"salary","id":"avgSalary","name":"avg"},{"field":"age","id":"avgAge","name":"avg"}]

//response
const response: DataSourceRemoteData<Developer> = {
  totalCount: 20,
  data: [
    {
      id: 34,
      country: "Argentina",
      city: "Buenos Aires",
      age: 30,
      salary: 20000,
      stack: "full-stack",
      firstName: "John",
      //...
    },
    {
      id: 35,
      country: "Argentina",
      city: "Buenos Aires",
      age: 35,
      salary: 25000,
      stack: "backend",
      firstName: "Jane",
      //...
    },
    //...
  ]
}
```

When a row group is expanded, since `InfiniteTable` has the group `keys` from the previous response when the node was loaded, it will use the `keys` array and pass them to the `DataSource.data` function when requesting for the children of the respective group.

You know when to serve last-level rows, because in that case, the length of the `groupKeys` array will be equal to the length of the `groupBy` array.

**Example: Server side grouping with lazy loding**

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

import {
  InfiniteTable,
  DataSource,
  GroupRowsState,
} from '@infinite-table/infinite-angular';
import type {
  DataSourceData,
  InfiniteTablePropColumns,
  DataSourceGroupBy,
  DataSourcePropAggregationReducers,
} 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 aggregationReducers: DataSourcePropAggregationReducers<Developer> = {
  salary: {
    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' },
};

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

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

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

  lazyLoadStartIndex,
  lazyLoadBatchSize,
  groupKeys = [],
  sortInfo,
}) => {
  if (sortInfo && !Array.isArray(sortInfo)) {
    sortInfo = [sortInfo];
  }
  const startLimit: string[] = [];
  if (lazyLoadBatchSize && lazyLoadBatchSize > 0) {
    const start = lazyLoadStartIndex || 0;
    startLimit.push(`start=${start}`);
    startLimit.push(`limit=${lazyLoadBatchSize}`);
  }
  const args = [
    ...startLimit,
    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,
    sortInfo
      ? 'sortInfo=' +
        JSON.stringify(
          sortInfo.map((s) => ({
            field: s.field,
            dir: s.dir,
          })),
        )
      : 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 + `/developers30k-sql?` + args,
  ).then((r) => r.json());
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      primaryKey="id"
      [data]="dataSource"
      [groupBy]="groupBy"
      [aggregationReducers]="aggregationReducers"
      [defaultGroupRowsState]="groupRowsState"
      [lazyLoad]="true"
    >
      <infinite-table
        debugId="server-side-grouping-with-lazy-load-example"
        [scrollStopDelay]="10"
        [hideEmptyGroupColumns]="true"
        [columns]="columns"
        [columnDefaultWidth]="220"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly aggregationReducers = aggregationReducers;
  protected readonly columns = columns;
  protected readonly dataSource = dataSource;
  protected readonly groupBy = groupBy;
  protected readonly groupRowsState = groupRowsState;
}
```

## Eager loading for group row nodes

When using lazy-loading together with batching, node data (without children) is loaded when a node (normal or grouped) comes into view. Only when a group node is expanded will its children be loaded. However, you can do this loading eagerly, by using the `dataset` property on the node you want to load.

This can be useful in combination with using `dataParams.groupRowsState` from the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function - so your datasource can know which groups are expanded, and thus it can serve those groups already loaded with children.

```tsx
//request:
groupKeys: [] // empty keys array, so it's a top-level group
groupBy: [{"field":"country"},{"field":"city"}]
reducers: [{"field":"salary","id":"avgSalary","name":"avg"},{"field":"age","id":"avgAge","name":"avg"}]
// lazyLoadStartIndex: 0, - passed if lazyLoad is configured with a batchSize
// lazyLoadBatchSize: 20 - passed if lazyLoad is configured with a batchSize

//response
const response: DataSourceRemoteData<Developer> = {
  cache: true,
  totalCount: 20,
  data: [
    {
      data: {country: "Argentina"},
      aggregations: {avgSalary: 20000, avgAge: 30},
      keys: ["Argentina"],
      // NOTE this dataset property used for eager-loading of group nodes
      dataset: {
        // the shape of the dataset is the same as the one normally returned by the datasource
        cache: true,
        totalCount: 4,
        data: [
          {
            data: {country: "Argentina", city: "Buenos Aires"},
            aggregations: {avgSalary: 20000, avgAge: 30},
            keys: ["Argentina", "Buenos Aires"],
          },
          {
            data: {country: "Argentina", city: "Cordoba"},
            aggregations: {avgSalary: 25000, avgAge: 35},
            keys: ["Argentina", "Cordoba"],
          },
        ]
      }
    },
    {
      data: {country: "Australia"},
      aggregations: {avgSalary: 25000, avgAge: 35},
      keys: ["Australia"],
    }
    //...
  ]
}
```
