如何在自定义 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; 绑定它,但它从未被设置,我尝试用 DateInputComponent(NgFormControl ngFormControl) 注入它,但失败了,因为没有提供者。

正确的获取方式是什么?

(也许我也以错误的方式接近它...我希望这个 DateInputComponent 能够自行显示所有可能发生的验证错误。)

您注入指令的方法是正确的,但问题是虽然 ngControl 可以被视为 NgFormControl 的语法糖,但它并不相同 class。

所有表单控件都从 NgControl 扩展而来,这就是您应该注入到组件中的内容。 DateInputComponent(NgControl ngControl)

所有表单指令都可以互换使用,因此它们都提供 NgControl 作为它们公开的接口。这允许您的日期组件的用户使用适用于他们的用例的任何指令:

  • NgModel:如果他们只是想提供或聆听价值
  • NgFormControl:如果他们想提供控制权
  • NgControlName:如果他们想在ControlMap中使用字符串标识符(这是你在上面使用的那个)

我让它与解决方案一起工作 建议:通过注入 Injector 并从中读取 NgControl

class DateInputComponent implements ControlValueAccessor, AfterViewInit {
  Injector _injector;
  DateInputComponent(this._injector);

  NgControl control;

  @override
  ngAfterViewInit() {
    control = _injector.get(NgControl).control;
  }
}

按照 Ted 的建议,直接注入 NgControl 是行不通的,因为它会导致循环依赖。

尝试在构造函数中访问 NgControl 将不起作用,因为它尚不可用。