# Getting Started

> Get started with Infinite Table for Angular. Our Angular DataGrid component helps with sorting, filtering, row/column grouping, pivoting, aggregations ...

Canonical page: https://infinite-table.com/angular/docs/learn/getting-started/

> `Infinite Table` is a UI component for data virtualization - helps you display huge datasets of tabular data.

`@infinite-table/infinite-angular` is Infinite Table for Angular: the same DataGrid, built from the same source and with the same focus on performance, as standalone Angular components with signal inputs, models and outputs.

# Installation

`Infinite Table` is available on the public [npm registry](https://www.npmjs.com/package/@infinite-table/infinite-angular) - install it by running the following command:

```bash
npm i @infinite-table/infinite-react
```

## Meet the Code

This is an example to get you started with Infinite Table with minimal setup. Click **edit** to change the code and see the grid update.

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

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

type Person = {
  Id: number;
  FirstName: string;
  Age: number;
};


const columns: InfiniteTablePropColumns<Person> = {
  id: {
    // specifies which field from the data source
    // should be rendered in this column
    field: 'Id',
    type: 'number',
    defaultWidth: 80,
  },

  firstName: {
    field: 'FirstName',
    header: 'First Name',
  },
  age: { field: 'Age', type: 'number' },
};

const data: Person[] = [
  {
    Id: 1,
    FirstName: 'Bob',
    Age: 3,
  },
  {
    Id: 2,
    FirstName: 'Alice',
    Age: 50,
  },
  {
    Id: 3,
    FirstName: 'Bill',
    Age: 5,
  },
];

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

Don't forget to add the CSS to your application's global styles to see the component in action - in the `styles` of the build options in `angular.json`, or at the top of `src/styles.css`:

```css
@import '@infinite-table/infinite-angular/index.css';
```

## Using the Components

In the code snippet above, you notice we're using 2 components:

- `DataSource` - this needs to be a parent (or ancestor, at any level) of the `InfiniteTable` component - it controls which `data` the table is rendering
- `InfiniteTable` - the actual virtualized table component - needs to be inside a `DataSource` (can be at any level of nesting).

Both components are named exports of the `@infinite-table/infinite-angular` package.

In a template they are the `<infinite-data-source>` and `<infinite-table>` elements: add both classes to the `imports` of your component.

## TypeScript Types

Our `TypeScript` types are published as part of the package, as named exports from the root of the package.

There are 2 components that you can use and import:

- `InfiniteTable`
- `DataSource`

Each of those has types provided for all the props it exposes, with the pattern of `<COMPONENT_NAME>Prop<PROP_NAME>`, so here are a few examples to clarify the rule:

```ts
import type {
  InfiniteTablePropColumns, // or accessible as InfiniteTableProps['columns']
  // corresponding to the `columns` input
  DataSourcePropGroupBy, // or accessible as DataSourceProps['groupBy']
  // corresponding to the `groupBy` input
} from '@infinite-table/infinite-angular';
```

Read more about how to use our TypeScript types.

## Built for Angular

`Infinite Table` for Angular is fully declarative and fully typed - standalone components, signals and `OnPush`, with no zone.js needed. It's configured through inputs, with the same names as the props of the React version:

- bind inputs in the template - `[columns]="columns"`, `[columnDefaultWidth]="120"`. The templates are type-checked against your data type (`strictTemplates`).
- the state the user changes (sorting, selection, column order, …) is a model: bind it two-way to a signal, for example [`[(sortInfo)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#sortInfo). The uncontrolled version ([`defaultSortInfo`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#defaultSortInfo)) is an input that needs nothing bound back.
- callbacks are outputs: [`(sortInfoChange)`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#onSortInfoChange), [`(cellClick)`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#onCellClick).
- columns stay plain objects. Their `render*` functions return text, a template (a `TemplateRef`), or a component (`renderComponent(MyCell)`) that reads the cell with [`injectColumnCell`](https://infinite-table.com/docs/reference/hooks/index.md#useInfiniteColumnCell).
- the imperative API is on the component: `#grid="infiniteTable"`, then `grid.api()`.

This is an example of how you might configure `InfiniteTable` in a real-world application and puts together several functionalities:

- grouping
- aggregation
- pinned columns
- sorting
- multiple selection
- custom cell rendering

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

import {
  DataSource,
  GroupRowsState,
  InfiniteCheckBox,
  InfiniteRender,
  InfiniteTable,
  renderTemplate,
} from '@infinite-table/infinite-angular';
import type {
  DataSourceGroupBy,
  DataSourcePropAggregationReducers,
  DataSourcePropFilterValue,
  DataSourcePropRowSelection_MultiRow,
  DataSourceSingleSortInfo,
  InfiniteTableColumn,
  InfiniteTableColumnRenderValueParam,
  InfiniteTablePropColumnPinning,
  InfiniteTablePropColumnTypes,
} 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,
  },
  currency: {
    field: 'currency',
    initialValue: new Set<string>(),
    reducer: (acc: Set<string>, value: string) => {
      acc.add(value);
      return acc;
    },
    done: (value: Set<string>) => {
      return value.size > 1 ? 'Mixed' : value.values().next().value;
    },
  },
  canDesign: {
    field: 'canDesign',
    initialValue: false,
    reducer: (acc: boolean | null, value: 'yes' | 'no') => {
      if (acc === null) {
        return acc;
      }
      if (acc === false && value === 'yes') {
        return null;
      }
      if (acc === true && value === 'no') {
        return null;
      }
      return acc;
    },
  },
};

