Shortest way to create Custom Control Accessor Component using DefaultValueAccessor in Angular
Frequently we need to create Custom Control Accessor Component. The standard path is to implement the ControlValueAccessor interface and add the Component in the NG_VALUE_ACCESSOR providers array. Unfortunately, this approach requires plenty of coding and knowledge that we often need to remember.
Fortunately, there is a shorter path with the help of DefaultValueAccessor.
DefaultValueAccessor
DefualtValueAccessor is a directive attached automatically to the input (type=”text”) or textarea. With the help of this directive, we can use ngModel and FormControl for these elements.
According to the Angular Docs, we can add the ngDefaultControl attribute to our Component, which will attach the value accessor behavior to our Component.
This value accessor is used by default for
<input type="text">
and<textarea>
elements, but you could also use it for custom Components that have similar behavior and do not require special processing. In order to attach the default value accessor to a custom element, add thengDefaultControl
attribute as shown below.
Internally DefaultValueAccessor has a selector that matches elements with the ngDefaultControl attribute: