← Back to Angular, page 5

angular-0082 · Medium mid

Build a tags input component that works with reactive forms. How do you implement both ControlValueAccessor and Validator?

Provide the component with NG_VALUE_ACCESSOR so forms can read and write its string array, and with NG_VALIDATORS so the control can report errors such as too many tags. The component keeps its tags in a signal, calls the registered change function when the user adds or removes a tag, and reports touched on blur.

Full answer

A tags input shows chips and lets the user type new ones. The form value is string[].

ControlValueAccessor (CVA) part: the same four methods as any custom control.

  • writeValue(tags) receives the value from the form and stores it in a signal. It must not call the change function.
  • registerOnChange(fn) stores the callback. Call it with a new array whenever the user adds or removes a tag.
  • registerOnTouched(fn) stores the callback, called on blur.
  • setDisabledState(disabled) disables the input and the remove buttons.

Validator part. A custom control can also validate itself. Implement the Validator interface (validate(control) returns null or an error object), and register the component under NG_VALIDATORS with multi: true. Then Validators on the control and the component's own rules combine. In the example, validate returns { maxTags: { max, actual } } when there are too many tags and { duplicate: true } is prevented at the input level instead. The component's max input is a signal, so when it changes call the stored onValidatorChange callback (from registerOnValidatorChange), so the form re-validates.

Behaviour: Enter or comma adds a trimmed, non-empty, unique tag. Backspace on an empty input removes the last tag. Each chip has a remove button with a label such as "Remove angular".

Accessibility: the input has a label, the chip list is a ul with an aria-label, and removal and addition are announced, for example with aria-live.

Use provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TagsInputComponent), multi: true, since the class is referenced inside its own decorator.

Test it with a host that has FormControl<string[]>: set the value, type a tag, press Enter, check control.value, and verify the error when the limit is exceeded.

typescript
import { Component, computed, forwardRef, input, signal } from '@angular/core';
import {
  AbstractControl,
  ControlValueAccessor,
  NG_VALIDATORS,
  NG_VALUE_ACCESSOR,
  ValidationErrors,
  Validator,
} from '@angular/forms';

@Component({
  selector: 'app-tags-input',
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TagsInputComponent), multi: true },
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => TagsInputComponent), multi: true },
  ],
  template: `
    <ul aria-label="Tags">
      @for (tag of tags(); track tag) {
        <li>
          {{ tag }}
          <button type="button" [disabled]="disabled()" [attr.aria-label]="'Remove ' + tag" (click)="remove(tag)">x</button>
        </li>
      }
    </ul>
    <label>
      Add a tag
      <input
        #box
        [disabled]="disabled()"
        (keydown)="onKey($event, box)"
        (blur)="add(box.value); box.value = ''; onTouched()"
      />
    </label>
    <p aria-live="polite">{{ tags().length }} of {{ max() }} tags</p>
  `,
})
export class TagsInputComponent implements ControlValueAccessor, Validator {
  readonly max = input(5);

  readonly tags = signal<string[]>([]);
  readonly disabled = signal(false);
  readonly count = computed(() => this.tags().length);

  private onChange: (value: string[]) => void = () => {};
  onTouched: () => void = () => {};

  writeValue(value: string[] | null): void {
    this.tags.set(value ?? []);
  }

  registerOnChange(fn: (value: string[]) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled.set(isDisabled);
  }

  validate(_control: AbstractControl): ValidationErrors | null {
    const actual = this.count();
    return actual > this.max() ? { maxTags: { max: this.max(), actual } } : null;
  }

  onKey(event: KeyboardEvent, box: HTMLInputElement): void {
    if (event.key === 'Enter' || event.key === ',') {
      event.preventDefault();
      this.add(box.value);
      box.value = '';
    } else if (event.key === 'Backspace' && box.value === '' && this.tags().length > 0) {
      this.remove(this.tags()[this.tags().length - 1]);
    }
  }

  add(raw: string): void {
    const tag = raw.trim();
    if (!tag || this.tags().includes(tag)) {
      return;
    }
    this.update([...this.tags(), tag]);
  }

  remove(tag: string): void {
    this.update(this.tags().filter((t) => t !== tag));
  }

  private update(next: string[]): void {
    this.tags.set(next);
    this.onChange(next);
  }
}

Angular 20.3, strict template check passes, and a Karma test checks add, remove, and the validation error.

Key points

  • CVA moves values between the form and the component. `writeValue` must not call `onChange`.
  • `Validator` plus `NG_VALIDATORS` lets the control report its own errors.
  • Call `onValidatorChange` when a validator-related input changes.
  • Keyboard: Enter and comma add, Backspace removes. Label everything.

Common mistakes

  • Forgetting `multi: true` on either provider.
  • Mutating the tag array in place and passing the same reference to `onChange`.
  • Not calling `onTouched`, so the control is never marked touched.

Follow-ups

  • How would you add an async validator to a custom control?
  • How does the form know the validator inputs changed?
  • How would you support pasting a comma separated list?

Tips

  • Say that CVA and Validator are independent interfaces, and show you can combine them.
  • Describe keyboard handling and accessibility before you are asked.
  • Mention immutability of the emitted array.

Evaluation rubric

  • Implements all CVA methods without loops.
  • Registers and implements Validator correctly.
  • Handles keyboard and accessibility.