Skip to content

Chips

Compact choices to pick from, or tags to type.

View as Markdown

Example

Sizes

xs, sm, md (default) and lg: set size="sm" on it, or data-size="sm" on any container, as here. See Theming.

Vegan
Halal
xs
Vegan
Halal
sm
Vegan
Halal
md
Vegan
Halal
lg

Installation

npx fizzy-ui add chips

Copies chips.ts into src/app/ui/ and installs what it needs. Run init once first.

Keyboard

KeyAction
← / →Move between chips (chip listbox)
SpaceToggle the focused chip
Enter / ,Add the typed tag (chip input)
BackspaceIn the empty input, remove the last tag

Accessibility

No axe-core violations axe-core 4.14.0 checks this example, closed and with its panels open, on every build; the site is not published otherwise.

  • A chip listbox is a horizontal listbox with one Tab stop; aria-label goes on fz-chip-listbox and moves to the listbox.
  • A chip input is a real <input>: label it with fzField or aria-label. Each tag has a "Remove …" button.
  • Added and removed tags are announced, since the input itself does not change.

Testing

FzChipListboxHarness drives it in your tests, the way a user would, with the Angular CDK harness API. --harness also copies chips.harness.ts; its methods are documented in the file.

npx fizzy-ui add chips --harness
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { FzChipListboxHarness } from './ui/chips.harness';

const chipListbox = await TestbedHarnessEnvironment.loader(fixture).getHarness(FzChipListboxHarness);

Source

The exact file add copies. It is yours to edit.

chips.ts
import { Component, Directive, ElementRef, booleanAttribute, computed, contentChildren, inject, input, model, output, viewChild } from '@angular/core';
import { Listbox, Option } from '@angular/aria/listbox';
import { LiveAnnouncer } from '@angular/cdk/a11y';

type FzSize = 'xs' | 'sm' | 'md' | 'lg';

/** One option of `fz-chip-listbox`, read as data: `<fz-chip value="vegan" label="Vegan" />`. */
@Directive({ selector: 'fz-chip' })
export class FzChip<V = unknown> {
  readonly value = input.required<V>();
  readonly label = input<string>();
  readonly disabled = input(false, { transform: booleanAttribute });
  readonly text = computed(() => this.label() ?? String(this.value()));
}

/**
 * Chips to pick from: `<fz-chip-listbox [(value)]="diet" multiple aria-label="Diet">` with `<fz-chip>`s.
 * A horizontal listbox with one Tab stop: arrows move, Space or a click toggles a chip. The value is
 * always an array (one item at most without `multiple`).
 */
@Component({
  selector: 'fz-chip-listbox',
  imports: [Listbox, Option],
  // The listbox is inside: its label moves there, off the host.
  host: { class: 'block', '[attr.aria-label]': 'null', '[attr.aria-labelledby]': 'null', '[attr.data-size]': 'size() ?? null', '(focusout)': 'onFocusOut($event)' },
  template: `
    <div
      ngListbox
      orientation="horizontal"
      selectionMode="explicit"
      [multi]="multiple()"
      [disabled]="disabled()"
      [value]="values()"
      (valueChange)="value.set($event)"
      [attr.aria-label]="ariaLabel()"
      [attr.aria-labelledby]="ariaLabelledby()"
      class="flex flex-wrap gap-2 rounded-md outline-none aria-disabled:opacity-50"
    >
      @for (chip of chips(); track chip.value()) {
        <div
          ngOption
          [value]="chip.value()"
          [label]="chip.text()"
          [disabled]="chip.disabled()"
          class="inline-flex h-[calc(var(--fz-h)-4px)] cursor-default select-none items-center gap-1.5 rounded-full border bg-background px-(--fz-field-px) text-(length:--fz-text) font-medium outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring aria-selected:border-primary aria-selected:bg-primary aria-selected:text-primary-foreground aria-selected:before:content-['✓'] aria-disabled:pointer-events-none aria-disabled:opacity-50"
        >
          {{ chip.text() }}
        </div>
      }
    </div>
  `,
})
export class FzChipListbox<V = unknown> {
  readonly value = model<V[]>([]);
  readonly multiple = input(false, { transform: booleanAttribute });
  /** xs, sm, md, lg. Unset, it takes the size of the nearest `data-size` container, else md. */
  readonly size = input<FzSize>();
  readonly disabled = input(false, { transform: booleanAttribute });
  readonly ariaLabel = input<string | undefined>(undefined, { alias: 'aria-label' });
  readonly ariaLabelledby = input<string | undefined>(undefined, { alias: 'aria-labelledby' });
  /** Emits when focus leaves it: forms mark the field touched. */
  readonly touch = output();
  protected readonly chips = contentChildren(FzChip<V>);
  /** Forms write null (ngModel before its first value, `reset()`): read it as empty. */
  protected readonly values = computed(() => this.value() ?? []);
  private readonly el: HTMLElement = inject(ElementRef).nativeElement;

