Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to provide NG_VALUE_ACCESSOR at the component level?

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?

like image 259
Sarun Intaralawan Avatar asked Jan 03 '18 21:01

Sarun Intaralawan


People also ask

What is Ng_value_accessor?

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.

What is the use of control value accessor in Angular?

ControlValueAccessorlink. Defines an interface that acts as a bridge between the Angular forms API and a native element in the DOM.


1 Answers

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.

like image 64
Zlatko Avatar answered Sep 19 '22 08:09

Zlatko