@molecule/app-color-picker-angular

Feature · color-picker · App (browser) · v1.1.1 · Apache-2.0

HSV slider + RGB sliders + HEX input — controlled color picker for design canvases, photo editors, animation tools

npm install @molecule/app-color-picker-angular

npm · Source on GitHub

How it works

@molecule/app-color-picker-angular is a ready-made color-picker 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, signal } from '@angular/core'
import { ColorPicker } from '@molecule/app-color-picker-angular'

@Component({
  selector: 'app-stroke-color',
  standalone: true,
  imports: [ColorPicker],
  template: `<div mol-color-picker [value]="color()" [onChange]="setColor"></div>`,
})
export class StrokeColorField {
  readonly color = signal('#3366ff')
  readonly setColor = (hex: string): void => this.color.set(hex)
}

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

Reference

Angular controlled HSV + RGB + HEX color picker — design canvases, photo editors, animation tools, brand editors.

The Angular counterpart of @molecule/app-color-picker-react: same exports, same props (React names), same DOM for the same input.

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, signal } from '@angular/core'
import { ColorPicker } from '@molecule/app-color-picker-angular'

@Component({
  selector: 'app-stroke-color',
  standalone: true,
  imports: [ColorPicker],
  template: `<div mol-color-picker [value]="color()" [onChange]="setColor"></div>`,
})
export class StrokeColorField {
  readonly color = signal('#3366ff')
  readonly setColor = (hex: string): void => this.color.set(hex)
}

Type

feature

Installation

npm install @molecule/app-color-picker-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-i18n @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

RgbColor

RGB color, 8-bit components (0–255).

interface RgbColor {
  /** Red (0–255). */
  r: number
  /** Green (0–255). */
  g: number
  /** Blue (0–255). */
  b: number
}

HsvColor

HSV color, hue degrees + saturation/value 0–1.

interface HsvColor {
  /** Hue in degrees (0–360). */
  h: number
  /** Saturation (0–1). */
  s: number
  /** Value / brightness (0–1). */
  v: number
}

ColorPickerProps

Props for the ColorPicker component.

interface ColorPickerProps {
  /** Current color as a 6-character HEX string with leading `#`. */
  value: string
  /** Called whenever the user picks a new color. Receives a `#rrggbb` string. */
  onChange: (hex: string) => void
  /** `data-mol-id` attribute for AI-agent selectors. */
  dataMolId?: string
  /** Extra classes appended via the ClassMap `cn()` helper. */
  className?: string
}

Classes

ColorPicker

ColorPicker component.

Controlled color picker — HSV (hue + saturation + value) sliders, RGB sliders, and a HEX text input. All four representations stay in lockstep with the controlling value.

Designed for design canvases, photo editors, animation tools, and brand editors. Pure UI — no popover/anchor logic; parents render this inside whatever portal/popover they prefer.

The host IS the outer <div> (div[mol-color-picker]), matching React's root exactly. Styling is delegated to getClassMap(); only inline styles are used for the live swatch background and slider track gradients.

Text is read through the binding's reactive useTranslation(), so a locale switch re-renders the translated aria-labels.

@Component({
  selector: 'div[mol-color-picker]',
  standalone: true,
  inputs: ['value', 'onChange', 'dataMolId', 'className'],
  host: {
    '[class]': 'classes()',
    '[attr.data-mol-id]': "dataMolId ?? 'color-picker'",
    role: 'group',
    '[attr.aria-label]': 'groupAria()',
  },
  template: `<div [class]="rowClasses()">
      <span aria-hidden="true" data-mol-id="color-picker-swatch" [style]="swatchStyle()"></span>
      <input
        type="text"
        (input)="handleHexInput($event)"
        (focusout)="commitAndRestore($event)"
        (keydown)="handleHexKeydown($event)"
        [attr.aria-label]="hexAria()"
        data-mol-id="color-picker-hex"
        spellcheck="false"
        maxlength="7"
        style="font-family: monospace; padding: 0.3rem 0.5rem"
      />
    </div>
    <label [class]="labelClasses()">
      <span>{{ hueAria() }}</span>
      <input
        type="range"
        min="0"
        max="360"
        step="1"
        (input)="handleHsvInput('h', $event)"
        [attr.aria-label]="hueAria()"
        data-mol-id="color-picker-hue"
        [style]="hueSliderStyle()"
      />
    </label>
    <label [class]="labelClasses()">
      <span>{{ saturationAria() }}</span>
      <input
        type="range"
        min="0"
        max="100"
        step="1"
        (input)="handleHsvInput('s', $event)"
        [attr.aria-label]="saturationAria()"
        data-mol-id="color-picker-saturation"
        [style]="sliderStyle()"
      />
    </label>
    <label [class]="labelClasses()">
      <span>{{ valueAria() }}</span>
      <input
        type="range"
        min="0"
        max="100"
        step="1"
        (input)="handleHsvInput('v', $event)"
        [attr.aria-label]="valueAria()"
        data-mol-id="color-picker-value"
        [style]="sliderStyle()"
      />
    </label>
    <div [class]="channelsClasses()">
      @for (channel of channels; track channel) {
        <label [class]="labelClasses()" style="flex: 1 1 0%">
          <span>{{ channelLabels()[channel] }}</span>
          <input
            type="number"
            min="0"
            max="255"
            step="1"
            (input)="handleRgbInput(channel, $event)"
            [attr.aria-label]="channelLabels()[channel]"
            [attr.data-mol-id]="'color-picker-' + channel"
            style="padding: 0.3rem 0.5rem"
          />
        </label>
      }
    </div>`,
})
export class ColorPicker implements AfterViewChecked {
  value?: string
  onChange?: ColorPickerProps['onChange']
  /** `data-mol-id` attribute for AI-agent selectors. */
  dataMolId?: string
  className?: string

