I'm trying to create a custom component (a customized autocomplete field) but I want to work for both reactive forms and template forms
So sometimes the value will come through [(ngModel)]
and sometimes i want to provide formControlName
Until now I've had 2 different templates, but everywhere i look it seems as if NG_VALUE_ACCESSOR is handling it by itself, there's just something missing in my implementation.
To make my question clearer If you use a PrimeNg component or any framework, the same component can take an [(ngModel)] or a formControlName and it behaves as a normal component in both cases without special treatment, this is what i want to do
Similar question with same issue :
How to wrap a primeng component like autocomplete using reactive forms?
This is an old question, but I was struggling with the same problem. In case anybody stumbles across this, here's how I interpret what is being asked, and my solution.
My component needs to be able to receive a
[value]
and emit some(output)
, while ALSO being able to simply receive aformControlName
. I too needed to solve this problem. Use the following example:OR
I fought with this for a while, but after looking at this repo it finally clicked for me.
Here's the html structure of my wrapped button-toggle component
And in the ts, we allow for formControlName as well as value setting:
So, what's happening is that when the button-toggle's
(change)
event is fired, it calls thethis.onChange
internally, which is handled by the ControlValueAccessor, but then I also tell my custom output to emit the value, so that any other type of non-reactive-form use case can still talk to the component.