đź’‰ Shot #7: How to implement custom form control in Angular
Introduction
If we want to use Angular forms bindings with custom form controls we need to implement ControlValueAccessor
interface.
Let’s assume we have a button with a counter that increments each time the user clicks on it.
And we need the ability to use it with the Angular forms API like so
<counter-button [formControlName]="counter"></counter-button>
Step 1: Implement ControlValueAccessor
interface
First of all, we need to implement ControlValueAccessor
interface.
Step 2: Implement writeValue
writeValue(obj: any): void
is the method which writes value from the data model to our custom control.
Step 3: Implement registerOnChange
registerOnChange(fn: any): void
registers the callback that has to be called to propagate changes back to the model. And then we call registerOnChange
when change data model internally in the inc
function.
Step 4: Skip registerOnTouched
registerOnTouched(fn: any): void
registers the function that has to be called when custom control was touched. In our case we don’t need registerOnTouched
, so, let’s skip it. For more information, check the link at the end of the article.
Step 5: Register ControlValueAccessor
The final step we need to perform is to register CounterButton
as a NG_VALUE_ACCESSOR
.
Shot
Here is the final shot ready for usage
Useful Links
- ControlValueAccessor— https://angular.io/api/forms/ControlValueAccessor