Formularios
Checkbox
Un control que permite al usuario alternar entre marcado y no marcado.
Ejemplo
You agree to our Terms of Service.
El ejemplo de arriba es este archivo, renderizado en vivo:
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
import { VoltCheckbox, VoltLabel } from '@voltui/components';
/** A "select all" parent whose mixed state is derived from its children. */
@Component({
selector: 'app-checkbox-example',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [VoltCheckbox, VoltLabel],
template: `
<div class="mx-auto max-w-sm space-y-6">
<div class="flex items-start gap-3">
<volt-checkbox id="terms" [(checked)]="terms" />
<div class="grid gap-1.5 leading-none">
<volt-label htmlFor="terms" class="cursor-pointer"
>Accept terms and conditions</volt-label
>
<p class="text-sm text-muted-foreground">You agree to our Terms of Service.</p>
</div>
</div>
<fieldset class="space-y-3">
<legend class="sr-only">Notifications</legend>
<div class="flex items-center gap-3">
<volt-checkbox
id="all"
[checked]="allChecked()"
[indeterminate]="someChecked()"
(checkedChange)="setAll($event)"
/>
<volt-label htmlFor="all">All notifications</volt-label>
</div>
@for (channel of channels(); track channel.id) {
<div class="flex items-center gap-3 pl-7">
<volt-checkbox
[id]="channel.id"
[checked]="channel.on"
(checkedChange)="toggle(channel.id, $event)"
/>
<volt-label [htmlFor]="channel.id">{{ channel.label }}</volt-label>
</div>
}
</fieldset>
</div>
`,
})
export class CheckboxExample {
readonly terms = signal(false);
readonly channels = signal([
{ id: 'email', label: 'Email', on: true },
{ id: 'sms', label: 'SMS', on: false },
{ id: 'push', label: 'Push', on: false },
]);
readonly allChecked = computed(() => this.channels().every(channel => channel.on));
readonly someChecked = computed(
() => !this.allChecked() && this.channels().some(channel => channel.on)
);
setAll(on: boolean): void {
this.channels.update(channels => channels.map(channel => ({ ...channel, on })));
}
toggle(id: string, on: boolean): void {
this.channels.update(channels =>
channels.map(channel => (channel.id === id ? { ...channel, on } : channel))
);
}
}
Zona de pruebas
Cambia los inputs e interactúa con la vista previa: el panel de eventos muestra lo que emite el componente y el código sigue tus ajustes.
volt-checkbox
aria-checked: false
Aún no hay eventos. Interactúa con la vista previa para verlos aquí.
HTML
<volt-checkbox id="releases" />Formularios y accesibilidad
<volt-checkbox>renderiza un<button role="checkbox">nativo;idyaria-labelpasan a él. Nómbralo con un<volt-label htmlFor>que apunte a suid, o conaria-label.aria-checkedestrue,falseomixed(indeterminate). La tecla Espacio lo activa; activar una casilla mixta la deja marcada y notificaindeterminateChange(false).- Con Forms, el valor del control es el booleano
checked. Una activación del usuario lo notifica una vez y marca el control como modificado; un valor que escribe tu código no. indeterminatesigue siendo tuyo: una escritura de Forms del valor que la casilla ya tiene (la escritura inicial, un padre "seleccionar todo" que se resincroniza) lo conserva; una escritura que cambia el valor lo resuelve.- Se marca como tocada al perder el foco;
aria-invalid="true"cuando el control es inválido y está tocado.requiredfijaaria-required. - Sin
id, recibe uno generado y numerado por aplicación, de modo que el renderizado en servidor y la hidratación coinciden. - El punto de entrada experimental de Quartz (
@voltui/components/quartz) pasa las mismas pruebas de contrato.
@voltui/components/quartz requiere @voltui/components 1.4.1 o posterior. La última versión en npm cuando se generó esta página era la 1.3.3.Referencia de la API
| Entrada | Tipo | Por defecto |
|---|---|---|
| id | unknown | injectVoltId('volt-checkbox') |
| ariaLabel | string | '' |
| aria-label | string | undefined | undefined |
| checked | boolean | false |
| indeterminate | boolean | false |
| disabled | boolean | false |
| required | boolean | false |
| Salida | Tipo |
|---|---|
| checkedChange | boolean |
| indeterminateChange | boolean |
Instalación
Copia el código en tu proyecto:
npx @voltui/cli add checkbox
O impórtalo desde el paquete:
npm install @voltui/components
Código fuente
Copia este código en tu proyecto. El componente usa ng-primitives/checkbox.
import {
booleanAttribute,
ChangeDetectionStrategy,
Component,
computed,
forwardRef,
input,
model,
signal,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NgpCheckbox } from 'ng-primitives/checkbox';
import { injectFormControlState } from '../../form-control-state';
import { forwardAttributesFromHost } from '../../host-forwarding';
import { injectVoltId } from '../../volt-ids';
@Component({
selector: 'volt-checkbox',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NgpCheckbox],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => VoltCheckbox),
multi: true,
},
],
template: `
<button
ngpCheckbox
type="button"
[id]="id()"
[ngpCheckboxChecked]="checked()"
[ngpCheckboxIndeterminate]="indeterminate()"
[ngpCheckboxDisabled]="isDisabled()"
[ngpCheckboxRequired]="required()"
[attr.aria-label]="ariaLabel() || ariaLabelAttribute() || null"
[attr.aria-invalid]="formControlState.invalid() ? 'true' : null"
(ngpCheckboxCheckedChange)="onCheckedChange($event)"
(ngpCheckboxIndeterminateChange)="onIndeterminateChange($event)"
(blur)="onTouched()"
class="peer flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-sm border-(length:--volt-control-border-width) border-primary ring-offset-background focus-visible:outline-hidden focus-visible:ring-(length:--ring-width) focus-visible:ring-ring focus-visible:ring-offset-(length:--ring-offset-width) disabled:cursor-not-allowed disabled:opacity-50 data-[checked]:bg-primary data-[checked]:text-primary-foreground data-[indeterminate]:bg-primary data-[indeterminate]:text-primary-foreground"
>
@if (indeterminate()) {
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="h-3 w-3"
aria-hidden="true"
>
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
} @else if (checked()) {
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="h-3 w-3"
aria-hidden="true"
>
<polyline points="20 6 9 17 4 12"></polyline>
</svg>
}
</button>
`,
})
export class VoltCheckbox implements ControlValueAccessor {
protected readonly formControlState = injectFormControlState();
readonly id = input(injectVoltId('volt-checkbox'));
/** Accessible name for a checkbox without a visible `<label>`. */
readonly ariaLabel = input('');
/** Same as `ariaLabel`, for the attribute spelling consumers write naturally. */
// eslint-disable-next-line @angular-eslint/no-input-rename -- mirrors VoltSwitch: `ariaLabel` owns the camelCase name
readonly ariaLabelAttribute = input<string | undefined>(undefined, { alias: 'aria-label' });
readonly checked = model(false);
readonly indeterminate = model(false);
readonly disabled = input<boolean, unknown>(false, { transform: booleanAttribute });
readonly required = input<boolean, unknown>(false, { transform: booleanAttribute });
private readonly controlDisabled = signal(false);
protected readonly isDisabled = computed(() => this.disabled() || this.controlDisabled());
private onChange: (value: boolean) => void = () => {};
protected onTouched: () => void = () => {};
constructor() {
// Both belong to the native button; a copy on the host would duplicate them.
forwardAttributesFromHost('id', 'aria-label');
}
protected onCheckedChange(value: boolean): void {
this.checked.set(value);
this.onChange(value);
}
protected onIndeterminateChange(value: boolean): void {
// model() emits `indeterminateChange` itself; a second output of that name is an error in Angular 22.
this.indeterminate.set(value);
}
writeValue(value: boolean | null | undefined): void {
const next = !!value;
// A write that changes the value resolves a mixed state. Writing the value the checkbox already
// has — the forms setup write, a "select all" parent re-syncing — leaves the consumer's
// `indeterminate` binding alone; clearing it there wiped a bound mixed state that the parent's
// unchanged binding would never send again.
if (next !== this.checked()) {
this.checked.set(next);
this.indeterminate.set(false);
}
}
registerOnChange(fn: (value: boolean) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.controlDisabled.set(isDisabled);
}
}