# Data view

Items of any type rendered through your own template, as a list or a responsive grid, with sorting, paging, an empty state and loading placeholders.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `vig-data-view`
- Source: [libs/ui/src/lib/organisms/data-view/data-view.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/organisms/data-view/data-view.ts)

```typescript title="Import"
import { DataView, DataViewItem } from '@vigdx/ui/data-view';
```

## Basic

Pass `items` and an `ng-template vigDataViewItem`; bind the same items to `vigDataViewItemOf` so `let-product` is typed. Each item renders in an `<li>` of a `<ul role="list">`.

```typescript title="data-view-basic.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { DataView, DataViewItem } from '@vigdx/ui/data-view';
import { PRODUCTS } from './products';

@Component({
  selector: 'app-data-view-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [DataView, DataViewItem, CurrencyPipe],
  template: `
    <vig-data-view [items]="products">
      <ng-template vigDataViewItem [vigDataViewItemOf]="products" let-product>
        <div class="flex flex-wrap items-center justify-between gap-2">
          <div>
            <h3 class="text-sm font-semibold">{{ product.name }}</h3>
            <p class="text-sm text-muted-foreground">{{ product.category }}</p>
          </div>
          <span class="font-semibold tabular-nums">{{ product.price | currency: 'USD' }}</span>
        </div>
      </ng-template>
    </vig-data-view>
  `,
})
export class DataViewBasicDemo {
  protected readonly products = PRODUCTS.slice(0, 4);
}
```

## List and grid

`[(layout)]` is `list` or `grid`; `layoutToggle` adds a list/grid `vig-select-button` to the header, next to any `[vigDataViewHeader]` content. The template gets `layout` in its context. The grid fills columns of at least `--vig-data-view-item-min-width` (15rem) and drops to one column in a narrow container; items stretch to the row height, so cards line up.

```typescript title="data-view-layout.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { Card } from '@vigdx/ui/card';
import { DataView, DataViewHeader, DataViewItem, type DataViewLayout } from '@vigdx/ui/data-view';
import { PRODUCTS } from './products';

@Component({
  selector: 'app-data-view-layout',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [DataView, DataViewItem, DataViewHeader, Card, CurrencyPipe],
  template: `
    <vig-data-view [items]="products" [(layout)]="layout" layoutToggle>
      <h3 vigDataViewHeader class="text-h4">Accessories</h3>
      <ng-template vigDataViewItem [vigDataViewItemOf]="products" let-product let-layout="layout">
        @if (layout === 'grid') {
          <vig-card [heading]="product.name" [headingLevel]="4">
            <p class="text-sm text-muted-foreground">{{ product.category }}</p>
            <p class="mt-2 font-semibold tabular-nums">{{ product.price | currency: 'USD' }}</p>
          </vig-card>
        } @else {
          <div class="flex flex-wrap items-center justify-between gap-2">
            <h4 class="text-sm font-semibold">{{ product.name }}</h4>
            <span class="font-semibold tabular-nums">{{ product.price | currency: 'USD' }}</span>
          </div>
        }
      </ng-template>
    </vig-data-view>
    <p class="text-sm text-muted-foreground">Layout: {{ layout() }}</p>
  `,
})
export class DataViewLayoutDemo {
  protected readonly products = PRODUCTS.filter((product) => product.category === 'Accessories');
  protected readonly layout = signal<DataViewLayout>('grid');
}
```

## Sorting and paging

