0

我正在尝试在自定义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();
    });
  }

但是当我这样做时,我使用组件的界面是空白的,没有错误!当我从构造函数中删除 NgControl 时,会呈现视图。

那是注入NgControl的方式吗?

提前致谢。

4

1 回答 1

0

在构造函数中直接注入 ngControl 会导致循环依赖。可以通过这样做来避免:

constructor(
    private injector: Injector,
    ...
  ) {
    ...
  }

ngOnInit(): void {
    this.ngControl = this.injector.get(NgControl);
  }
于 2020-09-11T01:59:17.683 回答