# Rating

A row of stars (or any icon) for a score from 1 to max, picked by pointer or keyboard, or shown read-only as an average.

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

```typescript title="Import"
import { Rating } from '@vigdx/ui/rating';
```

## Basic

Bind `[(value)]` to a `number | null` signal; `null` means not rated. Hovering previews a value without changing it.

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

@Component({
  selector: 'app-rating-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Rating],
  template: `
    <vig-rating label="Your rating" [(value)]="stars" />
    <p class="text-sm text-muted-foreground">Value: {{ stars() ?? 'none' }}</p>
  `,
})
export class RatingBasicDemo {
  protected readonly stars = signal<number | null>(3);
}
```

## Half steps, clearing, icons and sizes

`allowHalf` picks half icons (the half under the pointer, from the inline start) and steps the arrows by 0.5. `clearable` clears the rating when the current value is picked again or Delete is pressed. `max` sets the number of icons, `icon` any registered glyph, `size` the scale (`sm`, `md`, `lg`).

```typescript title="rating-options.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { provideVigdxIcons } from '@vigdx/ui/icon';
import { Rating } from '@vigdx/ui/rating';

@Component({
  selector: 'app-rating-options',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Rating],
  // Any registered glyph works as the icon; filled icons fill its outline.
  providers: [
    provideVigdxIcons({
      heart: {
        paths: [
          'M19 14c1.5-1.5 3-3.2 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.8 0-3 .5-4.5 2-1.5-1.5-2.7-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4 3 5.5l7 7Z',
        ],
      },
    }),
  ],
  template: `
    <div class="grid gap-6 sm:grid-cols-2">
      <vig-rating label="Half steps" allowHalf [(value)]="half" />
      <vig-rating
        label="Clearable"
        clearable
        hint="Pick the current rating again, or press Delete, to clear it."
        [(value)]="clearable"
      />
      <vig-rating label="Out of ten" size="sm" [max]="10" [(value)]="ten" />
      <vig-rating label="Favorite" icon="heart" size="lg" [max]="3" [(value)]="hearts" />
    </div>
  `,
})
export class RatingOptionsDemo {
  protected readonly half = signal<number | null>(3.5);
  protected readonly clearable = signal<number | null>(2);
  protected readonly ten = signal<number | null>(7);
  protected readonly hearts = signal<number | null>(1);
}
```

## Read-only, disabled and error

`readonly` shows a fixed rating, which may be fractional (an average fills part of an icon); it stays focusable and is announced, e.g. "3.7 of 5". Disabled ratings leave the tab order. Errors show once the field is touched and invalid.

```typescript title="rating-states.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Rating } from '@vigdx/ui/rating';

@Component({
  selector: 'app-rating-states',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Rating],
  template: `
    <div class="grid gap-6 sm:grid-cols-3">
      <vig-rating label="Average (read-only)" readonly [value]="3.7" hint="From 128 reviews" />
      <vig-rating label="Disabled" disabled [value]="2" />
      <vig-rating
        label="Required"
        required
        touched
        invalid
        [value]="null"
        [errors]="[{ kind: 'required' }]"
      />
    </div>
  `,
})
export class RatingStatesDemo {}
```

## Signal Forms

`vig-rating` implements `FormValueControl<number | null>`. A schema `max()` sets the number of icons; other rules show their message once the rating is touched.

```typescript title="rating-signal-forms.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { FormField, form, min, required } from '@angular/forms/signals';
import { Rating } from '@vigdx/ui/rating';

@Component({
  selector: 'app-rating-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, Rating],
  template: `
    <vig-rating label="How was your stay?" clearable [formField]="review.stay" />
    <p class="text-sm text-muted-foreground">
      Valid: {{ review().valid() ? 'yes' : 'no' }} · {{ model().stay ?? 'none' }}
    </p>
  `,
})
export class RatingSignalFormsDemo {
  protected readonly model = signal<{ stay: number | null }>({ stay: null });
  protected readonly review = form(this.model, (path) => {
    required(path.stay, { message: 'Rate your stay.' });
    min(path.stay, 2, { message: 'Tell us what went wrong below.' });
  });
}
```

## Reactive Forms

Import `VigValueAccessor` next to the component to use `formControlName`, `[formControl]` or `ngModel`.

```typescript title="rating-reactive-forms.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { VigValueAccessor } from '@vigdx/ui/core';
import { Rating } from '@vigdx/ui/rating';

