In Angular, the ControlValueAccessor
interface is what allows custom form components to work seamlessly with Angular forms (both reactive and template-driven).
π§ What is ControlValueAccessor
?
Itβs an Angular bridge between your custom component and the Angular Forms API.
When you use a custom form component (like a date picker, dropdown, slider, etc.), Angular doesn't automatically know how to read or write its value. Thatβs where ControlValueAccessor
comes in.
It tells Angular:
-
How to write a value to the component
-
How to notify Angular when the componentβs value changes
-
How to handle disabled state
π¦ Common Built-in Examples:
-
<input>
and<select>
already implementControlValueAccessor
-
You implement it when creating custom form controls
π§ Key Methods in the Interface
Method | Purpose |
---|---|
writeValue(obj: any) | Called by Angular to set the value in the component |
registerOnChange(fn: any) | Passes a function to call when the component value changes |
registerOnTouched(fn: any) | Called when the component is "touched" (blur/focus) |
setDisabledState?(isDisabled: boolean) | Optional method to handle disabled state |
ControlValueAccessor
in a Custom Component1. Create a custom form component
2. Use it in a reactive form
π― Summary
Feature | Description |
---|---|
Purpose | Sync custom form control with Angular forms |
Interface Name | ControlValueAccessor |
Used With | NG_VALUE_ACCESSOR token |
Methods Required | writeValue , registerOnChange , etc. |