@molecule/app-rating-form-angular

Feature · rating-form · App (browser) · v1.1.2 · Apache-2.0

Interactive star rating + textarea + submit form for collecting reviews

npm install @molecule/app-rating-form-angular

npm · Source on GitHub

How it works

@molecule/app-rating-form-angular is a ready-made rating-form feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.

import { Component } from '@angular/core'
import { RatingForm } from '@molecule/app-rating-form-angular'

@Component({
  selector: 'app-review',
  standalone: true,
  imports: [RatingForm],
  template: `
    <form
      mol-rating-form
      title="Leave a review"
      submitLabel="Submit review"
      [onSubmit]="submitReview"
    ></form>
  `,
})
export class Review {
  submitReview = (rating: number, comment: string): Promise<void> =>
    api.submitReview({ rating, comment })
}

Works with: @molecule/app-angular, @molecule/app-ui, @molecule/app-ui-angular

Reference

Angular interactive star-rating + comment form — the counterpart of @molecule/app-rating-form-react: the same props and the same DOM for the same input.

Exports <RatingForm> — a star radiogroup, a comment textarea and a submit button.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { Component } from '@angular/core'
import { RatingForm } from '@molecule/app-rating-form-angular'

@Component({
  selector: 'app-review',
  standalone: true,
  imports: [RatingForm],
  template: `
    <form
      mol-rating-form
      title="Leave a review"
      submitLabel="Submit review"
      [onSubmit]="submitReview"
    ></form>
  `,
})
export class Review {
  submitReview = (rating: number, comment: string): Promise<void> =>
    api.submitReview({ rating, comment })
}

Type

feature

Installation

npm install @molecule/app-rating-form-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

RatingFormProps

Props accepted by RatingForm — the same props @molecule/app-rating-form-react accepts. Node-valued props (title, submitLabel) are TemplateRefs (or plain strings/numbers) in Angular.

interface RatingFormProps {
  /** Called with the submitted rating + optional comment. */
  onSubmit: (rating: number, comment: string) => void | Promise<void>
  /** Maximum stars. Defaults to 5. */
  max?: number
  /** Initial rating (uncontrolled). */
  defaultRating?: number
  /** Whether a comment is required. Defaults to false. */
  requireComment?: boolean
  /** Form heading: text or a template. */
  title?: TemplateRef<unknown> | string | number | null
  /** Comment placeholder. */
  commentPlaceholder?: string
  /** Submit-button label: text or a template. */
  submitLabel?: TemplateRef<unknown> | string | number | null
  /** Extra classes. */
  className?: string
}

Classes

RatingForm

RatingForm component.

Interactive star-rating + comment form. Used for review submission (product reviews, course feedback, support-ticket CSAT). The host IS the <form> (form[mol-rating-form]), matching React's root exactly, so the root's class and submit handling are host bindings.

The submit button stays disabled until a star rating is selected, and requireComment blocks submission on blank comments silently (no inline error is rendered). Rejected onSubmit promises propagate — handle errors in your handler. Same props (React names) and same DOM as @molecule/app-rating-form-react's RatingForm.

