# Master Detail with Custom Row Detail Contents

> Learn how to use master-detail to customise your row detail contents

Canonical page: https://infinite-table.com/angular/docs/learn/master-detail/custom-row-detail-content

The Infinite Table Angular DataGrid allows you to render any template as row details - the [`rowDetailRenderer`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailRenderer) function returns an `ng-template` of your component (a `TemplateRef`, read with `viewChild`), which gets the master row as its context (`let-rowInfo`), or a component (`renderComponent(MyRowDetail)`).

You can render a DataGrid directly or you can nest the DataGrid at any level of nesting inside the row details.
Or you can simply choose to render anything else - no DataGrid required.

## Rendering a detail DataGrid

Your row detail content can include another Infinite Table DataGrid.

The DataGrid you're rendering inside the row detail doesn't need to be the root of the template the [`rowDetailRenderer`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailRenderer) function returns - it can be nested inside other elements of that template.

In this example, the row detail contains custom content, along with another Infinite Table DataGrid. You can nest a child DataGrid inside the row details at any level of nesting.

**Example: Master detail with custom content & DataGrid**

```ts
import { Component, TemplateRef, viewChild } 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;

  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-custom-datagrid-example-2"
        [domProps]="domProps"
        [columnDefaultWidth]="150"
        [columnMinWidth]="50"
        [defaultRowDetailState]="defaultRowDetailState"
        [columns]="masterColumns"
        [rowDetailHeight]="320"
        [rowDetailRenderer]="renderDetail"
      />
    </infinite-data-source>

    
    <ng-template #detail let-rowInfo>
      <div
        style="padding: 10px; color: var(--infinite-cell-color); background: var(--infinite-background); height: 100%; display: flex; flex-direction: column"
      >
        <h3>Developers in {{ rowInfo.data?.name }}, {{ rowInfo.data?.country }}</h3>

        <infinite-data-source
          [data]="detailDataSource"
          primaryKey="id"
          [shouldReloadData]="shouldReloadData"
        >
          <infinite-table
            debugId="master-detail-custom-datagrid-example"
            [columnDefaultWidth]="150"
            [columnMinWidth]="50"
            [columns]="detailColumns"
          />
        </infinite-data-source>
      </div>
    </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
  // the template gets the row info as its context (let-rowInfo)
  protected readonly renderDetail = () => this.detailTemplate();
}
```

You'll probably want to configure the height of the row detail content. Use the [`rowDetailHeight`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#rowDetailHeight) prop to do that.

## Rendering a chart component as row detail

**Example: Retrieving cell selection value by mapping over them**

_React only for now:_

```tsx
import * as React from 'react';

import {
  DataSourceData,
  InfiniteTable,
  InfiniteTablePropColumns,
  DataSource,
  InfiniteTableRowInfo,
  InfiniteTable_HasGrouping_RowInfoGroup,
  DataSourcePropGroupBy,
  DataSourcePropAggregationReducers,
} from '@infinite-table/infinite-react';

import { AgCharts as AgChartsReact } from 'ag-charts-react';

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 domProps = {
  style: {
    height: '100%',
  },
};

function renderDetail(rowInfo: InfiniteTableRowInfo<City>) {
  const [groupBy] = React.useState<DataSourcePropGroupBy<Developer>>([
    { field: 'stack' },
  ]);
  const [aggregationReducers] = React.useState<
    DataSourcePropAggregationReducers<Developer>
  >({
    salary: {
      field: 'salary',
      initialValue: 0,
      reducer: (acc, value) => acc + value,
      done: (value, arr) => Math.round(arr.length ? value / arr.length : 0),
    },
  });
  return (
    <div
      style={{
        padding: 10,
        color: 'var(--infinite-cell-color)',
        background: 'var(--infinite-background)',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {/**
       * In this example, we leverage the DataSource aggregation and grouping feature to
       * calculate the average salary by stack for the selected city.
       */}
      <DataSource<Developer>
        data={detailDataSource}
        primaryKey="id"
        groupBy={groupBy}
        aggregationReducers={aggregationReducers}
      >
        {/**
         * Notice here we're not rendering an InfiniteTable component
         * but rather we use a render function to access the aggregated data.
         */}
        {(params) => {
          const { dataArray: rowInfoArray } = params;
          const groups = rowInfoArray.filter(
            (rowInfo) => rowInfo.isGroupRow,
          ) as InfiniteTable_HasGrouping_RowInfoGroup<Developer>[];
          const groupData = groups.map((group) => {
            return {
              stack: group.data?.stack,
              avgSalary: group.reducerData?.salary,
            };
          });

          return (
            <AgChartsReact
              options={{
                title: {
                  text: `Avg salary by stack in ${rowInfo.data?.name}, ${rowInfo.data?.country}`,
                },
                data: groupData,
                series: [
                  {
                    type: 'bar',
                    xKey: 'stack',
                    yKey: 'avgSalary',
                    yName: 'Average Salary',
                  },
                ],
              }}
            />
          );
        }}
      </DataSource>
    </div>
  );
}

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

export default () => {
  return (
    <>
      <DataSource<City>
        data={citiesDataSource}
        primaryKey="id"
        defaultSortInfo={[
          {
            field: 'country',
            dir: 1,
          },
          {
            field: 'name',
            dir: 1,
          },
        ]}
      >
        <InfiniteTable<City>
          debugId="master-detail-chart-detail-example"
          domProps={domProps}
          columnDefaultWidth={150}
          defaultRowDetailState={defaultRowDetailState}
          columnMinWidth={50}
          columns={masterColumns}
          rowDetailHeight={320}
          rowDetailRenderer={renderDetail}
        />
      </DataSource>
    </>
  );
};

// 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);
};
```