  /** The three RGB channel keys, in render order. */
  readonly channels: ReadonlyArray<Channel> = ['r', 'g', 'b']

  private hexDraft: string | null = null

  /** The host element (the outer `<div>`). */
  private readonly el = inject(ElementRef)

  private readonly i18n = useTranslation()

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

  classes(): string {
    return this.cm().cn(this.cm().flex({ direction: 'col', gap: 'sm' }), this.className)
  }

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

  /** The RGB row's class (React's `cm.flex({ gap })`). */
  channelsClasses(): string {
    return this.cm().flex({ gap: 'sm' })
  }

  labelClasses(): string {
    return this.cm().cn(this.cm().textSize('xs'), this.cm().flex({ direction: 'col', gap: 'xs' }))
  }

  rgb(): RgbColor {
    return hexToRgb(this.value as string)
  }

  hsv(): HsvColor {
    return rgbToHsv(this.rgb())
  }

  hexShown(): string {
    return this.hexDraft ?? rgbToHex(this.rgb())
  }

  swatchStyle(): Record<string, string> {
    return {
      background: rgbToHex(this.rgb()),
      width: '56px',
      height: '56px',
      'border-radius': '8px',
      border: '1px solid var(--mol-color-outline, rgba(0,0,0,0.15))',
      'flex-shrink': '0',
    }
  }

  sliderStyle(): Record<string, string> {
    return {
      width: '100%',
      height: '14px',
      appearance: 'none',
      'border-radius': '7px',
      cursor: 'pointer',
    }
  }

  hueSliderStyle(): Record<string, string> {
    return {
      ...this.sliderStyle(),
      background:
        'linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)',
    }
  }

  /** The wrapper's `aria-label`. */
  groupAria(): string {
    return this.i18n.t('colorPicker.group', {}, { defaultValue: 'Color picker' })
  }

  /** The hex input's `aria-label`. */
  hexAria(): string {
    return this.i18n.t('colorPicker.hex', {}, { defaultValue: 'HEX color' })
  }

  /** The hue slider's and its label's text. */
  hueAria(): string {
    return this.i18n.t('colorPicker.hue', {}, { defaultValue: 'Hue' })
  }

  /** The saturation slider's and its label's text. */
  saturationAria(): string {
    return this.i18n.t('colorPicker.saturation', {}, { defaultValue: 'Saturation' })
  }

  /** The value slider's and its label's text. */
  valueAria(): string {
    return this.i18n.t('colorPicker.value', {}, { defaultValue: 'Value' })
  }

  /** The translated label of every RGB channel. */
  channelLabels(): Record<Channel, string> {
    return {
      r: this.i18n.t('colorPicker.r', {}, { defaultValue: 'Red' }),
      g: this.i18n.t('colorPicker.g', {}, { defaultValue: 'Green' }),
      b: this.i18n.t('colorPicker.b', {}, { defaultValue: 'Blue' }),
    }
  }

  private commitHex(raw: string): void {
    if (isValidHex(raw)) this.onChange?.(rgbToHex(hexToRgb(raw)))
    this.hexDraft = null
  }

