# Carousel

A row of slides on the browser's own scrolling and scroll snap: touch, trackpad, wheel and keyboard scroll it natively, and buttons and indicators page through it.

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

```typescript title="Import"
import { Carousel, CarouselItem } from '@vigdx/ui/carousel';
```

## Basic

Pass `items` and a `vigCarouselItem` template; bind the items to `vigCarouselItemOf` to type `let-item`. `[(page)]` is the zero-based page in view; it changes once scrolling settles, so a swipe emits `pageChange` once. A page holds as many slides as are in view, so `page` counts pages, not items (unlike the `activeIndex` of a galleria); a resize that changes the slides per view recomputes it. Name the carousel with `labels.ariaLabel`. Give slide images `width`/`height` and `loading="lazy"` after the first.

```typescript title="carousel-basic.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Carousel, CarouselItem } from '@vigdx/ui/carousel';

import { PHOTOS } from '../../image/demos/photos';

@Component({
  selector: 'app-carousel-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Carousel, CarouselItem],
  template: `
    <vig-carousel [items]="photos" [(page)]="page" [labels]="{ ariaLabel: 'Destinations' }">
      <ng-template vigCarouselItem [vigCarouselItemOf]="photos" let-photo let-i="index">
        <figure class="flex flex-col gap-2">
          <img
            [src]="photo.src"
            [alt]="photo.alt"
            [width]="photo.width"
            [height]="photo.height"
            [attr.loading]="i === 0 ? null : 'lazy'"
            decoding="async"
            class="h-auto w-full rounded-media"
          />
          <figcaption class="text-sm text-muted-foreground">{{ photo.caption }}</figcaption>
        </figure>
      </ng-template>
    </vig-carousel>
    <p class="text-sm text-muted-foreground">Page: {{ page() + 1 }}</p>
  `,
})
export class CarouselBasicDemo {
  protected readonly photos = PHOTOS.slice(0, 5);
  protected readonly page = signal(0);
}
```

## Several per view, circular

`perView` takes a number or `{ base, sm, md, lg, xl }`, resolved by container queries on the carousel's own width (sm from 40rem, md 48rem, lg 64rem, xl 80rem), so the server render and the first paint already have the right layout. A page is that many slides; swipes snap page by page. `circular` wraps previous and next around.

```typescript title="carousel-per-view.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Carousel, CarouselItem } from '@vigdx/ui/carousel';

import { PHOTOS } from '../../image/demos/photos';

@Component({
  selector: 'app-carousel-per-view',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Carousel, CarouselItem],
  template: `
    <vig-carousel
      [items]="photos"
      [perView]="{ base: 1, sm: 2, lg: 3 }"
      circular
      [labels]="{ ariaLabel: 'Regions' }"
    >
      <ng-template vigCarouselItem [vigCarouselItemOf]="photos" let-photo>
        <article class="flex h-full flex-col gap-2 rounded-card border border-border p-3">
          <img
            [src]="photo.src"
            [alt]="photo.alt"
            [width]="photo.width"
            [height]="photo.height"
            loading="lazy"
            decoding="async"
            class="h-auto w-full rounded-media"
          />
          <h3 class="text-sm font-semibold">{{ photo.caption }}</h3>
          <p class="text-sm text-muted-foreground">{{ photo.region }}</p>
        </article>
      </ng-template>
    </vig-carousel>
  `,
})
export class CarouselPerViewDemo {
  protected readonly photos = PHOTOS;
}
```

## Autoplay

Off by default. `autoplay` (`true` for 5 seconds, or milliseconds) turns the pages and wraps at the end. It pauses while the pointer is over the carousel, while it is pressed and while the user scrolls it; when focus enters it, rotation stops for good and only the stop/start button (first in the tab order, WCAG 2.2.2) starts it again, as the APG asks. It starts stopped when the system asks for reduced motion.

```typescript title="carousel-autoplay.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Carousel, CarouselItem } from '@vigdx/ui/carousel';

@Component({
  selector: 'app-carousel-autoplay',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Carousel, CarouselItem],
  template: `
    <vig-carousel [items]="news" [autoplay]="6000" [labels]="{ ariaLabel: 'Announcements' }">
      <ng-template vigCarouselItem [vigCarouselItemOf]="news" let-item>
        <div class="flex min-h-28 flex-col justify-center gap-1 rounded-card bg-subtle px-14 py-4">
          <h3 class="text-base font-semibold text-foreground">{{ item.title }}</h3>
          <p class="text-sm text-foreground-soft">{{ item.text }}</p>
        </div>
      </ng-template>
    </vig-carousel>
  `,
})
export class CarouselAutoplayDemo {
  protected readonly news = [
    { title: 'Release 2.1', text: 'Carousel, image and galleria join the kit.' },
    { title: 'Office hours', text: 'Every Thursday at 15:00 for questions about migration.' },
    { title: 'Accessibility review', text: 'Every component passes AXE in seven themes.' },
  ];
}
```

## 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="carousel"][data-part="root"] { … }`: 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="carousel"]`