  protected onFocusOut(event: FocusEvent) {
    if (!this.el.contains(event.relatedTarget as Node | null)) this.touch.emit();
  }
}

/**
 * Free-form tags: `<fz-chip-input [(value)]="tags" aria-label="Tags" />`, or inside `fzField` with a label.
 * Enter or a comma adds what was typed (trimmed, no duplicates); Backspace in the empty input removes
 * the last tag; each tag has a remove button. Additions and removals are announced.
 */
@Component({
  selector: 'fz-chip-input',
  host: {
    '[attr.aria-label]': 'null',
    '[attr.data-size]': 'size() ?? null',
    '(focusout)': 'onFocusOut($event)',
    class:
      'flex min-h-(--fz-h) w-full flex-wrap items-center gap-1.5 rounded-md border bg-background px-2 py-1 text-(length:--fz-text) shadow-xs ' +
      'focus-within:ring-2 focus-within:ring-ring has-[input[aria-invalid=true]]:border-destructive has-disabled:opacity-50',
  },
  template: `
    @if (values().length) {
      <ul class="contents">
        @for (tag of values(); track tag) {
          <li class="inline-flex h-6 items-center gap-1 rounded-full bg-secondary pe-0.5 ps-2.5 text-xs font-medium text-secondary-foreground">
            {{ tag }}
            <button
              type="button"
              [attr.aria-label]="'Remove ' + tag"
              [disabled]="disabled()"
              class="inline-flex size-5 cursor-pointer items-center justify-center rounded-full text-muted-foreground outline-none hover:bg-background hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
              (click)="remove(tag, true)"
            >
              <svg viewBox="0 0 16 16" class="size-3" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><path d="M4 4l8 8M12 4l-8 8" /></svg>
            </button>
          </li>
        }
      </ul>
    }
    <input
      #field
      [attr.id]="inputId() ?? null"
      [attr.aria-label]="ariaLabel() ?? null"
      [placeholder]="placeholder()"
      [disabled]="disabled()"
      class="h-[calc(var(--fz-h)-10px)] disabled:cursor-not-allowed min-w-24 flex-1 bg-transparent outline-none placeholder:text-muted-foreground"
      (keydown)="onKeydown($event)"
      (blur)="add()"
    />
  `,
})
export class FzChipInput {
  readonly value = model<string[]>([]);
  readonly placeholder = input('');
  readonly disabled = input(false, { transform: booleanAttribute });
  /** xs, sm, md, lg. Unset, it takes the size of the nearest `data-size` container, else md. */
  readonly size = input<FzSize>();
  /** Id of the inner input, for a `<label for>` outside `fzField`. */
  readonly inputId = input<string>();
  readonly ariaLabel = input<string | undefined>(undefined, { alias: 'aria-label' });
  /** Emits when focus leaves it: forms mark the field touched. */
  readonly touch = output();
  private readonly el: HTMLElement = inject(ElementRef).nativeElement;
  /** Forms write null (ngModel before its first value, `reset()`): read it as empty. */
  protected readonly values = computed(() => this.value() ?? []);
  private readonly field = viewChild.required<ElementRef<HTMLInputElement>>('field');
  private readonly announcer = inject(LiveAnnouncer);

  protected onFocusOut(event: FocusEvent) {
    if (!this.el.contains(event.relatedTarget as Node | null)) this.touch.emit();
  }

  protected onKeydown(event: KeyboardEvent) {
    const input = this.field().nativeElement;
    if (event.key === 'Enter' || event.key === ',') {
      if (input.value.trim()) event.preventDefault(); // an empty Enter still submits the form
      this.add();
    } else if (event.key === 'Backspace' && !input.value && this.values().length) {
      this.remove(this.values().at(-1)!);
    }
  }

  protected add() {
    const input = this.field().nativeElement;
    const tag = input.value.trim();
    input.value = '';
    if (!tag || this.values().includes(tag)) return;
    this.value.set([...this.values(), tag]);
    void this.announcer.announce(`Added ${tag}`);
  }

  protected remove(tag: string, refocus = false) {
    this.value.set(this.values().filter((t) => t !== tag));
    void this.announcer.announce(`Removed ${tag}`);
    if (refocus) this.field().nativeElement.focus(); // its button is gone
  }
}

export const FZ_CHIPS = [FzChipListbox, FzChip, FzChipInput] as const;