Creating a Custom Angular Form Control with ControlValueAccessor

Angular’s built-in form controls cover text fields, checkboxes, selects, and many common inputs. Real applications often need something more specialised: a star rating, date-range picker, address selector, colour palette, rich text editor, or a composite postcode field. These controls still need to behave like native Angular controls when used with reactive or template-driven forms.

The bridge between a custom component and Angular Forms is ControlValueAccessor, commonly abbreviated to CVA. It defines how Angular writes a value into the component, receives changes from it, marks it as touched, and applies a disabled state. Once those responsibilities are implemented, a custom component can use formControlName in the same way as an ordinary input.

This guide builds a reusable rating control in Angular. The example suits a product review flow for an online retailer in Sydney, Melbourne, or Brisbane, but the same pattern applies to more complex controls used by Australian development teams and agencies.

Why A Custom Control Needs CVA

A component with an @Input() value and an @Output() event is not automatically an Angular form control. It can display data and emit changes, but Angular does not know how to call it when setValue() runs, how to mark it touched after user interaction, or how to disable it through a parent form.

ControlValueAccessor supplies four important methods:

The component also needs to register itself with Angular through the NG_VALUE_ACCESSOR token. Without that provider, using formControlName on the component produces an error because Angular cannot find a value accessor.

A useful mental model is that writeValue() handles the form-to-component direction, while the callbacks handle the component-to-form direction. Keeping those paths separate prevents feedback loops and makes the control predictable.

Build The Rating Component

The component below stores a numeric rating from zero to five. It exposes buttons rather than clickable spans, which gives keyboard users a sensible interaction model and provides a better foundation for accessibility.

import { CommonModule } from '@angular/common';
import {
  Component,
  forwardRef
} from '@angular/core';
import {
  ControlValueAccessor,
  NG_VALUE_ACCESSOR
} from '@angular/forms';

@Component({
  selector: 'app-rating-control',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './rating-control.component.html',
  styleUrls: ['./rating-control.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => RatingControlComponent),
      multi: true
    }
  ]
})
export class RatingControlComponent implements ControlValueAccessor {
  value = 0;
  disabled = false;

  private onChange: (value: number) => void = () => {};
  private onTouched: () => void = () => {};

  writeValue(value: number | null): void {
    this.value = value ?? 0;
  }

  registerOnChange(fn: (value: number) => void): void {
    this.onChange = fn;
  }

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

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

  selectRating(rating: number): void {
    if (this.disabled) {
      return;
    }

    this.value = rating;
    this.onChange(rating);
    this.onTouched();
  }

  markAsTouched(): void {
    this.onTouched();
  }
}

The forwardRef() call allows the provider to refer to the component class before Angular has finished defining it. multi: true is important because Angular maintains a collection of value accessors, rather than replacing every existing accessor with this one.

The component template can render five buttons and expose useful labels to assistive technology:

<div
  class="rating"
  role="group"
  aria-label="Product rating"
  (blur)="markAsTouched()">

  <button
    *ngFor="let rating of [1, 2, 3, 4, 5]"
    type="button"
    [disabled]="disabled"
    [attr.aria-pressed]="rating === value"
    [attr.aria-label]="rating + ' out of 5 stars'"
    (click)="selectRating(rating)">
    {{ rating <= value ? '★' : '☆' }}
  </button>
</div>

The button’s type="button" prevents accidental form submission. This small detail matters in checkout and review forms, where a rating control may sit beside a submit button. A team working across AEST and AWST regions may never notice a timing difference in this component, but a form that submits unexpectedly is immediately visible to customers in Perth, Adelaide, or Canberra.

Connect The Control To A Reactive Form

Once the value accessor is registered, the custom component can be used with a standard reactive form. The parent component does not need to know whether the rating is implemented with buttons, icons, or a third-party widget.

import { Component } from '@angular/core';
import {
  FormControl,
  FormGroup,
  ReactiveFormsModule,
  Validators
} from '@angular/forms';
import { RatingControlComponent } from './rating-control.component';

@Component({
  selector: 'app-product-review',
  standalone: true,
  imports: [ReactiveFormsModule, RatingControlComponent],
  template: `
    <form [formGroup]="reviewForm" (ngSubmit)="submit()">
      <label for="comment">Comment</label>
      <textarea id="comment" formControlName="comment"></textarea>

      <app-rating-control formControlName="rating">
      </app-rating-control>

      <button type="submit">Send review</button>
    </form>
  `
})
export class ProductReviewComponent {
  reviewForm = new FormGroup({
    comment: new FormControl('', {
      nonNullable: true,
      validators: [Validators.required]
    }),
    rating: new FormControl(0, {
      nonNullable: true
    })
  });

  submit(): void {
    if (this.reviewForm.invalid) {
      this.reviewForm.markAllAsTouched();
      return;
    }

    console.log(this.reviewForm.getRawValue());
  }
}