const flags: Record<string, string> = {
  'United States': '🇺🇸',
  Canada: '🇨🇦',
  France: '🇫🇷',
  Germany: '🇩🇪',
  'United Kingdom': '🇬🇧',
  'South Africa': '🇿🇦',
  'New Zealand': '🇳🇿',
  Sweden: '🇸🇪',
  China: '🇨🇳',
  Brazil: '🇧🇷',
  Turkey: '🇹🇷',
  Italy: '🇮🇹',
  India: '🇮🇳',
  Indonesia: '🇮🇩',
  Japan: '🇯🇵',
  Argentina: '🇦🇷',
  'Saudi Arabia': '🇸🇦',
  Mexico: '🇲🇽',
  'United Arab Emirates': '🇦🇪',
};

const groupColumn: InfiniteTableColumn<Developer> = {
  header: 'Grouping',
  field: 'firstName',
  defaultWidth: 250,
  renderSelectionCheckBox: true,
  defaultFilterable: false,

  // 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: [
    ['United States'],
    ['United States', 'backend'],
    ['France'],
    ['Turkey'],
  ],
});

const columnTypes: InfiniteTablePropColumnTypes<Developer> = {
  number: {
    align: 'end',
    renderValue: ({ value, data, rowInfo }) => {
      return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency:
          rowInfo.isGroupRow && rowInfo.data?.currency === 'Mixed'
            ? 'USD'
            : data?.currency || 'USD',
      }).format(value);
    },
  },
};

const defaultRowSelection: DataSourcePropRowSelection_MultiRow = {
  selectedRows: [['United States'], ['India'], ['France'], ['Turkey']],
  deselectedRows: [['United States', 'frontend']],
  defaultSelection: false,
};

const defaultFilterValue: DataSourcePropFilterValue<Developer> = [
  {
    field: 'age',
    filter: {
      operator: 'gt',
      type: 'number',
      value: null,
    },
  },
];

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

const defaultSortInfo: DataSourceSingleSortInfo<Developer> = {
  dir: -1,
  field: 'country',
};

const defaultColumnPinning: InfiniteTablePropColumnPinning = {
  'group-by': true,
};

