[英]NgControl on Custom Directive in Angular2
I am trying to use ngControl on Custom Component.我正在尝试在自定义组件上使用 ngControl。 I have created the component and implemented
ControlValueAccessor
on the component.我已经创建了组件并在组件上实现了
ControlValueAccessor
。
Then in the constructor, NgControl is injected as below:然后在构造函数中,NgControl 被注入如下:
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.但是这样当我在选择器上使用 ngControl 时,表单类(
ng-pristine , ng-touched, ng-invalid
)不会更新,我也不能检查表单元素的值。
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.添加到问题的描述中,我尝试使用Thierry Templier解决方案,但我对 angular2 的了解有限,但我陷入了循环引用错误。
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
).在问题中详细说明,我有一个组件
MyComponent
,我在ContainerComponent
使用ngControl
,当我在容器组件中使用ngControl
时,通过 Thierry Templier 描述的更改,对MyComponent
进行了更改,我得到了循环引用错误,例如:( MyComponent -> ngControl ..... -> token** -> MyComponent
)。
Any suggestions around that.任何建议。
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.事实上,这种情况
forwardRef
是有帮助的。
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 {
(...)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.