繁体   English   中英

如何在自定义Ng2表单元素中访问NgFormControl

[英]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中使用字符串标识符(这是您在上面使用的字符串)

我将它与此注释建议的解决方案一起使用:通过注入InjectorNgControl读取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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM