Usage
import { randomId } from 'ngwr/utils';
const id = randomId('wr-input'); // 'wr-input-a8f2bx1k9q4z' (12 chars)
const short = randomId('wr-input', 6); // 'wr-input-h7m4k2'Why ngwr provides this
Every component that pairs a label with a control (<label for>, aria-describedby, aria-controls) needs a stable unique id per instance. Each native option is unsatisfying: Math.random() collides under load, Date.now() collides on the same tick, crypto.randomUUID() is 36 chars and isn't in every SSR runtime. randomId is short, prefixed, and SSR-safe.
// Native options all have downsides:
const a = Math.random().toString(36).slice(2); // collides under load, no prefix
const b = `id-${Date.now()}`; // collides when called twice the same tick
const c = crypto.randomUUID(); // 36 chars, ugly in HTML, not in every SSR runtime
// ngwr — short, prefixed, collision-resistant, SSR-safe.
const id = randomId('wr-input'); // 'wr-input-a8f2bx1k9q4z'API
| Name | Description | Type | Default |
|---|---|---|---|
randomId(prefix?, length?, random?) | Generates a stable random id like wr-input-a8f2bx1k9q4z. Safe for SSR (uses crypto when available). length is the random segment only, clamped to [4, 64]; random replaces the byte source, which is what makes an id deterministic in a test. | (prefix = 'wr', length = 12, random?: (byteLength: number) => Uint8Array) => string | — |