@Component({
  selector: 'app-rating-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ReactiveFormsModule, Rating, VigValueAccessor],
  template: `
    <vig-rating label="Service" allowHalf [formControl]="service" />
    <p class="text-sm text-muted-foreground">
      {{ service.value ?? 'none' }} · {{ service.dirty ? 'dirty' : 'pristine' }}
    </p>
  `,
})
export class RatingReactiveFormsDemo {
  protected readonly service = new FormControl<number | null>(4, Validators.required);
}
```

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

| Part | Element | data-state |
| --- | --- | --- |
| `label` | The visible label (`aria-labelledby` of the control). |   |
| `control` | The `role="slider"` row of icons; `preview` while a pointer hovers. | `preview` |
| `item` | One icon cell; its state is how much of the icon is filled. | `full, partial, empty` |
| `fill` | The solid copy of the icon, clipped to the filled share from the inline start. |   |
| `hint` | The `vig-hint` (a `display: contents` host; style its `text` part). |   |
| `disabled-reason` | The `vig-hint` with the disabled reason (`display: contents`). |   |
| `error` | The `vig-field-error` (a `display: contents` host; style its `message` part). |   |

## Accessibility

- One `role="slider"`, as in the APG rating slider example, not a radio group: a single tab stop, half steps and clearing map onto one number (a radio group would need two radios per icon plus a "none" radio), and screen readers announce the value as "3 of 5" through `aria-valuetext` (`labels.valueLabel`), or "No rating" (`labels.emptyLabel`).
- Right and Up raise the rating, Left and Down lower it (Left and Right swap under RTL), Page Up and Page Down move by a whole icon, Home and End jump to the lowest and highest rating. With `clearable` the slider's minimum is 0 ("No rating"): Home, stepping below the lowest rating, Delete and Backspace clear it; without it the minimum is the lowest rating.
- Filled icons are solid, empty ones outlined in `--color-border-control`: the state reads from the shape, also in forced-colors mode, and both hold 3:1 against the page. The filled color is the `--color-rating` token.
- Each icon cell is at least 24px (44px on touch screens). The hover preview is for mouse and pen only.
- `readonly` keeps the rating focusable with `aria-readonly`. The slider role has no `aria-required`, so `required` adds a visually hidden "Required" to the description.

## API

### Rating

Selector: `vig-rating` · Kind: component

A star rating: pick a whole (or, with `allowHalf`, half) number of icons out of `max`. `clearable` lets the user take the rating back by picking the current value again (or with Delete). `readonly` shows a fixed rating that is still announced ("3.5 of 5") and may be fractional, e.g. an average.

**Example :**

```html
<vig-rating label="Your rating" [(value)]="stars" clearable />
```

It is one `role="slider"` (the APG rating slider): a single tab stop whose arrows step by one icon (or half), mirrored under RTL, Home and End jump to the ends; with `clearable`, Home and stepping below the lowest rating clear it. Pointers preview the value on hover. Works with Signal Forms and, through `VigValueAccessor`, with Reactive Forms and `ngModel`.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `allowHalf` | `boolean` | `false` | Lets the user pick half icons; arrows then step by 0.5. |
| `clearable` | `boolean` | `false` | Picking the current value again (or pressing Delete) clears the rating. |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `hidden` | `boolean` | `false` | — |
| `hideLabel` | `boolean` | `false` | Keeps the label for assistive tech only. |
| `hint` | `string \| undefined` | `undefined` | — |
| `icon` | `string` | `'star'` | Name of a registered `vig-icon` glyph; filled icons fill its outline. |
| `invalid` | `boolean` | `false` | — |
| `label` (required) | `string` | — | — |
| `labels` | `Partial<RatingLabels>` | — | Texts (i18n); locale defaults. |
| `max` | `number \| undefined` | `5` | The number of icons, the highest rating (default 5). `number \| undefined` to match the `FormValueControl` contract, which binds a schema's `max()`. |
| `name` | `string` | `''` | — |
| `pending` | `boolean` | `false` | — |
| `readonly` | `boolean` | `false` | — |
| `required` | `boolean` | `false` | — |
| `size` | `FieldSize` | `'md'` | — |
| `touched` | `boolean` | `false` | — |
| `value` (model) | `number \| null` | `null` | The rating, `null` while unrated. |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `touch` | `void` | — |
| `valueChange` | `number \| null` | The rating, `null` while unrated. |

#### Methods

| Signature | Description |
| --- | --- |
| `focus(options?: FocusOptions): void` | Moves focus to the control's interactive element (the input, or the trigger of a popup control). Signal Forms calls it through `field().focusBoundControl()`; the host element itself cannot take focus. |
| `reset(): void` | Returns the control to its pristine look: drops in-progress text, closes an open popup, clears errors the component raised itself and the submitted state of `errorDisplay: 'interacted'`. Signal Forms calls it from `field().reset()`; `VigValueAccessor` from `control.reset()`. It never changes the value: the bound form owns that. |