`sort` is typed against the items: `{ by: (item) => value }` (empty values first, numbers and dates numerically, text by the locale's collator) or `{ compare: (a, b) => number }`, with `direction` `asc` or `desc`; sorting is stable. A new sort goes back to the first page and, with a `label`, is announced once with the item count. `paginator` adds a `vig-paginator` (`true`, or `{ position, rowsPerPageOptions, jumpToPage, size }`), named by `labels.paginatorAriaLabel` ("Item pages"), bound to `[(first)]` and `[(rows)]`. `itemId` keeps each item's element across sorts and new arrays.

```typescript title="data-view-sort-page.ts"
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { DataView, DataViewHeader, DataViewItem, type DataViewSort } from '@vigdx/ui/data-view';
import { Select, type SelectOption } from '@vigdx/ui/select';
import { PRODUCTS, type Product } from './products';

const SORTS: Record<string, DataViewSort<Product>> = {
  name: { by: (product) => product.name, label: 'Name' },
  priceAsc: { by: (product) => product.price, label: 'Price, low to high' },
  priceDesc: { by: (product) => product.price, direction: 'desc', label: 'Price, high to low' },
  rating: {
    compare: (a, b) => b.rating - a.rating || a.price - b.price,
    label: 'Best rated, then cheapest',
  },
};

@Component({
  selector: 'app-data-view-sort-page',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [DataView, DataViewItem, DataViewHeader, Select, CurrencyPipe],
  template: `
    <vig-data-view
      [items]="products"
      [sort]="sort()"
      [paginator]="{ rowsPerPageOptions: [3, 5, 10] }"
      [(first)]="first"
      [(rows)]="rows"
      [itemId]="productId"
    >
      <div vigDataViewHeader class="max-w-60">
        <vig-select label="Sort by" [options]="sortOptions" [(value)]="sortKey" />
      </div>
      <ng-template vigDataViewItem [vigDataViewItemOf]="products" let-product>
        <div class="flex flex-wrap items-center justify-between gap-2">
          <h3 class="text-sm font-semibold">{{ product.name }}</h3>
          <span class="text-sm text-muted-foreground">{{ product.rating }} / 5</span>
          <span class="font-semibold tabular-nums">{{ product.price | currency: 'USD' }}</span>
        </div>
      </ng-template>
    </vig-data-view>
  `,
})
export class DataViewSortPageDemo {
  protected readonly products = PRODUCTS;
  protected readonly sortOptions: SelectOption<string>[] = Object.entries(SORTS).map(
    ([value, sort]) => ({ value, label: sort.label ?? value }),
  );
  protected readonly sortKey = signal<string | null>('name');
  protected readonly first = signal(0);
  protected readonly rows = signal(5);
  protected readonly productId = (product: Product) => product.id;
  protected readonly sort = computed(() => {
    const key = this.sortKey();
    return key ? SORTS[key] : undefined;
  });
}
```

## Empty and loading

Without items the data view shows a small `vig-empty-state` (heading `labels.emptyLabel`), or your `ng-template vigDataViewEmpty`. `loading` shows skeleton placeholders (a page's worth with the paginator, at most 12, else 3), or one `vigDataViewLoading` template per placeholder, and disables the paginator.

```typescript title="data-view-states.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { DataView, DataViewEmpty, DataViewItem } from '@vigdx/ui/data-view';
import { ToggleSwitch } from '@vigdx/ui/toggle-switch';
import { PRODUCTS } from './products';

@Component({
  selector: 'app-data-view-states',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [DataView, DataViewItem, DataViewEmpty, ToggleSwitch],
  template: `
    <div class="flex flex-wrap gap-6">
      <vig-toggle-switch label="Loading" [(value)]="loading" />
      <vig-toggle-switch label="Empty" [(value)]="empty" />
    </div>
    <vig-data-view [items]="empty() ? [] : products" [loading]="loading()" layout="grid">
      <ng-template vigDataViewItem [vigDataViewItemOf]="products" let-product>
        <div class="rounded-card border border-border p-4">
          <h3 class="text-sm font-semibold">{{ product.name }}</h3>
          <p class="text-sm text-muted-foreground">{{ product.category }}</p>
        </div>
      </ng-template>
      @if (customEmpty()) {
        <ng-template vigDataViewEmpty>
          <p class="text-sm text-muted-foreground">No products match these filters.</p>
        </ng-template>
      }
    </vig-data-view>
    <vig-toggle-switch label="Custom empty state" [(value)]="customEmpty" />
  `,
})
export class DataViewStatesDemo {
  protected readonly products = PRODUCTS.slice(0, 3);
  protected readonly loading = signal(false);
  protected readonly empty = signal(false);
  protected readonly customEmpty = signal(false);
}
```

## Server-side paging

Set `totalRecords` to the server's count: `items` is then the page at `first` and is shown as given. Load from the bound models, e.g. with a `resource` whose `params` read `first()` and `rows()`, and set `loading` while a page is on its way. Sort on the server too: in this mode `sort` only describes the order of `items` and is not applied again, but a new sort still goes back to the first page and is announced, with `totalRecords` as the count, once the page has loaded.

Every item on the page is rendered: there is no virtual scrolling. Page long lists, or show very long ones in `vig-table` with `virtualScroll`.

## Styling hooks

Internal elements carry a stable `data-part` and the component's `data-scope`; both are public API, so removing one is a breaking change. Select a part by both, e.g. `[data-scope="data-view"][data-part="header"] { … }`: the pair stays within this component when kit components nest, and also reaches parts in overlay panels, which render outside the host. State is exposed through `aria-*` and, where listed, a `data-state`; literal values are checked by the API gate, values computed from the component's state follow its documented types. Other `data-*` attributes listed below (such as `data-opening` while an overlay animates) are API too. See [Customizing](https://vigdx.com/docs/theming.md#customizing).

Scope: `[data-scope="data-view"]`

| Part | Element | data-state |
| --- | --- | --- |
| `header` | The row of the `[vigDataViewHeader]` content and the layout toggle. |   |
| `layout-toggle` | The list/grid `vig-select-button`; style its `[data-scope="select-button"]` parts. |   |
| `status` | The visually hidden polite region (loading, sorted). |   |
| `list` | The `<ul role="list">` of the items, as a list or a grid. |   |
| `item` | One `<li>` around an item template. |   |
| `empty` | Wrapper of the empty state or the `vigDataViewEmpty` template. |   |
| `loading` | The hidden container of the placeholders (`loading`). |   |
| `placeholder` | One skeleton or `vigDataViewLoading` placeholder. |   |
| `paginator` | The `vig-paginator` (`paginator`); style its own parts. |   |

## Accessibility

- Items render as a list in both layouts (`role="list"` keeps list semantics in Safari, which drops them for unstyled lists), so screen readers announce the count and each position. Give items a heading of the right level for the page and real controls: the data view adds no keyboard handling of its own, so Tab moves through the items' controls.
- The layout toggle is a radio group named "Layout" (`labels.layoutAriaLabel`); its options carry visually hidden text next to the icons.
- Sorting moves the existing elements (tracked by `itemId`), keeping focus inside an item. A sort with a `label` is announced once through a polite status ("Sorted by Price, low to high"), and so is `loading`; the placeholders are hidden from screen readers.

## API

### DataView

Selector: `vig-data-view` · Kind: component

Items of any type rendered through your own template, as a list or a responsive grid, with optional sorting, paging, a layout toggle, an empty state and loading placeholders.

**Example :**

```html
<vig-data-view [items]="products" [(layout)]="layout" layoutToggle paginator>
  <ng-template vigDataViewItem [vigDataViewItemOf]="products" let-product>
    <h3>{{ product.name }}</h3>
  </ng-template>
</vig-data-view>
```

Items render in a `<ul role="list">`, one `<li>` each, in both layouts; headings and controls inside an item are the template's. The grid fills columns of at least `--vig-data-view-item-min-width` (15rem), one column on a narrow container. `sort` orders the items in memory; `paginator` shows a `vig-paginator` and pages them, or — with `totalRecords` — shows `items` as the current page of a server-side list, whose `first` and `rows` you load from. Every item is rendered: page long lists, or use `vig-table`'s virtual scrolling for very long ones.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `first` (model) | `number` | `0` | Zero-based index of the first item on the page. |
| `itemId` | `((item: T) => unknown) \| undefined` | `undefined` | Identity of an item, so its element survives sorting and new arrays; the item itself by default. |
| `items` | `readonly T[]` | `[]` | The items. With `totalRecords`, the current page only. |
| `labels` | `Partial<DataViewLabels>` | — | Texts (i18n); locale defaults. |
| `layout` (model) | `DataViewLayout` | `'list'` | `list` (default) or `grid`; two-way bindable. |
| `layoutToggle` | `boolean` | `false` | Shows a list/grid toggle in the header. |
| `loading` | `boolean` | `false` | Shows placeholders instead of the items, and a "Loading" status. |
| `paginator` | `DataViewPaginatorOptions \| null` | `null` | Pages the items with a `vig-paginator`: `true`, or its options. |
| `rows` (model) | `number` | `10` | Page size. |
| `sort` | `DataViewSort<T> \| null \| undefined` | `undefined` | The order of the items: an accessor (`by`) or a comparator (`compare`). A new sort goes back to the first page and is announced with its `label`. With `totalRecords` the server sorts: the sort then only describes the order of `items` (announced, not applied). |
| `totalRecords` | `number \| undefined` | `undefined` | Total count of a server-side list: `items` is then the page at `first` and is shown as given. Unset, the data view pages `items` itself. |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `firstChange` | `number` | Zero-based index of the first item on the page. |
| `layoutChange` | `DataViewLayout` | `list` (default) or `grid`; two-way bindable. |
| `rowsChange` | `number` | Page size. |

### DataViewItem

Selector: `ng-template[vigDataViewItem]` · Kind: directive

Renders each item of `vig-data-view`; `layout` in the context tells list from grid. Bind the items to `vigDataViewItemOf` to type `let-item`:

**Example :**

```html
<ng-template vigDataViewItem [vigDataViewItemOf]="products" let-product let-layout="layout">
  …
</ng-template>
```

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `vigDataViewItemOf` | `readonly T[] \| null \| undefined` | `undefined` | Type-only: the items the template renders, so `let-item` is typed. Not read at runtime. |

### Templates and directives

| Selector | Export | Description |
| --- | --- | --- |
| `ng-template[vigDataViewEmpty]` | `DataViewEmpty` | Replaces the default empty state of `vig-data-view`. |
| `ng-template[vigDataViewLoading]` | `DataViewLoading` | One loading placeholder of `vig-data-view`, in place of the default skeleton. |
| `[vigDataViewHeader]` | `DataViewHeader` | Marks projected content (a heading, a sort select) for the data view's header row. |
