# Models

> defineModel declares a value a parent binds two ways with v-model, and v-model on a form control binds to a ref. Each framework gets its own two-way binding.

A model is a value that a parent and a child both change: a stepper's count, a disclosure's open state, a field's text. The child shows the value and writes it when the person acts, and the parent holds it and may write it too. A component declares a model with `defineModel`, and a parent binds it with `v-model`. The same `v-model` binds a form control's state to a ref.

## Declaring a model

`defineModel` takes the model's name and its options, and gives a ref that the component reads and writes as `value.value`, as it would its own state:

<!-- prettier-ignore -->
```tsx [Stepper.uf.tsx]
import { defineModel } from "@uxfront/unframework";

export default function Stepper({ label }: { label: string }) {
  const value = defineModel<number>("value", { default: 0 });
  return (
    <div class="stepper">
      <button type="button" aria-label={`Fewer ${label}`} onClick={() => (value.value -= 1)}>
        -
      </button>
      <span>
        {label}: {value.value}
      </span>
      <button type="button" aria-label={`More ${label}`} onClick={() => (value.value += 1)}>
        +
      </button>
    </div>
  );
}
```

<!-- prettier-ignore -->
```tsx [Order.uf.tsx]
import { ref } from "@uxfront/unframework";

import Stepper from "./Stepper.uf.tsx";

export default function Order() {
  const cups = ref(2);
  return (
    <section aria-label="Order">
      <Stepper label="Cups" v-model:value={cups.value} />
      <output>Ordered: {cups.value}</output>
      <button type="button" onClick={() => (cups.value = 0)}>
        Clear
      </button>
    </section>
  );
}
```

A parent binds the model with `v-model:` and its name, `v-model:value={cups.value}`. The child then shows the parent's value, and a write in the child asks the parent to change it:

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [Stepper.tsx]
import { type ComponentPropsWithRef, useLayoutEffect, useRef, useState } from "react";

export interface StepperModels {
  value?: number;
  onValueChange?: (value: number) => void;
}

export type StepperAttributes = Omit<
  ComponentPropsWithRef<"div">,
  "label" | "value" | "onValueChange" | "children"
>;

export default function Stepper({
  label,
  value: valueProp,
  onValueChange,
  className,
  style,
  ...attributes
}: { label: string } & StepperModels & StepperAttributes) {
  const [localValue, setLocalValue] = useState<{ value: number }>({ value: 0 });
  const value = valueProp === undefined ? localValue.value : valueProp;
  const valueRef = useRef(value);

  useLayoutEffect(() => {
    valueRef.current = value;
  });

  return (
    <div className={cx("stepper", className)} style={style} {...attributes}>
      <button
        type="button"
        aria-label={`Fewer ${label}`}
        onClick={() => {
          valueRef.current -= 1;
          setLocalValue({ value: valueRef.current });
          onValueChange?.(valueRef.current);
        }}
      >
        -
      </button>
      <span>
        {label}: {value}
      </span>
      <button
        type="button"
        aria-label={`More ${label}`}
        onClick={() => {
          valueRef.current += 1;
          setLocalValue({ value: valueRef.current });
          onValueChange?.(valueRef.current);
        }}
      >
        +
      </button>
    </div>
  );
}

/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") {
      if (part) names.push(part);
    } else if (part && typeof part === "object") {
      for (const [key, on] of Object.entries(part)) {
        if (on) names.push(key);
      }
    }
  }
  return names.join(" ");
}
```

<!-- prettier-ignore -->
```tsx [Order.tsx]
import Stepper from "./Stepper";
import { type ComponentPropsWithRef, useRef, useState } from "react";

export type OrderAttributes = Omit<ComponentPropsWithRef<"section">, "children">;

export default function Order({ className, style, ...attributes }: OrderAttributes) {
  const [cups, setCups] = useState(2);
  const cupsRef = useRef(cups);

  return (
    <section aria-label="Order" className={className} style={style} {...attributes}>
      <Stepper
        label="Cups"
        value={cups}
        onValueChange={(value) => {
          cupsRef.current = value;
          setCups(cupsRef.current);
        }}
      />
      <output>Ordered: {cups}</output>
      <button
        type="button"
        onClick={() => {
          cupsRef.current = 0;
          setCups(cupsRef.current);
        }}
      >
        Clear
      </button>
    </section>
  );
}
```

#vue

<!-- prettier-ignore -->
```vue [Stepper.vue]
<script setup lang="ts">
const { label } = defineProps<{ label: string }>();
const value = defineModel<number>("value", { default: 0 });
</script>

