# Master Detail - Collapsing and Expanding Rows

> Learn how to use master-detail and configure the state of the row details as expanded or collapsed

Canonical page: https://infinite-table.com/angular/docs/learn/master-detail/collapsing-and-expanding-rows

You can control the collapsed/expanded state of rows in the master-detail configuration.

By default, all row details are collapsed. You can very easily change this by using the [`defaultRowDetailState`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#defaultRowDetailState) prop.

```ts
const defaultRowDetailState: RowDetailStateObject = {
  collapsedRows: true,
  expandedRows: [39, 54],
};

// <infinite-table
//   [columns]="columns"
//   [defaultRowDetailState]="defaultRowDetailState"
//   [rowDetailRenderer]="renderDetail"
// />
```

Some of the rows in the master DataGrid are expanded by default.

Also, we have a default sort defined, by the `country` and `city` columns.

**Example: Master detail DataGrid with some row details expanded by default**

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

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

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

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

  salary: number;
};

type City = {
  id: number;
  name: string;
  country: string;
};

const masterColumns: InfiniteTablePropColumns<City> = {
  id: {
    field: 'id',
    header: 'ID',
    defaultWidth: 70,
    renderRowDetailIcon: true,
  },
  country: { field: 'country', header: 'Country' },
  city: { field: 'name', header: 'City', defaultFlex: 1 },
};

const detailColumns: InfiniteTablePropColumns<Developer> = {
  firstName: {
    field: 'firstName',
    header: 'First Name',
  },
  salary: {
    field: 'salary',
    type: 'number',
  },

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

const domProps = {
  style: {
    height: '100%',
  },
};
const shouldReloadData = {
  sortInfo: true,
  filterValue: true,
};

const defaultRowDetailState = {
  collapsedRows: true as const,
  expandedRows: [39, 54],
};

// fetch an array of cities from the server
const citiesDataSource: DataSourceData<City> = () => {
  const cityNames = new Set<string>();
  const result: City[] = [];
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql`)
    .then((response) => response.json())
    .then((response) => {
      response.data.forEach((data: Developer) => {
        if (cityNames.has(data.city)) {
          return;
        }
        cityNames.add(data.city);
        result.push({
          name: data.city,
          country: data.country,
          id: result.length,
        });
      });

      return result;
    });
};

const detailDataSource: DataSourceData<Developer> = ({
  filterValue,
  sortInfo,
  masterRowInfo,
}) => {
  if (sortInfo && !Array.isArray(sortInfo)) {
    sortInfo = [sortInfo];
  }

  if (!filterValue) {
    filterValue = [];
  }
  if (masterRowInfo) {
    // filter by master country and city
    filterValue = [
      {
        field: 'city',
        filter: {
          operator: 'eq',
          type: 'string',
          value: masterRowInfo.data.name,
        },
      },
      {
        field: 'country',
        filter: {
          operator: 'eq',
          type: 'string',
          value: masterRowInfo.data.country,
        },
      },
      ...filterValue,
    ];
  }
  const args = [
    sortInfo
      ? 'sortInfo=' +
        JSON.stringify(
          sortInfo.map((s) => ({
            field: s.field,
            dir: s.dir,
          })),
        )
      : null,

    filterValue
      ? 'filterBy=' +
        JSON.stringify(
          filterValue.map(({ field, filter }) => {
            return {
              field: field,
              operator: filter.operator,
              value:
                filter.type === 'number' ? Number(filter.value) : filter.value,
            };
          }),
        )
      : null,
  ]
    .filter(Boolean)
    .join('&');

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

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source
      [data]="citiesDataSource"
      primaryKey="id"
      [defaultSortInfo]="[
        {
          field: 'country',
          dir: 1,
        },
        {
          field: 'name',
          dir: 1,
        },
      ]"
    >
      <infinite-table
        debugId="master-detail-default-expanded-example-2"
        [domProps]="domProps"
        [columnDefaultWidth]="150"
        [columnMinWidth]="50"
        [defaultRowDetailState]="defaultRowDetailState"
        [columns]="masterColumns"
        [rowDetailHeight]="200"
        [rowDetailRenderer]="renderDetail"
      />
    </infinite-data-source>

    
    <ng-template #detail>
      <infinite-data-source
        [data]="detailDataSource"
        primaryKey="id"
        [shouldReloadData]="shouldReloadData"
      >
        <infinite-table
          debugId="master-detail-default-expanded-example"
          [columnDefaultWidth]="150"
          [columnMinWidth]="50"
          [columns]="detailColumns"
        />
      </infinite-data-source>
    </ng-template>
  `,
})
export default class App {
  protected readonly citiesDataSource = citiesDataSource;
  protected readonly detailDataSource = detailDataSource;
  protected readonly masterColumns = masterColumns;
  protected readonly detailColumns = detailColumns;
  protected readonly domProps = domProps;
  protected readonly shouldReloadData = shouldReloadData;
  protected readonly defaultRowDetailState = defaultRowDetailState;