@Component({
  selector: 'form[mol-rating-form]',
  standalone: true,
  imports: [Button, Textarea, NgTemplateOutlet],
  inputs: [
    'onSubmit',
    'max',
    'defaultRating',
    'requireComment',
    'title',
    'commentPlaceholder',
    'submitLabel',
    'className',
  ],
  host: {
    '[class]': 'formClasses()',
    '(submit)': 'handle($event)',
  },
  // The template's whitespace is semantic: Angular keeps whitespace-only text
  // nodes, so the DOM React renders is reproduced by gluing the tags.
  // prettier-ignore
  template: `@if (showTitle()) {<h3 [class]="titleClasses()">@if (titleTemplate(); as tpl) {<ng-container [ngTemplateOutlet]="tpl" />}@else {<ng-container>{{ textOf(title) }}</ng-container>}</h3>}<div role="radiogroup" tabindex="-1" [attr.aria-label]="ratingLabel()" [class]="groupClasses()" (mouseleave)="clearHover()">@for (n of stars(); track n) {<button #star type="button" role="radio" data-mol-id="rating-form-star" [attr.tabindex]="starTab(n)" [attr.aria-checked]="rating() === n" [attr.aria-label]="starLabel(n)" (click)="select(n)" (keydown)="onStarKey($event)" (mouseenter)="preview(n)" [class]="starClasses()" [style.background]="'none'" [style.border]="'none'" [style.font-size]="'28px'" [style.color]="starColor(n)">★</button>}</div><div mol-textarea [value]="comment()" (change)="onCommentChange($event)" [placeholder]="placeholderText()" [rows]="4" [attr.aria-label]="commentLabel()"></div><button mol-button [type]="'submit'" [variant]="'solid'" [color]="'primary'" [disabled]="submitting() || !rating()">@if (submitting()) {<ng-container>{{ submittingText() }}</ng-container>}@else if (submitLabelTemplate(); as tpl) {<ng-container [ngTemplateOutlet]="tpl" />}@else if (hasSubmitLabel()) {<ng-container>{{ textOf(submitLabel) }}</ng-container>}@else {<ng-container>{{ submitText() }}</ng-container>}</button>`,
})
export class RatingForm implements OnInit {
  onSubmit?: (rating: number, comment: string) => void | Promise<void>
  /** Maximum stars (defaults to 5 at read time). */
  max?: number
  /** Initial rating (uncontrolled). */
  defaultRating?: number
  /** Whether a comment is required. */
  requireComment?: boolean
  /** Form heading: text or a template. */
  title?: TemplateRef<unknown> | string | number | null
  /** Comment placeholder. */
  commentPlaceholder?: string
  /** Submit-button label: text or a template. */
  submitLabel?: TemplateRef<unknown> | string | number | null
  /** Extra classes. */
  className?: string

  /** Reactive translation, read in the injection context. */
  private readonly i18n = useTranslation()

  /** The selected rating (React's `useState`, seeded from `defaultRating`). */
  protected readonly rating = signal(0)
  /** The hovered star, or 0 (React's `useState`). */
  protected readonly hover = signal(0)
  /** The controlled comment. */
  protected readonly comment = signal('')
  /** Whether a submit is in flight. */
  protected readonly submitting = signal(false)
  /** The star buttons, in DOM order (React's `starRefs` map). */
  @ViewChildren('star')
  protected readonly starRefs?: QueryList<ElementRef<HTMLButtonElement>>

  ngOnInit(): void {
    this.rating.set(this.defaultRating ?? 0)
  }

  /** The current class map. */
  cm(): UIClassMap {
    return getClassMap()
  }

  /** The form's class list (React's `cm.cn(cm.stack(3), className)`). */
  formClasses(): string {
    return this.cm().cn(this.cm().stack(3), this.className)
  }

  /** The heading's class list. */
  titleClasses(): string {
    return this.cm().cn(this.cm().textSize('base'), this.cm().fontWeight('semibold'))
  }

  groupClasses(): string {
    return this.cm().flex({ align: 'center', gap: 'xs' })
  }

  starClasses(): string {
    return this.cm().cn(this.cm().cursorPointer, this.cm().touchTarget)
  }

  maxValue(): number {
    return this.max ?? 5
  }

  stars(): number[] {
    return Array.from({ length: this.maxValue() }, (_value, index) => index + 1)
  }

  /** The value a star draws at (React's `hover || rating`). */
  display(): number {
    return this.hover() || this.rating()
  }

  /** A star's fill colour. */
  starColor(n: number): string {
    return n <= this.display() ? STAR_COLORS.filled : STAR_COLORS.empty
  }

  starTab(n: number): number {
    return n === this.tabStop() ? 0 : -1
  }

  tabStop(): number {
    const selected = this.rating()
    return selected >= 1 && selected <= this.maxValue() ? selected : 1
  }

  selectAndFocus(n: number): void {
    this.rating.set(n)
    this.starRefs?.get(n - 1)?.nativeElement.focus()
  }