<template>
  <div class="stepper">
    <button type="button" :aria-label="`Fewer ${label}`" @click="value -= 1">-</button>
    <span>{{ label }}: {{ value }}</span>
    <button type="button" :aria-label="`More ${label}`" @click="value += 1">+</button>
  </div>
</template>
```

<!-- prettier-ignore -->
```vue [Order.vue]
<script setup lang="ts">
import Stepper from "./Stepper.vue";
import { ref } from "vue";

const cups = ref(2);
</script>

<template>
  <section aria-label="Order">
    <Stepper v-model:value="cups" label="Cups" />
    <output>Ordered: {{ cups }}</output>
    <button type="button" @click="cups = 0">Clear</button>
  </section>
</template>
```

#svelte

<!-- prettier-ignore -->
```svelte [Stepper.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts">
  import type { ClassValue, SvelteHTMLElements } from "svelte/elements";

  type Props = Omit<
    SvelteHTMLElements["div"],
    "label" | "value" | "children" | "class" | "style" | "ref"
  > & {
    label: string;
    value?: number;
    class?: ClassValue;
    style?: string;
    ref?: HTMLElementTagNameMap["div"] | null;
  };

  let {
    label,
    value = $bindable(0),
    class: className,
    style,
    ref = $bindable(null),
    ...attributes
  }: Props = $props();
</script>

<div class={["stepper", className]} {style} bind:this={ref} {...attributes}>
  <button type="button" aria-label={`Fewer ${label}`} onclick={() => (value -= 1)}>-</button
  ><span>{label}: {value}</span
  ><button type="button" aria-label={`More ${label}`} onclick={() => (value += 1)}>+</button>
</div>
```

<!-- prettier-ignore -->
```svelte [Order.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts">
  import Stepper from "./Stepper.svelte";
  import type { ClassValue, SvelteHTMLElements } from "svelte/elements";

  type Props = Omit<SvelteHTMLElements["section"], "children" | "class" | "style" | "ref"> & {
    class?: ClassValue;
    style?: string;
    ref?: HTMLElementTagNameMap["section"] | null;
  };

  let { class: className, style, ref = $bindable(null), ...attributes }: Props = $props();

  let cups = $state(2);
</script>

<section aria-label="Order" class={className} {style} bind:this={ref} {...attributes}>
  <Stepper label="Cups" bind:value={cups} /><output>Ordered: {cups}</output
  ><button type="button" onclick={() => (cups = 0)}>Clear</button>
</section>
```

#angular

<!-- prettier-ignore -->
```ts [stepper.ts]
import { isPlatformBrowser } from "@angular/common";
import {
  Component,
  Directive,
  ElementRef,
  type OnChanges,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  Renderer2,
  inject,
  input,
  model,
  viewChild,
} from "@angular/core";

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

/** A native listener of each event a consumer passes, by the event's name (ADR-0118). */
type Listeners = { [K in keyof HTMLElementEventMap]?: (event: HTMLElementEventMap[K]) => void };

/**
 * Puts what a consumer passes the component, and the component does not declare, on the element
 * that takes it (ADR-0118): the attributes, the consumer's winning over the element's own, and
 * the native listeners, which run after the element's own.
 */
@Directive({ selector: "[ufFallthrough]" })
export class Fallthrough implements OnChanges, OnDestroy {
  readonly ufFallthrough = input.required<{
    attributes: Record<string, unknown> | undefined;
    listeners: Listeners | undefined;
  }>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID));
  private readonly listening = new Map<string, { handler: unknown; stop: () => void }>();
  private written: Record<string, unknown> = {};

  ngOnChanges(): void {
    const element = this.element.nativeElement;
    const { attributes = {}, listeners = {} } = this.ufFallthrough();
    for (const name of Object.keys(this.written)) {
      if (!(name in attributes)) this.renderer.removeAttribute(element, name);
    }
    for (const [name, value] of Object.entries(attributes)) {
      if (value === null || value === undefined) this.renderer.removeAttribute(element, name);
      else this.renderer.setAttribute(element, name, String(value));
    }
    this.written = attributes;
    if (!this.browser) return;
    const handlers = new Map(Object.entries(listeners));
    for (const [event, { handler, stop }] of this.listening) {
      if (handlers.get(event) === handler) continue;
      stop();
      this.listening.delete(event);
    }
    for (const [event, handler] of handlers) {
      if (handler === undefined || this.listening.has(event)) continue;
      this.listening.set(event, { handler, stop: this.renderer.listen(element, event, handler) });
    }
  }

  ngOnDestroy(): void {
    for (const { stop } of this.listening.values()) stop();
  }
}