const domProps = {
  style: {
    minHeight: '50vh',
    height: 600,
    margin: 5,
  },
};

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

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable, InfiniteRender, InfiniteCheckBox],
  template: `
    <infinite-data-source
      [data]="dataSource"
      primaryKey="id"
      [defaultFilterValue]="defaultFilterValue"
      [useGroupKeysForMultiRowSelection]="true"
      [defaultRowSelection]="defaultRowSelection"
      [defaultSortInfo]="defaultSortInfo"
      (dataArrayChange)="onDataArrayChange($event)"
      [defaultGroupRowsState]="defaultGroupRowsState"
      [aggregationReducers]="aggregationReducers"
      [groupBy]="groupBy"
    >
      <infinite-table
        debugId="full-demo"
        groupRenderStrategy="single-column"
        [defaultColumnPinning]="defaultColumnPinning"
        [domProps]="domProps"
        [defaultActiveRowIndex]="0"
        [groupColumn]="groupColumn"
        [columns]="columns()"
        [columnTypes]="columnTypes"
        [columnDefaultWidth]="150"
      />
    </infinite-data-source>

    <!-- the salary cell: a heatmap background behind the default content -->
    <ng-template
      #salaryCell
      let-renderBag="renderBag"
      let-backgroundColor="backgroundColor"
    >
      <div
        style="
          position: absolute;
          display: flex;
          align-items: center;
          justify-content: flex-end;
          inset: 0;
        "
        [style.background-color]="backgroundColor"
      >
        <ng-container [infiniteRender]="renderBag.all" />
      </div>
    </ng-template>

    <ng-template #canDesignCell let-value="value">
      <div style="display: flex; align-items: center">
        <input
          infiniteCheckBox
          [defaultChecked]="value === null ? null : value === 'yes'"
          style="margin-right: 10px"
        />
        {{ value === null ? 'Some' : value === 'yes' ? 'Yes' : 'No' }}
      </div>
    </ng-template>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly defaultFilterValue = defaultFilterValue;
  protected readonly defaultRowSelection = defaultRowSelection;
  protected readonly defaultSortInfo = defaultSortInfo;
  protected readonly defaultGroupRowsState = defaultGroupRowsState;
  protected readonly aggregationReducers = aggregationReducers;
  protected readonly groupBy = groupBy;
  protected readonly defaultColumnPinning = defaultColumnPinning;
  protected readonly domProps = domProps;
  protected readonly groupColumn = groupColumn;
  protected readonly columnTypes = columnTypes;

  private readonly salaryCellTemplate =
    viewChild.required<TemplateRef<unknown>>('salaryCell');
  private readonly canDesignCellTemplate =
    viewChild.required<TemplateRef<unknown>>('canDesignCell');

  // the min and max salary of the current rows, for the heatmap background
  private readonly salaryRange = signal({ min: 0, max: 0 });

  protected onDataArrayChange(data: Developer[]) {
    const salaries = data.map((developer) => developer.salary ?? 0);
    this.salaryRange.set({
      min: Math.min(...salaries),
      max: Math.max(...salaries),
    });
  }

  // the columns are recomputed when the salary range changes
  protected readonly columns = computed<
    Record<string, InfiniteTableColumn<Developer>>
  >(() => {
    const { min, max } = this.salaryRange();
    return {
      age: {
        field: 'age',
        header: 'Age',
        type: 'number',
        defaultWidth: 100,
        renderValue: ({ value }) => value,
      },
      salary: {
        header: 'Compensation',
        field: 'salary',
        type: 'number',
        defaultWidth: 210,
        render: ({ renderBag, value }) => {
          const percentage = ((value - min) / Math.abs(max - min)) * 100;
          const alpha = Number((percentage / 100).toPrecision(2)) + 0.2;

          return renderTemplate(this.salaryCellTemplate(), {
            renderBag,
            backgroundColor: `rgba(255, 0, 0, ${alpha})`,
          });
        },
      },
      currency: { field: 'currency', header: 'Currency', defaultWidth: 100 },
      preferredLanguage: {
        field: 'preferredLanguage',
        header: 'Programming Language',
      },
      canDesign: {
        defaultWidth: 135,
        field: 'canDesign',
        header: 'Design Skills',
        renderMenuIcon: false,
        renderValue: () => this.canDesignCellTemplate(),
      },
      country: {
        field: 'country',
        header: 'Country',
        renderValue: ({ value }) => `${flags[value] ?? ''} ${value}`,
      },
      firstName: { field: 'firstName', header: 'First Name' },
      stack: { field: 'stack', header: 'Stack' },
      city: { field: 'city', header: 'City' },
    };
  });
}
```

## Licensing

`@infinite-table/infinite-angular` is published under the same license as the React package. Without a license key, the grid shows a [Powered by Infinite Table](https://infinite-table.com) footer. Provide your key once, for every grid of your application:

```ts
// app.config.ts
import type { ApplicationConfig } from '@angular/core';
import { provideInfiniteTable } from '@infinite-table/infinite-angular';

export const appConfig: ApplicationConfig = {
  providers: [
    
    provideInfiniteTable({ licenseKey: 'your-license-key' }),
  ],
};
```

A grid's own `[licenseKey]` input wins over it.

Read more about our licensing model and how you can use Infinite Table.

## About the Docs

> We're grateful for the work done by the [team behind reactjs.org](https://github.com/reactjs/reactjs.org) and the new React documentation found at [beta.reactjs.org](https://beta.reactjs.org/) - we've built our documentation on their excellent work 🙏 and we're grateful for that.

The documentation is versioned, and we will publish a new version of the documentation when there are any significant changes in the corresponding `@infinite-table/infinite-angular` version.
