Sub topic 20
Making Custom Components Work as Form Controls
Native inputs such as <input>, <select>, and <textarea> work with formControlName because Angular ships a built-in adapter for each of them. A component you write yourself, such as a star rating, a color picker, or a tag selector, has no adapter. To bind it with formControlName or [formControl], the component must implement the ControlValueAccessor interface.
This chapter assumes you already know how to bind a FormGroup to a template, how validation state works, and how to disable controls. It also assumes you have used standalone components and Angular's dependency injection providers.
What a value accessor does
A value accessor connects a FormControl in your component code to a UI element in the DOM. Data moves in two directions:
- Model to view: when you call
setValue,patchValue, orreset, the control tells the accessor to display the new value. - View to model: when the user interacts with the element, the accessor reports the new value and the "touched" event back to the control.
The formControlName directive does not talk to your component directly. When the directive initializes, it asks the injector for the NG_VALUE_ACCESSOR token on the same element and wires the control to whatever it finds.
The four methods
| Method | Called by | Your job |
|---|---|---|
| `writeValue(value)` | Forms API, whenever the model changes | Update the component's display. Do not report the change back. |
| `registerOnChange(fn)` | Forms API, once at setup | Store `fn`. Call it whenever the user changes the value. |
| `registerOnTouched(fn)` | Forms API, once at setup | Store `fn`. Call it when the user is done interacting, usually on blur. |
| `setDisabledState(isDisabled)` | Forms API, at setup and on `enable()` / `disable()` | Optional. Disable the component's interactive parts. |
A complete rating control
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, forwardRef, inject } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-rating',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@for (star of stars; track star) {
<button
type="button"
[disabled]="disabled"
[attr.aria-label]="star + ' stars'"
(click)="select(star)"
(blur)="onTouched()"
>
{{ star > value ? '☆' : '★' }}
</button>
}
`,
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => RatingComponent), multi: true },
],
})
export class RatingComponent implements ControlValueAccessor {
private cdr = inject(ChangeDetectorRef);
stars = [1, 2, 3, 4, 5];
value = 0;
disabled = false;
private onChange: (value: number) => void = () => {};
onTouched: () => void = () => {};
writeValue(value: number | null): void {
this.value = value ?? 0;
this.cdr.markForCheck();
}
registerOnChange(fn: (value: number) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
this.cdr.markForCheck();
}
select(star: number): void {
if (this.disabled) return;
this.value = star;
this.onChange(star);
}
}The provider registers the component as its own value accessor. forwardRef is needed because the class is referenced inside its own decorator before the class is defined. multi: true adds this accessor to the list of accessors on the element instead of replacing the whole token.
Using it in a form
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { RatingComponent } from './rating.component';
@Component({
selector: 'app-review-form',
standalone: true,
imports: [ReactiveFormsModule, RatingComponent],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<app-rating formControlName="rating" />
@if (form.controls.rating.touched && form.controls.rating.hasError('min')) {
<p>Please choose a rating.</p>
}
<textarea formControlName="comment"></textarea>
<button type="submit" [disabled]="form.invalid">Send</button>
</form>
`,
})
export class ReviewFormComponent {
form = new FormGroup({
rating: new FormControl(0, { nonNullable: true, validators: [Validators.min(1)] }),
comment: new FormControl('', { nonNullable: true }),
});
submit(): void {
console.log(this.form.getRawValue());
}
}The rating behaves like any other control. Validators, touched and dirty flags, reset(), disable(), and valueChanges all work without the component knowing about them.
Common errors
"No value accessor for form control name"
This error means Angular found no NG_VALUE_ACCESSOR on the element. Usually the provider is missing, or the component is not in the parent's imports array. If the component is not imported, Angular treats <app-rating> as an unknown element, and no accessor exists.
Calling onChange inside writeValue
writeValue reports a change that came from the model. If it calls onChange, the value goes straight back to the control, which marks the control dirty and emits valueChanges a second time. Only call onChange in response to user actions.
Not handling null
writeValue can receive null. This happens with a nullable control after reset(), and with some setup orders before the initial value arrives. Type the parameter as T | null and fall back to a sensible default.
Forgetting onTouched
If you never call onTouched, the control stays untouched forever, and error messages that depend on touched never appear. Call it on blur, or after a selection if the component has no natural blur event.
Disabling through the template
Do not bind [disabled] on <app-rating formControlName="rating">. Reactive forms ignore that binding and log a warning. Call form.controls.rating.disable() instead. Since Angular 15, setDisabledState is also called during setup even when the control is enabled, so make sure it handles false correctly.
When not to write an accessor
If a component only wraps a native input to add styling or a label, you can often pass the FormControl in as an input and bind [formControl] on the inner <input>. That avoids a second layer of state. Write a full accessor when the component's value is not a native input's value, as with ratings, pickers, or composite widgets, or when consumers should be able to use formControlName without knowing how the component works inside.
Exercise
A teammate's rating component sets this.value = value; this.onChange(value); inside writeValue. What symptoms will they see after calling form.reset()?
Show answer
The control is marked dirty right after the reset, because onChange reports the value as a user change. valueChanges also emits twice for one reset. The fix is to remove the onChange call from writeValue and only call it from user event handlers.
Exercise
You add <app-rating formControlName="rating" /> to a form and get "No value accessor for form control name: 'rating'". The component has the correct NGVALUEACCESSOR provider. What is the most likely cause?
Show answer
The parent standalone component does not list RatingComponent in its imports array, so Angular never creates the component or its provider on that element. Add it to imports.
Exercise
Your OnPush rating component shows the correct stars when the user clicks, but form.patchValue({ rating: 3 }) does not change the display. Why, and how do you fix it?
Show answer
writeValue updates a plain field, and OnPush does not re-render because no input binding changed. Inject ChangeDetectorRef and call markForCheck() inside writeValue, or keep the value in a signal.