Sub topic 18
Making Custom Components Work as Form Controls
This chapter assumes you can already build a FormGroup, bind it with formControlName, and write a ValidatorFn. It covers two topics. The first is making your own component act like a native input. The second is testing form logic without rendering a template.
Making Custom Components Work as Form Controls
The formControlName directive can't write to an element it doesn't understand. It talks to every input through a ControlValueAccessor, which is an interface that connects a form control to a UI element. Angular ships accessors for native inputs, checkboxes, and selects. For your own component, you implement the interface yourself and register the component under the NG_VALUE_ACCESSOR token.
The interface has four methods:
| Method | Called by | Purpose |
|---|---|---|
| `writeValue(value)` | Form model | Pushes a model value into the component |
| `registerOnChange(fn)` | Form model | Hands you a callback to report new values |
| `registerOnTouched(fn)` | Form model | Hands you a callback to report a blur or touch |
| `setDisabledState(isDisabled)` | Form model | Optional. Reflects `disable()` and `enable()` |
import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-rating',
standalone: true,
template: `
@for (star of stars; track star) {
<button type="button" [disabled]="disabled" (click)="select(star)">
{{ star > value ? '☆' : '★' }}
</button>
}
`,
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => RatingComponent), multi: true },
],
})
export class RatingComponent implements ControlValueAccessor {
stars = [1, 2, 3, 4, 5];
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;
}
select(star: number): void {
this.value = star;
this.onChange(star);
this.onTouched();
}
}Once the component is registered, you bind it the same way you bind a native input: <app-rating formControlName="score" />.
Common mistakes with custom accessors:
- Leaving out
multi: true. This replaces Angular's built-in accessors instead of adding yours to them. - Never calling
onTouched. The control then never becomestouched, so error messages gated ontouchednever appear. - Not handling
nullinwriteValue. Callingreset()passesnullto the accessor.
Unit Testing Form Models and Validators
Form models are plain objects, so you can test them without TestBed or a rendered template. Build the model, set values, and check valid, errors, or hasError.
import { FormControl, FormGroup } from '@angular/forms';
import { passwordsMatch } from './passwords-match.validator';
describe('passwordsMatch', () => {
it('reports an error when passwords differ', () => {
const form = new FormGroup(
{
password: new FormControl('secret1', { nonNullable: true }),
confirmPassword: new FormControl('secret2', { nonNullable: true }),
},
{ validators: passwordsMatch },
);
expect(form.hasError('passwordsMismatch')).toBe(true);
form.controls.confirmPassword.setValue('secret1');
expect(form.valid).toBe(true);
});
});To test a custom accessor, call its methods directly. Call writeValue(3) and check value. Then register a spy with registerOnChange, call select(5), and check that the spy received 5.
Exercise
A form using your custom component never shows its "required" error message, even after the user interacts with the component. The template shows the error only when the control is touched. What is the most likely bug?
Show answer
The component never calls the callback passed to registerOnTouched, so the control never becomes touched. Call onTouched() when the user interacts with the component or when it loses focus.
Exercise
Why can the passwordsMatch test run without TestBed?
Show answer
FormGroup, FormControl, and validators are plain TypeScript objects and functions. They don't depend on a template, change detection, or dependency injection, so you can create and check them directly.