Angular calls writeValue(0) when the form is initialised. If a backend later loads a review with a rating of four, reviewForm.patchValue({ rating: 4 }) calls writeValue(4), updating the component without simulating a click.

When a customer selects a star, selectRating() updates the local display and calls the callback supplied by registerOnChange(). Angular then updates the FormControl value, runs its validation pipeline, and emits the relevant valueChanges event. The custom component does not need to inject NgControl or manually manipulate the parent form.

A rating of zero may need special handling. Angular’s built-in Validators.required considers numeric zero a present value, so it will not necessarily enforce “choose at least one star”. If the product review requires a rating, add a validator in the parent form or implement the optional Validator interface in the control.

Handle Touch And Disabled States

A control becomes touched when the user has interacted with it and moved away, or when the application deliberately marks it touched. Calling onTouched() from selectRating() gives useful behaviour for a button-based control because a click represents interaction. The (blur) handler provides another path for keyboard navigation.

Do not call onTouched() from writeValue(). Programmatic changes are not user interaction, and marking the control touched at that point can cause validation messages to appear while a form is loading. Likewise, do not call onChange() from writeValue(). Doing so can produce duplicate valueChanges events and circular update behaviour.

setDisabledState() must affect every interactive element. In this example, assigning disabled to each button prevents clicks and communicates the state to the browser. For a composite control, all inputs, buttons, and interactive overlays should follow the same state. A date picker that disables only its visible text box but leaves its calendar trigger active is still functionally enabled.

Styling should also communicate the state without relying on colour alone:

.rating {
  display: inline-flex;
  gap: 0.25rem;
}

.rating button {
  border: 0;
  background: transparent;
  cursor: pointer;
  font-size: 2rem;
  line-height: 1;
}

.rating button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.rating button:focus-visible {
  outline: 3px solid #005bbb;
  outline-offset: 3px;
}

The strong focus outline is valuable for keyboard users and aligns with the accessibility expectations increasingly found in Australian government and enterprise projects. It also helps testers verify the control without depending on a mouse.

Add Validation And Test The Contract

ControlValueAccessor handles value synchronisation, not validation. If the control has rules of its own, such as requiring a rating between one and five, expose those rules deliberately. A simple parent-level validator keeps the rating component focused on interaction:

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export const ratingRequired: ValidatorFn =
  (control: AbstractControl): ValidationErrors | null => {
    return control.value >= 1
      ? null
      : { ratingRequired: true };
  };

Apply it to the rating control alongside any other business rules:

rating: new FormControl(0, {
  nonNullable: true,
  validators: [ratingRequired]
})

For a reusable library component, implementing Validator may be preferable. That approach lets the component provide its own rules through NG_VALIDATORS, though it adds another registration token and another lifecycle method. Choose the ownership model that matches the rest of the application.

Test the CVA contract rather than testing only the rendered star character. A useful test suite should verify that writeValue(4) displays four selected stars, selecting a star calls the registered change callback, interaction calls the touched callback, and setDisabledState(true) prevents further changes. Also test form integration with a real FormControl.

In a .NET and Angular codebase, integration tests should confirm that the value sent to an ASP.NET Core API is the expected number and that an API-loaded value appears correctly after patchValue(). This catches mismatches such as a string rating from JSON being treated differently from a numeric rating in TypeScript.

Use The Pattern For Larger Controls

The same architecture works for controls that contain several internal values. A date-range component might expose { start: Date; end: Date }, while an Australian address component could expose a structured object containing a street, suburb, state, and postcode. writeValue() should map the external object into the internal fields, and the internal fields should emit one consistent object through onChange().

For complex controls, avoid emitting incomplete objects unless the parent form explicitly expects them. A date-range picker can hold an internal start date while the end date is empty, but its public value might remain null until both dates are selected. Define that contract clearly and cover it with tests.

Use ChangeDetectionStrategy.OnPush when appropriate, especially for reusable controls in large Angular applications. With OnPush, remember that writeValue() changes component state directly. If the control uses asynchronous rendering or signals in a more advanced implementation, ensure the view is notified when a programmatic value arrives.

Value typing deserves attention too. A rating accessor might accept number | null, while a date control may need Date | null or an ISO string. Avoid silently converting values in several places. Pick one public type, document it, and convert at the boundary where data enters the component.

A custom control can also wrap third-party widgets, but the CVA remains the Angular-facing contract. The widget’s event handlers should call onChange() and onTouched(), while writeValue() should update the widget when the parent form changes. This makes replacing a calendar or editor library much less disruptive.

Recommendations For Production-Ready Controls

A well-designed ControlValueAccessor gives a custom Angular component the same form behaviour as a native input. Start with the four lifecycle methods, register the provider, define a clear value contract, and then add validation and accessibility around that foundation. From a five-star review widget to an Australian address selector, this approach keeps the component reusable, testable, and compatible with the rest of an Angular application.

Add the rating control to a small sample form, exercise it with setValue(), patchValue(), disabling, validation, and keyboard input, then adapt the same contract to the specialised control your project needs.