In the above example, please note that on every render (after the detail component is mounted), we pass the same `dataSource`, `groupBy` and `aggregationReducers` props to the `<DataSource />` component. The references for all those objects are stable. We don't want to pass new references on every render, as that would cause the `<DataSource />` to reload and reprocess the data.

## Multiple levels of nesting

The master-detail configuration for the DataGrid can contain any level of nesting.

The example below shows 3 levels of nesting - so a master DataGrid, a detail DataGrid and another third-level detail with custom content.

In this example, we have 3 levels of nesting:

- The master DataGrid shows cities/countries
- The first level of detail shows developers in each city
- The second level of detail shows custom data about each developer

**Example: Master detail with 3 levels of nesting**

```ts
import { Component, TemplateRef, viewChild } 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;

  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',
    renderRowDetailIcon: true,
  },
  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],
  styles: `
    .detail {
      padding: 10px;
      color: var(--infinite-cell-color);
      background: var(--infinite-background);
      height: 100%;
      display: flex;
      flex-direction: column;
    }
  `,
  template: `
    <infinite-data-source
      [data]="citiesDataSource"
      primaryKey="id"
      [defaultSortInfo]="[
        {
          field: 'country',
          dir: 1,
        },
        {
          field: 'name',
          dir: 1,
        },
      ]"
    >
      <infinite-table
        debugId="master-detail-3-levels-example-2"
        [domProps]="domProps"
        [columnDefaultWidth]="150"
        [defaultRowDetailState]="defaultRowDetailState"
        [columnMinWidth]="50"
        [columns]="masterColumns"
        [rowDetailHeight]="350"
        [rowDetailRenderer]="renderDetail"
      />
    </infinite-data-source>

    
    <ng-template #detail let-rowInfo>
      <div class="detail">
        <h3>Developers in {{ rowInfo.data?.name }}, {{ rowInfo.data?.country }}</h3>

        <infinite-data-source
          [data]="detailDataSource"
          primaryKey="id"
          [shouldReloadData]="shouldReloadData"
        >
          <infinite-table
            debugId="master-detail-3-levels-example"
            [columnDefaultWidth]="150"
            [columnMinWidth]="50"
            [columns]="detailColumns"
            [rowDetailHeight]="200"
            [rowDetailRenderer]="renderLastDetail"
          />
        </infinite-data-source>
      </div>
    </ng-template>

    <!-- third level: the details of a developer -->
    <ng-template #lastDetail let-rowInfo>
      @if (rowInfo.data; as data) {
        <div class="detail">
          <h3>Developer: {{ data.firstName }} {{ data.lastName }}</h3>
          <div style="display: grid; grid-template-columns: auto 1fr; gap: 10px">
            <div>Preferred Language</div>
            <div>{{ data.preferredLanguage }}</div>

            <div>Salary</div>
            <div>{{ data.salary }}</div>

            <div>Currency</div>
            <div>{{ data.currency }}</div>

            <div>Can Design</div>
            <div>{{ data.canDesign }}</div>
          </div>
        </div>
      } @else {
        <div>No data ...</div>
      }
    </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');
  private readonly lastDetailTemplate =
    viewChild.required<TemplateRef<unknown>>('lastDetail');

  // fields, so the grids get the same functions every time
  protected readonly renderDetail = () => this.detailTemplate();
  protected readonly renderLastDetail = () => this.lastDetailTemplate();
}
```

## Understanding the lifecycle of the row detail component

You have to keep in mind that the content you render in the row detail can be mounted and unmounted multiple times. Whenever the user expands the row detail, it gets mounted and rendered, but then it will be unmounted when the user scrolls the content out of view. This can happen very often.

Also note that the row detail element is recycled - it can be reused for different rows. When that happens, the content you render (the views of your template, or your component) is destroyed and created again for the new master row, so a component never shows the details of two different rows.

In practice this means that it's best if your row detail content is using controlled state and avoids using local state.
