在我的自定义表单控件之一内,我需要访问其表单控件。事实证明,这并不是很简单。在网上我找到了3个解决方案:
使用验证器接口并访问控件如下d
public validate(c: FormControl) {
if (!this.control)
this.control=c;
return c?.errors;
}
使用
inject
或 Injector
(在我的例子中)总是给出循环依赖注入错误或 No provider for NgControl
this.ngControl = inject(NgControl);
或
this.ngControl = this.injector.get(NgControl);
使用@Input访问FormControl
@Input() formControl: FormControl;
不幸的是,这个不能与
formControlName
一起使用。
所以问题是,根据我的发现,我应该使用 1) 或 3)。或者还有其他解决办法吗?
正如我所写,您可以从应用于宿主元素的
FormControlName
指令中获取它。
请记住,这是一个循环依赖注入,因此您必须在构建后阶段访问它 - 在我的示例中,它是
ngAfterViewInit
回调
在您的自定义表单控件中
constructor(@Optional() @Host() private injector: Injector) {
}
ngAfterViewInit() {
// setTimeout(() => {
const formControlName = this.injector.get(FormControlName);
console.log('ctrl??', formControlName.control);
//
});
}
导致
ctrl?? FormControl{验证器:f,asyncValidator:null,_onCollectionChange:f,原始:true,...}
我已经分叉了一些随机的 stackblitz 示例来对其进行 POC。
忽略错误,因为其他 2 个控件使用
ngModel
和 `formControl