| Part | Element | data-state |
| --- | --- | --- |
| `root` | The host, a `role="region"` with `aria-roledescription="carousel"`; `rotating` while autoplay turns pages. | `rotating, idle` |
| `rotation` | Stop/start button of `autoplay`, first in the tab order. | `playing, paused` |
| `viewport` | Positions the previous/next buttons over the track. |   |
| `previous` | Previous page button. |   |
| `next` | Next page button. |   |
| `track` | The focusable scroll-snap row; `--vig-carousel-gap` sets the gap between slides. |   |
| `slide` | One slide, a group named "3 of 10"; `active` while in view. | `active, inactive` |
| `status` | Visually hidden polite status announcing the settled page. |   |
| `indicators` | The group of indicator buttons. |   |
| `indicator` | One page button; the current one has `aria-current="true"` and a wider dot. | `active, inactive` |

## Accessibility

- The APG carousel pattern: a `role="region"` with `aria-roledescription="carousel"`, slides as groups with `aria-roledescription="slide"` named "3 of 10". The role descriptions and every name are `labels` keys, so they translate.
- The track is one tab stop and scrolls natively with the arrow keys, Page Up/Down and Home/End; links and buttons inside slides keep their own keys, and focusing one scrolls its slide into view. Previous and next come before the slides in reading order.
- Indicators are buttons with `aria-current="true"` on the current page rather than tabs: several slides can be in view and every slide stays reachable by scrolling, which the tabs pattern (one visible panel, the others hidden) would not allow. The current dot is also wider, so it does not rely on color; in forced colors it is drawn in Highlight.
- A visually hidden polite status announces "Slide 3 of 10" once scrolling settles (`scrollend`, with a debounced `scroll` fallback), whether a button, an indicator or a swipe moved it; nothing is announced while autoplay rotates.
- Autoplay pauses on hover, while pressed and while the user scrolls; focus entering the carousel stops it until the rotation button is pressed. The direction comes from the carousel's own computed `direction`, so a plain `dir="rtl"` ancestor is enough. With a responsive `perView` the indicators stay invisible (their space kept) until the browser resolved how many pages there are.
- When previous or next becomes disabled while focused, focus moves to the other button. Every button is at least 24px (44px on touch screens). Smooth scrolling is used only without `prefers-reduced-motion`.

## API

### Carousel

Selector: `vig-carousel` · Kind: component

A row of slides on native scrolling and CSS scroll snap, following the APG carousel pattern: touch, trackpad, mouse wheel and the keyboard (the focusable track) scroll it natively; previous/next buttons and one indicator button per page (`aria-current`) scroll it from script. Slides are groups named "3 of 10"; a polite status announces where the carousel settled.

`perView` shows several slides at once, by container width; `circular` wraps the buttons around; `autoplay` (off by default) rotates through the pages, pauses while hovered, pressed or scrolled by the user, stops for good when focus enters the carousel (APG), offers a stop/start button (WCAG 2.2.2) and starts stopped under `prefers-reduced-motion`.

**Example :**

```html
<vig-carousel [items]="products" [perView]="{ base: 1, sm: 2, lg: 3 }" [labels]="{ ariaLabel: 'New arrivals' }">
  <ng-template vigCarouselItem [vigCarouselItemOf]="products" let-product>
    <app-product-card [product]="product" />
  </ng-template>
</vig-carousel>
```

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `autoplay` | `number` | `0` | Automatic rotation, off by default: `true` turns pages every 5 seconds, a number every that many milliseconds. It always wraps around. |
| `circular` | `boolean` | `false` | Previous on the first page goes to the last, next on the last to the first. |
| `indicators` | `boolean` | `true` | One indicator button per page below the slides. Default `true`. |
| `items` | `readonly T[]` | `[]` | The slides' data; each renders through the `vigCarouselItem` template. |
| `labels` | `Partial<CarouselLabels>` | — | Texts (i18n) over the locale defaults. |
| `page` (model) | `number` | `0` | Two-way: the zero-based page in view, set once scrolling settles (so a swipe emits `pageChange` once). With one slide per view a page is a slide; with several it counts pages, unlike a galleria's `activeIndex`, which is an item index. A resize that changes the slides per view recomputes it. |
| `perView` | `number \| CarouselPerView` | `1` | Slides per view: a number, or a `CarouselPerView` by container width. Default 1. |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `pageChange` | `number` | Two-way: the zero-based page in view, set once scrolling settles (so a swipe emits `pageChange` once). With one slide per view a page is a slide; with several it counts pages, unlike a galleria's `activeIndex`, which is an item index. A resize that changes the slides per view recomputes it. |

#### Methods

| Signature | Description |
| --- | --- |
| `goTo(page: number): void` | Scrolls to a zero-based page. |
| `next(): void` | Scrolls to the next page (the first one from the last, when `circular`). |
| `previous(): void` | Scrolls to the previous page (the last one from the first, when `circular`). |

### CarouselItem

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

The template of each slide. Bind the carousel's items to `vigCarouselItemOf` (like `ngForOf`) to type `let-item`.

**Example :**

```html
<ng-template vigCarouselItem [vigCarouselItemOf]="products" let-product let-i="index">
  <app-product-card [product]="product" />
</ng-template>
```

#### Inputs

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