  handleHexInput(event: Event): void {
    this.hexDraft = (event.target as HTMLInputElement).value
  }

  handleHexKeydown(event: KeyboardEvent): void {
    if (event.key !== 'Enter') return
    this.commitAndRestore(event)
  }

  commitAndRestore(event: Event): void {
    const element = event.target as HTMLInputElement
    this.commitHex(element.value)
    this.applyValue(element, rgbToHex(hexToRgb(this.value as string)))
  }

  handleHsvInput(part: 'h' | 's' | 'v', event: Event): void {
    const element = event.target as HTMLInputElement
    const hsv = this.hsv()
    const merged = {
      h: part === 'h' ? Number(element.value) : hsv.h,
      s: part === 's' ? Number(element.value) / 100 : hsv.s,
      v: part === 'v' ? Number(element.value) / 100 : hsv.v,
    }
    this.onChange?.(rgbToHex(hsvToRgb(merged)))
    const display =
      part === 'h'
        ? Math.round(hsv.h)
        : part === 's'
          ? Math.round(hsv.s * 100)
          : Math.round(hsv.v * 100)
    this.applyValue(element, String(display))
  }

  handleRgbInput(channel: Channel, event: Event): void {
    const element = event.target as HTMLInputElement
    const rgb = this.rgb()
    this.onChange?.(
      rgbToHex({
        r: channel === 'r' ? Number(element.value) : rgb.r,
        g: channel === 'g' ? Number(element.value) : rgb.g,
        b: channel === 'b' ? Number(element.value) : rgb.b,
      }),
    )
    this.applyValue(element, String(rgb[channel]))
  }

  private applyValue(element: HTMLInputElement, text: string): void {
    if (element.value !== text) element.value = text
    if (element.defaultValue !== text) element.defaultValue = text
  }

  ngAfterViewChecked(): void {
    const host = this.el.nativeElement as HTMLElement
    const sync = (id: string, text: string): void => {
      const element = host.querySelector<HTMLInputElement>(`[data-mol-id="${id}"]`)
      if (element) this.applyValue(element, text)
    }
    const rgb = this.rgb()
    const hsv = this.hsv()
    sync('color-picker-hex', this.hexShown())
    sync('color-picker-hue', String(Math.round(hsv.h)))
    sync('color-picker-saturation', String(Math.round(hsv.s * 100)))
    sync('color-picker-value', String(Math.round(hsv.v * 100)))
    sync('color-picker-r', String(rgb.r))
    sync('color-picker-g', String(rgb.g))
    sync('color-picker-b', String(rgb.b))
  }
}

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

Functions

clamp(n, lo, hi)

Clamp a number to the inclusive range [lo, hi].

function clamp(n: number, lo: number, hi: number): number
  • n — Input value.
  • lo — Lower bound.
  • hi — Upper bound.

Returns: The clamped value.

hexToRgb(hex)

Parse a #rgb/#rrggbb hex string into an RGB color. Falls back to black for unparseable input rather than throwing — pickers shouldn't crash on a stray empty string.

function hexToRgb(hex: string): RgbColor
  • hex — Color string (with or without the leading #).

Returns: The parsed RGB color.

rgbToHex(rgb)

Format an RGB color as a #rrggbb hex string (lowercase).

function rgbToHex({ r, g, b }: RgbColor): string
  • rgb — Color to format.

Returns: The hex string.

rgbToHsv(rgb)

Convert RGB (0–255) to HSV (h: 0–360, s/v: 0–1).

function rgbToHsv({ r, g, b }: RgbColor): HsvColor
  • rgb — Color to convert.

Returns: The equivalent HSV color.

hsvToRgb(hsv)

Convert HSV (h: 0–360, s/v: 0–1) to RGB (0–255).

function hsvToRgb({ h, s, v }: HsvColor): RgbColor
  • hsv — Color to convert.

Returns: The equivalent RGB color.

isValidHex(hex)

Whether hex parses to a 6-character hex color.

function isValidHex(hex: string): boolean
  • hex — Candidate hex string (with or without #).

Returns: true when the string parses cleanly.

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-i18n ^1.0.1
  • @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-i18n

  • @molecule/app-ui

  • @molecule/app-ui-angular

  • Requires a bonded ClassMap (getClassMap()) and the binding's i18n provider for the translated aria-labels — rendering throws without a ClassMap.

  • Controlled: the parent owns value and receives every change through onChange. Pure UI — render it inside whatever popover you prefer.

Translations

Translation strings are provided by @molecule/app-locales-color-picker.