![](/img/trans.png)
[英]How can I trigger custom and built in validators to validate on an ng2 template form?
[英]How to access NgFormControl in custom Ng2 form element
我通过实现ControlValueAccessor
编写了自己的自定义表单元素DateInputComponent
,并像这样使用它:
<my-date-input ngControl="date"></my-date-input>
据我了解, ngControl
是[ngFormControl]="myControlGroup.controls['date']"
语法糖。
现在,在我的DateInputComponent
内部,我想访问NgFormControl
。
我试图将其与@Input NgFormControl ngFormControl;
绑定@Input NgFormControl ngFormControl;
但它从未设置过,我尝试用DateInputComponent(NgFormControl ngFormControl)
注入它,但是失败了,因为没有提供者。
什么是正确的方法呢?
(也许我也以错误的方式来处理它……我希望此DateInputComponent
能够单独显示可能发生的所有验证错误。)
您可以使用正确的方法插入指令,但是问题是,虽然ngControl
可以被视为NgFormControl的语法糖,但它不是同一类。
所有窗体控件都从NgControl扩展而来,这就是您应该注入到组件中的内容。 DateInputComponent(NgControl ngControl)
所有的形式指令都是可以互换使用的,因此它们都提供NgControl作为公开的接口。 这允许您的日期组件的用户使用适用于其用例的任何指令:
NgModel
:如果他们只是想提供或收听值 NgFormControl
:如果他们想提供控件 NgControlName
:如果他们想在ControlMap中使用字符串标识符(这是您在上面使用的字符串) 我将它与此注释建议的解决方案一起使用:通过注入Injector
并NgControl
读取NgControl
:
class DateInputComponent implements ControlValueAccessor, AfterViewInit {
Injector _injector;
DateInputComponent(this._injector);
NgControl control;
@override
ngAfterViewInit() {
control = _injector.get(NgControl).control;
}
}
正如Ted所建议的NgControl
,直接注入NgControl
不起作用,因为这会导致循环依赖性。
尝试在构造函数中访问NgControl
无效,因为尚不可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.