[英]Angular 10: Access NgControl in an Angular Material custom form field control
I am trying to access NgControl within a custom Angular Material Form Field Control :我正在尝试在自定义Angular Material Form Field Control 中访问 NgControl:
constructor(
@Self() @Optional() public ngControl: NgControl,
private fb: FormBuilder,
private fm: FocusMonitor,
private elRef: ElementRef<HTMLElement>
) {
this.createForm();
console.log('<< ', this.ngControl);
if (this.ngControl != null) {
this.ngControl.valueAccessor = this;
}
fm.monitor(elRef.nativeElement, true).subscribe(origin => {
this.focused = !!origin;
this.stateChanges.next();
});
}
But when I do this the interface where I use the component is blank, no errors!但是当我这样做时,我使用组件的界面是空白的,没有错误! When I remove the NgControl from the constructor the view is rendered.当我从构造函数中删除 NgControl 时,视图被呈现。
Is that the way to inject NgControl?那是注入NgControl的方式吗?
Thanks in advance.提前致谢。
Injecting ngControl directly in constructor causes cyclic dependency.直接在构造函数中注入 ngControl 会导致循环依赖。 Can be avoided by doing this:可以通过这样做来避免:
constructor(
private injector: Injector,
...
) {
...
}
ngOnInit(): void {
this.ngControl = this.injector.get(NgControl);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.