  private readonly detailTemplate =
    viewChild.required<TemplateRef<unknown>>('detail');

  // a field, so the grid gets the same function every time
  protected readonly renderDetail = (rowInfo: InfiniteTableRowInfo<City>) => {
    console.log('rendering detail for master row', rowInfo.id);
    return this.detailTemplate();
  };
}
```

## Understanding and defining the collapse/expand state for row details

When you want to specify a different collapse/expand state of the row details (since by default they are all collapsed, and you might want to expand some of them), you need to use the [`defaultRowDetailState`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#defaultRowDetailState) prop, or its controlled counterpart - the [`[(rowDetailState)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailState) prop.

The [row detail state](https://infinite-table.com/docs/reference/type-definitions/index.md#RowDetailState) can be defined in two ways:

- either specify `collapsedRows: true` (which means all rows are collapsed by default) and specify an array of `expandedRows`, which will contain the ids of the rows that should be rendered as expanded.

```tsx
const defaultRowDetailState = {
  collapsedRows: true,
  expandedRows: ['id-1', 'id-2', 'id-56'],
};
```

- or specify `expandedRows: true` (which means all rows are expanded by default) and specify an array of `collapsedRows`, which will contain the ids of the rows that should be rendered as collapsed.

```tsx
const rowDetailState = {
  expandedRows: true,
  collapsedRows: ['id-1', 'id-2', 'id-56'],
};
```

You can pass these objects into either the [`defaultRowDetailState`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#defaultRowDetailState) (uncontrolled) or the [`[(rowDetailState)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailState) (controlled).

[`[(rowDetailState)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailState) is a model: the grid writes the state back when the user expands or collapses a row. Bind it two-way to a signal, or bind the input and update your signal from the [`(rowDetailStateChange)`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#onRowDetailStateChange) output, as the examples below do.

As an alternative to using the object literals as specified above, you can import the `RowDetailState` class from `@infinite-table/infinite-angular` and use it to define the state of the row details. You can pass instances of `RowDetailState` into the [`defaultRowDetailState`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#defaultRowDetailState) or [`[(rowDetailState)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailState) props.

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

const rowDetailState = new RowDetailState({
  collapsedRows: true,
  expandedRows: [2, 3, 4],
});

// <infinite-table [columns]="columns" [rowDetailState]="rowDetailState" />
```

```ts
<infinite-table
  [columns]="columns"
  [rowDetailState]="{
    collapsedRows: true,
    expandedRows: [2, 3, 4],
  }"
/>
```

See our type definitions for [more details on row detail state](https://infinite-table.com/docs/reference/type-definitions/index.md#RowDetailState).

Some of the rows in the master DataGrid are expanded by default.

We use the controlled [`[(rowDetailState)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailState) prop to manage the state of the row details and update it by using [`(rowDetailStateChange)`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#onRowDetailStateChange).

**Example: Master detail DataGrid with listener for row expand/collapse**

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

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

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

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

  salary: number;
};

type City = {
  id: number;
  name: string;
  country: string;
};

const masterColumns: InfiniteTablePropColumns<City> = {
  id: {
    field: 'id',
    header: 'ID',
    defaultWidth: 70,
    renderRowDetailIcon: true,
  },
  country: { field: 'country', header: 'Country' },
  city: { field: 'name', header: 'City', defaultFlex: 1 },
};

const detailColumns: InfiniteTablePropColumns<Developer> = {
  firstName: {
    field: 'firstName',
    header: 'First Name',
  },
  salary: {
    field: 'salary',
    type: 'number',
  },

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

const domProps = {
  style: {
    height: '100%',
  },
};
const shouldReloadData = {
  sortInfo: true,
  filterValue: true,
};

// fetch an array of cities from the server
const citiesDataSource: DataSourceData<City> = () => {
  const cityNames = new Set<string>();
  const result: City[] = [];
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql`)
    .then((response) => response.json())
    .then((response) => {
      response.data.forEach((data: Developer) => {
        if (cityNames.has(data.city)) {
          return;
        }
        cityNames.add(data.city);
        result.push({
          name: data.city,
          country: data.country,
          id: result.length,
        });
      });

      return result;
    });
};

const detailDataSource: DataSourceData<Developer> = ({
  filterValue,
  sortInfo,
  masterRowInfo,
}) => {
  if (sortInfo && !Array.isArray(sortInfo)) {
    sortInfo = [sortInfo];
  }

  if (!filterValue) {
    filterValue = [];
  }
  if (masterRowInfo) {
    // filter by master country and city
    filterValue = [
      {
        field: 'city',
        filter: {
          operator: 'eq',
          type: 'string',
          value: masterRowInfo.data.name,
        },
      },
      {
        field: 'country',
        filter: {
          operator: 'eq',
          type: 'string',
          value: masterRowInfo.data.country,
        },
      },
      ...filterValue,
    ];
  }
  const args = [
    sortInfo
      ? 'sortInfo=' +
        JSON.stringify(
          sortInfo.map((s) => ({
            field: s.field,
            dir: s.dir,
          })),
        )
      : null,

    filterValue
      ? 'filterBy=' +
        JSON.stringify(
          filterValue.map(({ field, filter }) => {
            return {
              field: field,
              operator: filter.operator,
              value:
                filter.type === 'number' ? Number(filter.value) : filter.value,
            };
          }),
        )
      : null,
  ]
    .filter(Boolean)
    .join('&');

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

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable, JsonPipe],
  template: `
    <div
      style="display: flex; flex-flow: row; color: var(--infinite-cell-color); background: var(--infinite-background); max-height: 200px; overflow: auto; gap: 10px"
    >
      <code style="padding-inline: 10px">
        <pre>Row detail state: {{ rowDetailState() | json }}</pre>
      </code>
      <div
        style="display: flex; gap: 10px; padding: 10px; align-items: flex-start"
      >
        <button (click)="api()?.rowDetailApi?.expandAllDetails()">
          Expand All
        </button>
        <button (click)="collapseAll()">Collapse All</button>
      </div>
    </div>
    <infinite-data-source
      [data]="citiesDataSource"
      primaryKey="id"
      [defaultSortInfo]="[
        {
          field: 'country',
          dir: 1,
        },
        {
          field: 'name',
          dir: 1,
        },
      ]"
    >
      <infinite-table
        debugId="master-detail-controlled-expanded-enhanced-example-2"
        [domProps]="domProps"
        (ready)="api.set($event.api)"
        [columnDefaultWidth]="150"
        [rowDetailState]="rowDetailState()"
        (rowDetailStateChange)="onRowDetailStateChange($event)"
        [columnMinWidth]="50"
        [columns]="masterColumns"
        [rowDetailHeight]="200"
        [rowDetailRenderer]="renderDetail"
      />
    </infinite-data-source>

    
    <ng-template #detail>
      <infinite-data-source
        [data]="detailDataSource"
        primaryKey="id"
        [shouldReloadData]="shouldReloadData"
      >
        <infinite-table
          debugId="master-detail-controlled-expanded-enhanced-example"
          [columnDefaultWidth]="150"
          [columnMinWidth]="50"
          [columns]="detailColumns"
        />
      </infinite-data-source>
    </ng-template>
  `,
})
export default class App {
  protected readonly citiesDataSource = citiesDataSource;
  protected readonly detailDataSource = detailDataSource;
  protected readonly masterColumns = masterColumns;
  protected readonly detailColumns = detailColumns;
  protected readonly domProps = domProps;
  protected readonly shouldReloadData = shouldReloadData;

  // controlled: the grid gets the state from this signal
  protected readonly rowDetailState = signal<RowDetailStateObject>({
    collapsedRows: true as const,
    expandedRows: [39, 54],
  });

  protected readonly api = signal<InfiniteTableApi<City> | null>(null);

  private readonly detailTemplate =
    viewChild.required<TemplateRef<unknown>>('detail');

  protected onRowDetailStateChange(
    rowDetailState: RowDetailState | RowDetailStateObject | undefined,
  ) {
    if (rowDetailState) {
      this.rowDetailState.set(
        rowDetailState instanceof RowDetailState
          ? rowDetailState.getState()
          : rowDetailState,
      );
    }
  }

  protected collapseAll() {
    // we could use the api to collapse all details
    // this.api()?.rowDetailApi.collapseAllDetails();
    // but we can also use the controlled input
    this.rowDetailState.set({
      collapsedRows: true,
      expandedRows: [],
    });
  }

  // a field, so the grid gets the same function every time
  protected readonly renderDetail = (rowInfo: InfiniteTableRowInfo<City>) => {
    console.log('rendering detail for master row', rowInfo.id);
    return this.detailTemplate();
  };
}
```

## Listening to row detail state changes

In order to be notified when the collapse/expand state of row details changes, you can use the [`(rowDetailStateChange)`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#onRowDetailStateChange) prop.

The output emits the new [`[(rowDetailState)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailState). Please note this is an instance of [`RowDetailState`](https://infinite-table.com/docs/reference/type-definitions/index.md#RowDetailState). If you want to use the object literal, make sure you call `getState()` on the instance of `RowDetailState`.

```ts
@Component({
  selector: 'master-detail',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source primaryKey="id" [data]="data">
      <infinite-table
        [rowDetailState]="rowDetailState()"
        (rowDetailStateChange)="onRowDetailStateChange($event)"
        [columnMinWidth]="50"
        [columns]="masterColumns"
        [rowDetailHeight]="200"
        [rowDetailRenderer]="renderDetail"
      />
    </infinite-data-source>
  `,
})
export class MasterDetail {
  protected readonly data = data;
  protected readonly masterColumns = masterColumns;
  protected readonly renderDetail = renderDetail;

  protected readonly rowDetailState = signal<RowDetailStateObject>({
    collapsedRows: true as const,
    expandedRows: [39, 54],
  });

  protected onRowDetailStateChange(
    rowDetailStateInstance: RowDetailState | RowDetailStateObject | undefined,
  ) {
    if (rowDetailStateInstance instanceof RowDetailState) {
      this.rowDetailState.set(rowDetailStateInstance.getState());
    }
  }
}
```

When using the controlled [`[(rowDetailState)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailState), the grid applies the user interaction itself and writes the new state back to the model. Use the [`(rowDetailStateChange)`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#onRowDetailStateChange) output to keep your own signal in sync - or to replace the new state with your own, as the single row expand example below does.

This allows you to manage the state of the row details yourself - making it easy to expand/collapse all rows, or to expand/collapse a specific row by simply updating the value of the [`[(rowDetailState)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailState) prop.

```ts
@Component({
  selector: 'expand-collapse-all',
  imports: [InfiniteTable],
  template: `
    <button (click)="expandAll()">Expand All</button>
    <button (click)="collapseAll()">Collapse All</button>
    <infinite-table [columns]="columns" [rowDetailState]="rowDetailState()" />
  `,
})
export class ExpandCollapseAll {
  protected readonly columns = columns;

  protected readonly rowDetailState = signal<RowDetailStateObject>({
    collapsedRows: true,
    expandedRows: [39, 54],
  });

  protected expandAll() {
    this.rowDetailState.set({
      collapsedRows: [],
      expandedRows: true,
    });
  }

  protected collapseAll() {
    this.rowDetailState.set({
      collapsedRows: true,
      expandedRows: [],
    });
  }
}
```

If you prefer the more imperative approach, you can still use the [Row Detail API](https://infinite-table.com/docs/reference/row-detail-api/index.md) to [expand](https://infinite-table.com/docs/reference/row-detail-api/index.md#expandRowDetail) or [collapse](https://infinite-table.com/docs/reference/row-detail-api/index.md#collapseRowDetail) details for rows.

## Single row expand

Using the controlled [`[(rowDetailState)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailState) prop is very powerful - it allows you to configure the expand state to only allow one row to be expanded at a time, if that's something you need.

This means that if any other row(s) are expanded and you expand a new row, the previously expanded rows will all be collapsed.

In this demo we allow only one row to be expanded at any given time.

We use the controlled [`[(rowDetailState)]`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailState) prop to manage the state of the row details and update it by using [`(rowDetailStateChange)`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#onRowDetailStateChange).

**Example: Master detail only one row expanded at a time**

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

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

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

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

  salary: number;
};

type City = {
  id: number;
  name: string;
  country: string;
};

const masterColumns: InfiniteTablePropColumns<City> = {
  id: {
    field: 'id',
    header: 'ID',
    defaultWidth: 70,
    renderRowDetailIcon: true,
  },
  country: { field: 'country', header: 'Country' },
  city: { field: 'name', header: 'City', defaultFlex: 1 },
};

const detailColumns: InfiniteTablePropColumns<Developer> = {
  firstName: {
    field: 'firstName',
    header: 'First Name',
  },
  salary: {
    field: 'salary',
    type: 'number',
  },

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

const domProps = {
  style: {
    height: '100%',
  },
};
const shouldReloadData = {
  sortInfo: true,
  filterValue: true,
};

// fetch an array of cities from the server
const citiesDataSource: DataSourceData<City> = () => {
  const cityNames = new Set<string>();
  const result: City[] = [];
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + `/developers1k-sql`)
    .then((response) => response.json())
    .then((response) => {
      response.data.forEach((data: Developer) => {
        if (cityNames.has(data.city)) {
          return;
        }
        cityNames.add(data.city);
        result.push({
          name: data.city,
          country: data.country,
          id: result.length,
        });
      });

      return result;
    });
};

const detailDataSource: DataSourceData<Developer> = ({
  filterValue,
  sortInfo,
  masterRowInfo,
}) => {
  if (sortInfo && !Array.isArray(sortInfo)) {
    sortInfo = [sortInfo];
  }

  if (!filterValue) {
    filterValue = [];
  }
  if (masterRowInfo) {
    // filter by master country and city
    filterValue = [
      {
        field: 'city',
        filter: {
          operator: 'eq',
          type: 'string',
          value: masterRowInfo.data.name,
        },
      },
      {
        field: 'country',
        filter: {
          operator: 'eq',
          type: 'string',
          value: masterRowInfo.data.country,
        },
      },
      ...filterValue,
    ];
  }
  const args = [
    sortInfo
      ? 'sortInfo=' +
        JSON.stringify(
          sortInfo.map((s) => ({
            field: s.field,
            dir: s.dir,
          })),
        )
      : null,

    filterValue
      ? 'filterBy=' +
        JSON.stringify(
          filterValue.map(({ field, filter }) => {
            return {
              field: field,
              operator: filter.operator,
              value:
                filter.type === 'number' ? Number(filter.value) : filter.value,
            };
          }),
        )
      : null,
  ]
    .filter(Boolean)
    .join('&');

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


@Component({
  selector: 'row-detail',
  imports: [DataSource, InfiniteTable],
  // laid out by the row detail element, as the grid would be
  host: { style: 'display: contents' },
  template: `
    @if (masterRowInfo()) {
      <infinite-data-source
        [data]="detailDataSource"
        primaryKey="id"
        [shouldReloadData]="shouldReloadData"
      >
        <infinite-table
          debugId="master-detail-one-expanded-row-example"
          [columnDefaultWidth]="150"
          [columnMinWidth]="50"
          [columns]="detailColumns"
        />
      </infinite-data-source>
    }
  `,
})
class RowDetail {
  protected readonly masterRowInfo = injectMasterRowInfo<City>();

  protected readonly detailDataSource = detailDataSource;
  protected readonly detailColumns = detailColumns;
  protected readonly shouldReloadData = shouldReloadData;

  constructor() {
    console.log('rendering detail for master row', this.masterRowInfo()?.id);
  }
}

const components = {
  RowDetail,
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <code
      style="padding: 10px; color: var(--infinite-cell-color); background: var(--infinite-background); max-height: 200px; overflow: auto"
    >
      <pre>Current expanded row: {{ currentExpandedRow() }}</pre>
    </code>
    <infinite-data-source
      [data]="citiesDataSource"
      primaryKey="id"
      [defaultSortInfo]="[
        {
          field: 'country',
          dir: 1,
        },
        {
          field: 'name',
          dir: 1,
        },
      ]"
    >
      <infinite-table
        debugId="master-detail-one-expanded-row-example-2"
        [domProps]="domProps"
        (ready)="onReady($event)"
        [columnDefaultWidth]="150"
        [rowDetailState]="rowDetailState()"
        (rowDetailStateChange)="onRowDetailStateChange($event)"
        [columnMinWidth]="50"
        [columns]="masterColumns"
        [components]="components"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly citiesDataSource = citiesDataSource;
  protected readonly masterColumns = masterColumns;
  protected readonly domProps = domProps;
  protected readonly components = components;

  protected readonly rowDetailState = signal<RowDetailStateObject<any>>({
    collapsedRows: true as const,
    expandedRows: [39],
  });

  protected readonly currentExpandedRow = computed(() => {
    const { expandedRows } = this.rowDetailState();
    return expandedRows === true ? '---' : expandedRows[0] ?? 'none';
  });

  protected onReady({ api }: { api: InfiniteTableApi<City> }) {
    console.log(api.rowDetailApi);
  }

  protected onRowDetailStateChange(
    newRowDetailState: RowDetailState | RowDetailStateObject | undefined,
  ) {
    if (!newRowDetailState) {
      return;
    }
    const newState =
      newRowDetailState instanceof RowDetailState
        ? newRowDetailState.getState()
        : newRowDetailState;

    const expandedRows =
      newState.expandedRows === true ? [] : newState.expandedRows;

    const rowDetailState = this.rowDetailState();
    const oldExpandedRows = new Set(
      rowDetailState.expandedRows === true ? [] : rowDetailState.expandedRows,
    );

    for (const row of expandedRows) {
      if (!oldExpandedRows.has(row)) {
        this.rowDetailState.set({
          collapsedRows: true,
          expandedRows: [row],
        });
        return;
      }
    }

    this.rowDetailState.set(newState);
  }
}
```