@Component({
  selector: "uf-stepper",
  imports: [ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let label = this.label();
    @let value = this.value();
    <div
      class="stepper"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >
      <button type="button" [attr.aria-label]="'Fewer ' + label" (click)="onClick()">-</button>
      <span>{{ label }}: {{ value }}</span>
      <button type="button" [attr.aria-label]="'More ' + label" (click)="onClick_1()">+</button>
    </div>
  `,
})
export default class Stepper {
  readonly label = input.required<string>();
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly value = model<number>(0);
  readonly ufElement = viewChild<ElementRef<HTMLDivElement>>("ufElement");

  protected onClick() {
    this.value.update((value) => value - 1);
  }

  protected onClick_1() {
    this.value.update((value) => value + 1);
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

<!-- prettier-ignore -->
```ts [order.ts]
import Stepper from "./stepper";
import { isPlatformBrowser } from "@angular/common";
import {
  Component,
  Directive,
  ElementRef,
  type OnChanges,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  Renderer2,
  inject,
  input,
  signal,
  viewChild,
} from "@angular/core";

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

/** A native listener of each event a consumer passes, by the event's name (ADR-0118). */
type Listeners = { [K in keyof HTMLElementEventMap]?: (event: HTMLElementEventMap[K]) => void };

/**
 * Puts what a consumer passes the component, and the component does not declare, on the element
 * that takes it (ADR-0118): the attributes, the consumer's winning over the element's own, and
 * the native listeners, which run after the element's own.
 */
@Directive({ selector: "[ufFallthrough]" })
export class Fallthrough implements OnChanges, OnDestroy {
  readonly ufFallthrough = input.required<{
    attributes: Record<string, unknown> | undefined;
    listeners: Listeners | undefined;
  }>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID));
  private readonly listening = new Map<string, { handler: unknown; stop: () => void }>();
  private written: Record<string, unknown> = {};

  ngOnChanges(): void {
    const element = this.element.nativeElement;
    const { attributes = {}, listeners = {} } = this.ufFallthrough();
    for (const name of Object.keys(this.written)) {
      if (!(name in attributes)) this.renderer.removeAttribute(element, name);
    }
    for (const [name, value] of Object.entries(attributes)) {
      if (value === null || value === undefined) this.renderer.removeAttribute(element, name);
      else this.renderer.setAttribute(element, name, String(value));
    }
    this.written = attributes;
    if (!this.browser) return;
    const handlers = new Map(Object.entries(listeners));
    for (const [event, { handler, stop }] of this.listening) {
      if (handlers.get(event) === handler) continue;
      stop();
      this.listening.delete(event);
    }
    for (const [event, handler] of handlers) {
      if (handler === undefined || this.listening.has(event)) continue;
      this.listening.set(event, { handler, stop: this.renderer.listen(element, event, handler) });
    }
  }

  ngOnDestroy(): void {
    for (const { stop } of this.listening.values()) stop();
  }
}

@Component({
  selector: "uf-order",
  imports: [Stepper, ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let cups = this.cups();
    <section
      aria-label="Order"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >
      <uf-stepper [label]="'Cups'" [(value)]="this.cups" />
      <output>Ordered: {{ cups }}</output>
      <button type="button" (click)="onClear()">Clear</button>
    </section>
  `,
})
export default class Order {
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly ufElement = viewChild<ElementRef<HTMLElement>>("ufElement");
  protected readonly cups = signal(2);

  protected onClear() {
    this.cups.set(0);
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

<!-- prettier-ignore -->
```tsx [Stepper.tsx]
import { type ComponentProps, type JSX, createSignal, splitProps } from "solid-js";

export interface StepperModels {
  value?: number;
  onValueChange?: (value: number) => void;
}

export default function Stepper(
  props: { label: string } & StepperModels &
    Omit<ComponentProps<"div">, "label" | "value" | "style"> & { style?: JSX.CSSProperties },
) {
  const [, others] = splitProps(props, ["label", "value", "onValueChange", "class"]);

  const [localValue, setLocalValue] = createSignal<number>(0);
  const value = () => (props.value === undefined ? localValue() : props.value);

  function setValue(next: number) {
    setLocalValue(next);
    props.onValueChange?.(next);
  }

  return (
    <div class={props.class ? `stepper ${props.class}` : "stepper"} {...others}>
      <button
        type="button"
        aria-label={`Fewer ${props.label}`}
        onClick={() => setValue(value() - 1)}
      >
        -
      </button>
      <span>
        {props.label}: {value()}
      </span>
      <button
        type="button"
        aria-label={`More ${props.label}`}
        onClick={() => setValue(value() + 1)}
      >
        +
      </button>
    </div>
  );
}
```

<!-- prettier-ignore -->
```tsx [Order.tsx]
import Stepper from "./Stepper";
import { type ComponentProps, type JSX, createSignal } from "solid-js";

export default function Order(
  props: Omit<ComponentProps<"section">, "style"> & { style?: JSX.CSSProperties },
) {
  const [cups, setCups] = createSignal(2);

  return (
    <section aria-label="Order" {...props}>
      <Stepper label="Cups" value={cups()} onValueChange={setCups} />
      <output>Ordered: {cups()}</output>
      <button type="button" onClick={() => setCups(0)}>
        Clear
      </button>
    </section>
  );
}
```

#qwik

<!-- prettier-ignore -->
```tsx [Stepper.tsx]
import {
  $,
  type CSSProperties,
  type ClassList,
  type PropsOf,
  type QRL,
  component$,
  useComputed$,
  useSignal,
} from "@qwik.dev/core";

export interface StepperModels {
  value?: number;
  onValueChange$?: QRL<(value: number) => void>;
}

export default component$<
  { label: string } & StepperModels &
    Omit<PropsOf<"div">, "label" | "value" | "onValueChange$" | "class" | "style"> & {
      class?: ClassList;
      style?: CSSProperties;
    }
>(({ label, value: valueProp, onValueChange$, class: className, style, ...attributes }) => {
  const valueLocal = useSignal<number>(0);
  const value = useComputed$(() => (valueProp === undefined ? valueLocal.value : valueProp));

  const setValue = $(async (next: number) => {
    if (valueProp === undefined) valueLocal.value = next;
    await onValueChange$?.(next);
  });

  return (
    <div class={["stepper", className]} style={style} {...attributes}>
      <button
        type="button"
        aria-label={`Fewer ${label}`}
        onClick$={() => setValue(value.value - 1)}
      >
        -
      </button>
      <span>
        {label}: {value.value}
      </span>
      <button type="button" aria-label={`More ${label}`} onClick$={() => setValue(value.value + 1)}>
        +
      </button>
    </div>
  );
});
```

<!-- prettier-ignore -->
```tsx [Order.tsx]
import Stepper from "./Stepper";
import {
  type CSSProperties,
  type ClassList,
  type PropsOf,
  component$,
  useSignal,
} from "@qwik.dev/core";

export default component$<
  Omit<PropsOf<"section">, "class" | "style"> & { class?: ClassList; style?: CSSProperties }
>(({ class: className, style, ...attributes }) => {
  const cups = useSignal(2);

  return (
    <section aria-label="Order" class={className} style={style} {...attributes}>
      <Stepper label="Cups" value={cups.value} onValueChange$={(value) => (cups.value = value)} />
      <output>Ordered: {cups.value}</output>
      <button type="button" onClick$={() => (cups.value = 0)}>
        Clear
      </button>
    </section>
  );
});
```

#astro

<!-- prettier-ignore -->
```astro [Stepper.astro]
---
import type { HTMLAttributes } from "astro/types";

interface Props extends Omit<HTMLAttributes<"div">, "label" | "value"> {
  label: string;
  value?: number;
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { label, value = 0, class: className, style, ...attrs } = Astro.props;
---

<div class:list={["stepper", className]} style={style} {...attrs}>
  <button type="button" aria-label={`Fewer ${label}`}>-</button>
  <span>{label}: {value}</span>
  <button type="button" aria-label={`More ${label}`}>+</button>
</div>
```

<!-- prettier-ignore -->
```astro [Order.astro]
---
import Stepper from "./Stepper.astro";
import type { HTMLAttributes } from "astro/types";

interface Props extends HTMLAttributes<"section"> {
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { class: className, style, "aria-label": ariaLabel, ...attrs } = Astro.props;

const cups = 2 as number;
---

<section
  aria-label={"aria-label" in Astro.props ? ariaLabel : "Order"}
  class:list={[className]}
  style={style}
  {...attrs}
>
  <Stepper label="Cups" value={cups} />
  <output>Ordered: {cups}</output>
  <button type="button">Clear</button>
</section>
```

::

- React, Solid and Qwik give a model two props: the value, `value`, and a callback, `onValueChange`, which Qwik writes `onValueChange$`. They are exported as `StepperModels`. The parent passes both, and its callback writes its own state.
- Vue writes `defineModel`, and the parent `v-model:value`.
- Svelte declares the prop `$bindable(0)`, and the parent binds it with `bind:value`.
- Angular declares `model<number>(0)`, and the parent binds a signal two ways, `[(value)]="this.cups"`.
- Astro renders the model's value, and the parent passes its state as the prop, `value={cups}`. Nothing changes it there: Astro renders on the server only (`model` is native, and the binding is inert).

The name is a string literal, and the options, `default` and `required`, are static values, as a prop's default is ([UF2028](/docs/reference/diagnostics#UF2028), whose fix names a nameless model `"value"`). Every target names the prop after the model, and React, Solid and Qwik its callback too, `onValueChange`.

## Bound and unbound

A child doesn't need its parent to bind a model. Unbound, it keeps the value as local state, which starts at its `default`:

<!-- prettier-ignore -->
```tsx [Disclosure.uf.tsx]
import { defineModel } from "@uxfront/unframework";

export default function Disclosure({ title }: { title: string }) {
  const open = defineModel<boolean>("open", { default: false });
  return (
    <div class="disclosure">
      <button type="button" aria-expanded={open.value} onClick={() => (open.value = !open.value)}>
        {title}
      </button>
      {open.value && <p>Details of {title}</p>}
    </div>
  );
}
```

<!-- prettier-ignore -->
```tsx [Panels.uf.tsx]
import { ref } from "@uxfront/unframework";

import Disclosure from "./Disclosure.uf.tsx";

export default function Panels() {
  const shipping = ref(true);
  return (
    <section aria-label="Panels">
      <Disclosure title="Shipping" v-model:open={shipping.value} />
      <Disclosure title="Returns" />
      <output>Shipping is {shipping.value ? "open" : "closed"}</output>
      <button type="button" onClick={() => (shipping.value = !shipping.value)}>
        Toggle shipping
      </button>
    </section>
  );
}
```

The "Shipping" disclosure shows its parent's `shipping` and asks the parent to change it, so the parent's button opens and closes it too. The "Returns" disclosure, unbound, opens and closes by itself. React, Solid and Qwik tell the two apart by `value === undefined`: a model bound to `undefined` acts unbound there, so bind a model to a value that is never `undefined` ([Semantics](/docs/reference/semantics#models)).

A component may declare several models, and a parent binds each one with its name:

<!-- prettier-ignore -->
```tsx [Search.uf.tsx]
<PriceRange label="Price" v-model:min={low.value} v-model:max={high.value} />
```

`v-model` without a name, on a component, is [UF3042](/docs/reference/diagnostics#UF3042), whose fix names the model of a child that declares one. A name the child doesn't declare is [UF3037](/docs/reference/diagnostics#UF3037), with a fix to the closest model.

## Form controls

`v-model` on a form control binds the control's state to a ref, `v-model={name.value}`:

<!-- prettier-ignore -->
```tsx [ContactForm.uf.tsx]
import { ref } from "@uxfront/unframework";

export default function ContactForm() {
  const name = ref("Ada");
  const email = ref("");
  return (
    <form aria-label="Contact">
      <label>
        Name <input v-model={name.value} />
      </label>
      <label>
        Email <input type="email" v-model={email.value} />
      </label>
      <output>
        {name.value} at {email.value || "no address"}
      </output>
      <button type="button" onClick={() => (name.value = "Grace")}>
        Use Grace
      </button>
    </form>
  );
}
```

::framework-switcher

#react

<!-- prettier-ignore -->
```tsx [ContactForm.tsx]
import { type ComponentPropsWithRef, useRef, useState } from "react";

export type ContactFormAttributes = Omit<ComponentPropsWithRef<"form">, "children">;

export default function ContactForm({ className, style, ...attributes }: ContactFormAttributes) {
  const [name, setName] = useState("Ada");
  const nameRef = useRef(name);
  const [email, setEmail] = useState("");

  return (
    <form aria-label="Contact" className={className} style={style} {...attributes}>
      <label>
        Name{" "}
        <input
          value={name}
          onChange={(event) => {
            nameRef.current = event.target.value;
            setName(nameRef.current);
          }}
        />
      </label>
      <label>
        Email{" "}
        <input type="email" value={email} onChange={(event) => setEmail(event.target.value)} />
      </label>
      <output>
        {name} at {email || "no address"}
      </output>
      <button
        type="button"
        onClick={() => {
          nameRef.current = "Grace";
          setName(nameRef.current);
        }}
      >
        Use Grace
      </button>
    </form>
  );
}
```

#vue

<!-- prettier-ignore -->
```vue [ContactForm.vue]
<script setup lang="ts">
import { ref } from "vue";

const name = ref("Ada");
const email = ref("");
</script>

<template>
  <form aria-label="Contact">
    <label>Name <input v-model="name" /></label>
    <label>Email <input v-model="email" type="email" /></label>
    <output>{{ name }} at {{ email || "no address" }}</output>
    <button type="button" @click="name = 'Grace'">Use Grace</button>
  </form>
</template>
```

#svelte

<!-- prettier-ignore -->
```svelte [ContactForm.svelte]
<svelte:options runes={true} preserveWhitespace={false} />

<script lang="ts">
  import type { ClassValue, HTMLFormAttributes } from "svelte/elements";

  type Props = Omit<HTMLFormAttributes, "children" | "class" | "style" | "ref"> & {
    class?: ClassValue;
    style?: string;
    ref?: HTMLElementTagNameMap["form"] | null;
  };

  let { class: className, style, ref = $bindable(null), ...attributes }: Props = $props();

  let name = $state("Ada");
  let email = $state("");
</script>

<form aria-label="Contact" class={className} {style} bind:this={ref} {...attributes}>
  <label>Name <input bind:value={name} /></label
  ><label>Email <input type="email" bind:value={email} /></label
  ><output>{name} at {email || "no address"}</output
  ><button type="button" onclick={() => (name = "Grace")}>Use Grace</button>
</form>
```

#angular

<!-- prettier-ignore -->
```ts [contact-form.ts]
import { isPlatformBrowser } from "@angular/common";
import {
  Component,
  Directive,
  ElementRef,
  type OnChanges,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  Renderer2,
  inject,
  input,
  signal,
  viewChild,
} from "@angular/core";

/** The scope attributes taken off each host, for the roots its component renders later. */
const scopes = new WeakMap<Element, string[]>();

/**
 * Gives a root node of its component the scope attributes the component's styled parents put on
 * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.
 */
@Directive({ selector: "[ufScope]" })
export class ScopeAttributes implements OnInit {
  readonly ufScope = input.required<HTMLElement>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);

  ngOnInit(): void {
    const host = this.ufScope();
    let names = scopes.get(host);
    if (!names) {
      names = host.getAttributeNames().filter((name) => name.startsWith("data-uf-"));
      for (const name of names) this.renderer.removeAttribute(host, name);
      scopes.set(host, names);
    }
    for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, "");
  }
}

/** A native listener of each event a consumer passes, by the event's name (ADR-0118). */
type Listeners = { [K in keyof HTMLElementEventMap]?: (event: HTMLElementEventMap[K]) => void };

/**
 * Puts what a consumer passes the component, and the component does not declare, on the element
 * that takes it (ADR-0118): the attributes, the consumer's winning over the element's own, and
 * the native listeners, which run after the element's own.
 */
@Directive({ selector: "[ufFallthrough]" })
export class Fallthrough implements OnChanges, OnDestroy {
  readonly ufFallthrough = input.required<{
    attributes: Record<string, unknown> | undefined;
    listeners: Listeners | undefined;
  }>();
  private readonly element = inject<ElementRef<Element>>(ElementRef);
  private readonly renderer = inject(Renderer2);
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID));
  private readonly listening = new Map<string, { handler: unknown; stop: () => void }>();
  private written: Record<string, unknown> = {};

  ngOnChanges(): void {
    const element = this.element.nativeElement;
    const { attributes = {}, listeners = {} } = this.ufFallthrough();
    for (const name of Object.keys(this.written)) {
      if (!(name in attributes)) this.renderer.removeAttribute(element, name);
    }
    for (const [name, value] of Object.entries(attributes)) {
      if (value === null || value === undefined) this.renderer.removeAttribute(element, name);
      else this.renderer.setAttribute(element, name, String(value));
    }
    this.written = attributes;
    if (!this.browser) return;
    const handlers = new Map(Object.entries(listeners));
    for (const [event, { handler, stop }] of this.listening) {
      if (handlers.get(event) === handler) continue;
      stop();
      this.listening.delete(event);
    }
    for (const [event, handler] of handlers) {
      if (handler === undefined || this.listening.has(event)) continue;
      this.listening.set(event, { handler, stop: this.renderer.listen(element, event, handler) });
    }
  }

  ngOnDestroy(): void {
    for (const { stop } of this.listening.values()) stop();
  }
}

@Component({
  selector: "uf-contact-form",
  imports: [ScopeAttributes, Fallthrough],
  host: { "[attr.class]": "null", "[attr.style]": "'display: contents;'" },
  preserveWhitespaces: false,
  template: `
    @let name = this.name();
    @let email = this.email();
    <form
      aria-label="Contact"
      [class]="this.class()"
      [style]="this.style()"
      [ufFallthrough]="{ attributes: this.ufAttributes(), listeners: this.ufListeners() }"
      [ufScope]="this.host"
      #ufElement
    >
      <label>Name <input
        #nameField
        [value]="this.name()"
        (input)="this.name.set(nameField.value)"
      /></label>
      <label>Email <input
        type="email"
        #emailField
        [value]="this.email()"
        (input)="this.email.set(emailField.value)"
      /></label>
      <output>{{ name }} at {{ email || "no address" }}</output>
      <button type="button" (click)="onUseGrace()">Use Grace</button>
    </form>
  `,
})
export default class ContactForm {
  readonly class = input<string>();
  readonly style = input<Record<string, string | null | undefined>>();
  readonly ufAttributes = input<Record<string, unknown>>();
  readonly ufListeners = input<Listeners>();
  readonly ufElement = viewChild<ElementRef<HTMLFormElement>>("ufElement");
  protected readonly name = signal("Ada");
  protected readonly email = signal("");

  protected onUseGrace() {
    this.name.set("Grace");
  }
  protected readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
}
```

#solid

<!-- prettier-ignore -->
```tsx [ContactForm.tsx]
import { type ComponentProps, type JSX, createSignal } from "solid-js";

export default function ContactForm(
  props: Omit<ComponentProps<"form">, "style"> & { style?: JSX.CSSProperties },
) {
  const [name, setName] = createSignal("Ada");
  const [email, setEmail] = createSignal("");

  return (
    <form aria-label="Contact" {...props}>
      <label>
        Name <input value={name()} onInput={(event) => setName(event.currentTarget.value)} />
      </label>
      <label>
        Email{" "}
        <input
          type="email"
          value={email()}
          onInput={(event) => setEmail(event.currentTarget.value)}
        />
      </label>
      <output>
        {name()} at {email() || "no address"}
      </output>
      <button type="button" onClick={() => setName("Grace")}>
        Use Grace
      </button>
    </form>
  );
}
```

#qwik

<!-- prettier-ignore -->
```tsx [ContactForm.tsx]
import {
  type CSSProperties,
  type ClassList,
  type PropsOf,
  component$,
  useSignal,
} from "@qwik.dev/core";

export default component$<
  Omit<PropsOf<"form">, "class" | "style"> & { class?: ClassList; style?: CSSProperties }
>(({ class: className, style, ...attributes }) => {
  const name = useSignal("Ada");
  const email = useSignal("");

  const currentName = name.value;
  const currentEmail = email.value;

  return (
    <form aria-label="Contact" class={className} style={style} {...attributes}>
      <label>
        Name <input value={currentName} onInput$={(_, element) => (name.value = element.value)} />
      </label>
      <label>
        Email{" "}
        <input
          type="email"
          value={currentEmail}
          onInput$={(_, element) => (email.value = element.value)}
        />
      </label>
      <output>
        {name.value} at {email.value || "no address"}
      </output>
      <button type="button" onClick$={() => (name.value = "Grace")}>
        Use Grace
      </button>
    </form>
  );
});
```

#astro

<!-- prettier-ignore -->
```astro [ContactForm.astro]
---
import type { HTMLAttributes } from "astro/types";

interface Props extends HTMLAttributes<"form"> {
  class?: string;
  style?: Record<string, string | number | undefined>;
}

const { class: className, style, "aria-label": ariaLabel, ...attrs } = Astro.props;

const name = "Ada" as string;
const email = "" as string;
---

<form
  aria-label={"aria-label" in Astro.props ? ariaLabel : "Contact"}
  class:list={[className]}
  style={style}
  {...attrs}
>
  <label>Name <input value={name} /></label>
  <label>Email <input type="email" value={email} /></label>
  <output>{name} at {email || "no address"}</output>
  <button type="button">Use Grace</button>
</form>
```

::

What `v-model` binds depends on the control:

- the value of an `<input>` without a `type`, or of type `text`, `search`, `email`, `url`, `tel`, `password`, `date`, `time`, `datetime-local`, `month`, `week` or `color`, which Vue binds as text;
- the value of a `<textarea>` and of a `<select>`;
- the checked state of a checkbox, a boolean, and of a radio, the radio's `value`;
- an array of `value`s for checkboxes that share one ref, and for a `<select multiple>`;
- a number for an `<input>` of type `number` or `range`.

Each framework writes its own binding:

| Control                       | React                          | Vue       | Svelte         | Angular                                                             | Solid                                     | Qwik                                       | Astro                  |
| ----------------------------- | ------------------------------ | --------- | -------------- | ------------------------------------------------------------------- | ----------------------------------------- | ------------------------------------------ | ---------------------- |
| A text field, a `<textarea>`  | `value` and `onChange`         | `v-model` | `bind:value`   | `[value]` and `(input)`                                             | `value` and `onInput`                     | `value`, read in render, and `onInput$`    | its initial value      |
| A checkbox                    | `checked` and `onChange`       | `v-model` | `bind:checked` | `[checked]` and `(change)`                                          | `checked` and `onChange`                  | `checked` and `onChange$`                  | its initial `checked`  |
| A radio                       | `checked={plan === "monthly"}` | `v-model` | `bind:group`   | `[checked]` and `(change)`                                          | as React                                  | as React, with `onChange$`                 | its initial `checked`  |
| A `<select>`                  | `value` and `onChange`         | `v-model` | `bind:value`   | `[defaultSelected]` and `[selected]` on each option, and `(change)` | `selected` on each option, and `onChange` | `selected` on each option, and `onChange$` | its initial `selected` |
| Checkboxes into an array      | `toggle`                       | `v-model` | `bind:group`   | `toggle`                                                            | `toggle`                                  | `toggle`                                   | its initial `checked`  |
| A `<select multiple>`         | `value`, an array              | `v-model` | `bind:value`   | `selectedValues`                                                    | `selectedValues`                          | `selectedValues`                           | its initial `selected` |
| A number or range, a modifier | `modelText`                    | `v-model` | `modelText`    | `modelText`                                                         | `modelText`                               | `modelText`                                | its initial value      |

`toggle`, `selectedValues` and `modelText` are small inline helpers that each output declares where it needs them, as Vue's own `v-model` behaves ([`model-array`](/docs/reference/targets#capabilities) and [`model-modifiers`](/docs/reference/targets#capabilities)). React's `modelText` is a hook, `useModelText`. On Astro every `v-model` renders the control's initial state and does nothing more, since nothing runs in the browser (`two-way-binding`, for information).

The bound value is a ref's or a model's `.value`. Anything else is [UF3042](/docs/reference/diagnostics#UF3042): a file, button or hidden input, a value that is no ref's, or a modifier on a control that holds no text.

## Modifiers

Vue's three `v-model` modifiers are written with an underscore, since JSX has no `.` in an attribute's name:

<!-- prettier-ignore -->
```tsx [Profile.uf.tsx]
import { ref } from "@uxfront/unframework";

export default function Profile() {
  const name = ref("");
  const city = ref("Lisbon");
  const weight = ref(0);
  return (
    <form aria-label="Profile">
      <label>
        Name <input v-model_trim={name.value} />
      </label>
      <label>
        City <input v-model_lazy={city.value} />
      </label>
      <label>
        Weight <input v-model_number={weight.value} />
      </label>
      <output>
        [{name.value}] from {city.value}, {weight.value + 1}
      </output>
    </form>
  );
}
```

- `v-model_trim` trims the text the ref receives, and the field once it commits.
- `v-model_lazy` writes the ref on `change`, when the field commits, rather than on every `input`. React writes it as the field loses focus, so Enter alone doesn't commit it there.
- `v-model_number` casts the text to a number where it reads as one, as Vue's `looseToNumber` does, and an `<input>` of type `number` or `range` casts the same way without it.

A text field updates its ref on `input` events on every target. While someone composes text with an input method, as for Japanese or Chinese, Vue waits for the composition to end and the other targets don't: that difference is outside the contract.

The decisions behind this page are [ADR-0054](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0054-composition-on-every-target.md) and [ADR-0058](https://github.com/uxfront-com/unframework/blob/main/docs/adrs/0058-normalising-slot-templates-and-bound-values.md).