  onStarKey(event: KeyboardEvent): void {
    const current = this.tabStop()
    let next: number
    switch (event.key) {
      case 'ArrowRight':
      case 'ArrowDown':
        next = current >= this.maxValue() ? 1 : current + 1
        break
      case 'ArrowLeft':
      case 'ArrowUp':
        next = current <= 1 ? this.maxValue() : current - 1
        break
      case 'Home':
        next = 1
        break
      case 'End':
        next = this.maxValue()
        break
      default:
        return
    }
    event.preventDefault()
    this.selectAndFocus(next)
  }

  /** The radiogroup's accessible label (React's `rating.label`). */
  ratingLabel(): string {
    return this.i18n.t('rating.label', {}, { defaultValue: 'Rating' })
  }

  /** A star's accessible label (React's `rating.star`). */
  starLabel(n: number): string {
    return this.i18n.t(
      'rating.star',
      { n, max: this.maxValue() },
      { defaultValue: '{{n}} of {{max}}' },
    )
  }

  /** The comment placeholder (React's `commentPlaceholder ?? t(…)`). */
  placeholderText(): string {
    return (
      this.commentPlaceholder ??
      this.i18n.t(
        'rating.commentPlaceholder',
        {},
        {
          defaultValue: 'Share your thoughts (optional)',
        },
      )
    )
  }

  /** The comment field's accessible label (React's `rating.comment`). */
  commentLabel(): string {
    return this.i18n.t('rating.comment', {}, { defaultValue: 'Comment' })
  }

  /** The button's text while submitting (React's `rating.submitting`). */
  submittingText(): string {
    return this.i18n.t('rating.submitting', {}, { defaultValue: 'Submitting…' })
  }

  /** The button's idle text (React's `rating.submit`). */
  submitText(): string {
    return this.i18n.t('rating.submit', {}, { defaultValue: 'Submit review' })
  }

  /** The text fallback used when a value is not a template. */
  textOf(value: unknown): string {
    return textOf(value)
  }

  /** The title as a template, when the caller passed a node. */
  titleTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.title) ? this.title : null
  }

  /** The submit label as a template, when the caller passed a node. */
  submitLabelTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.submitLabel) ? this.submitLabel : null
  }

  /** Whether the heading renders (React's `title && …`). */
  showTitle(): boolean {
    return truthyNode(this.title)
  }

  hasSubmitLabel(): boolean {
    return this.submitLabel !== undefined && this.submitLabel !== null
  }

  /** Selects a star (React's `onClick` → `setRating`). */
  select(n: number): void {
    this.rating.set(n)
  }

  /** Previews a star (React's `onMouseEnter` → `setHover`). */
  preview(n: number): void {
    this.hover.set(n)
  }

  /** Clears the hover preview (React's `onMouseLeave` on the radiogroup). */
  clearHover(): void {
    this.hover.set(0)
  }

  onCommentChange(event: Event): void {
    this.comment.set((event.target as HTMLTextAreaElement).value)
  }

  async handle(event: Event): Promise<void> {
    event.preventDefault()
    if (this.submitting() || !this.rating()) return
    if (this.requireComment && !this.comment().trim()) return
    this.submitting.set(true)
    try {
      await this.onSubmit?.(this.rating(), this.comment())
    } finally {
      this.submitting.set(false)
    }
  }
}

(Member comments are shortened to their first sentence, and the 13 longest are left out to fit; the full declaration is in node_modules/@molecule/app-rating-form-angular/dist/rating-form.component.d.ts.)

Injection Notes

Requirements

Peer dependencies:

  • @angular/common ^22.0.0
  • @angular/core ^22.0.0
  • @angular/platform-browser ^22.0.0
  • @molecule/app-angular ^3.5.0 || ^4.0.0
  • @molecule/app-ui ^1.0.1
  • @molecule/app-ui-angular ^1.1.0

Runtime Dependencies

  • @angular/common
  • @angular/core
  • @angular/platform-browser
  • @molecule/app-angular
  • @molecule/app-ui
  • @molecule/app-ui-angular

Companion locale bond: @molecule/app-locales-rating-form. The submit button stays disabled until a star rating is selected, and requireComment blocks submission on blank comments silently (no inline error is rendered). Rejected onSubmit promises propagate — handle errors in your handler. Requires a bonded ClassMap and @molecule/app-angular's i18n provider above it.

Translations

Translation strings are provided by @molecule/app-locales-rating-form.