Reputation: 541
I am trying to use ngControl on Custom Component. I have created the component and implemented ControlValueAccessor
on the component.
Then in the constructor, NgControl is injected as below:
constructor(@Self() private ngControl: NgControl){
this.ngControl.valueAccessor = this;
}
But this way when i use the ngControl on the selector, the form classes (ng-pristine , ng-touched, ng-invalid
) are not updated, nor can i check the value of the form element.
Can anyone help out where i am doing it wrong.
Adding to the description of the problem I tried to Thierry Templier solution, with the limited knowledge in angular2 but I get into a circular reference error.
Detailing more in the issue, I Have a component MyComponent
which I am using in a ContainerComponent
, when i use ngControl
in container component, with the changes described by Thierry Templier, made to MyComponent
, I get the circular reference error, something like: (MyComponent -> ngControl ..... -> token** -> MyComponent
).
Any suggestions around that.
Upvotes: 3
Views: 957
Reputation: 202306
In fact, you need to register your value accessor into the providers of your component. Note that it can be itself: the component is the value accessor and needs to be registered itself in its providers). In fact this case forwardRef
is helpful.
Something like that:
const CUSTOM_VALUE_ACCESSOR = new Provider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => LabelsValueAccessor), multi: true});
@Component({
(...)
providers: [CUSTOM_VALUE_ACCESSOR]
})
export class LabelsValueAccessor implements ControlValueAccessor {
(...)
}
Upvotes: 1