【问题标题】:Angular 10: Access NgControl in an Angular Material custom form field controlAngular 10:在 Angular Material 自定义表单字段控件中访问 NgControl
【发布时间】:2020-09-11 09:59:17
【问题描述】:

我正在尝试在自定义 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的方式吗?

提前致谢。

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

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

    constructor(
        private injector: Injector,
        ...
      ) {
        ...
      }
    
    ngOnInit(): void {
        this.ngControl = this.injector.get(NgControl);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-30
      • 2016-03-22
      • 2021-12-18
      • 2019-02-01
      • 2022-07-29
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      相关资源
      最近更新 更多