Take a look at this example:
https://stackblitz.com/edit/angular-nxjeu3
It does not work.
But if I move the providers
from the @NgModule
to HelloComponent
, it does work. Why? Shouldn't providing at the @NgModule
level or @Component
level be the same?
NG_VALUE_ACCESSOR provider specifies a class that implements ControlValueAccessor interface and is used by Angular to setup synchronization with formControl . It's usually the class of the component or directive that registers the provider.
ControlValueAccessorlink. Defines an interface that acts as a bridge between the Angular forms API and a native element in the DOM.
Because the NG_VALUE_ACCESSOR
is binding things to component's :host
and linking to methods (ControlValueAccessor methods) there. Your module does not have any of those form methods (like writeValue, registerOnTouched etc). Your form element does. So providing at component level binds this for that specific element. Additionally, providing so deep down means each form control has it's own control value accessor and not a shared one.
Angular Form controls and its API is not the same as the DOM form controls. What angular does is binds to the inputs/outputs of the dom element and provides you with the results. Now, with your custom control, you must provide the same bindings there. By implementing ControlValueAccessor
and providing NG_VALUE_ACCESSOR
, you are telling Angular's Forms API how it can read and write values from/to your custom form control.
Take a look at the source.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With