简体   繁体   English

Angular 10:在 Angular Material 自定义表单字段控件中访问 NgControl

[英]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.

相关问题 如何在自定义表单控件中模拟 ngControl - Angular 单元测试 - How to mock ngControl in Custom Form Control - Unit tests Angular 角材料:“自定义表单字段控件”-移动浮动标签(向下) - Angular Material: Custom Form Field Control - move floating label (down) 角材料窗体字段控件为null - Angular Material form field control is null Angular Material:mat-form-field 在创建自定义表单域控件时必须包含一个 MatFormFieldControl - Angular Material: mat-form-field must contain a MatFormFieldControl when creating a custom form field control 在自定义角度材料表格字段上的验证 - Validation on Custom Angular Material Form Field Angular2 中自定义指令的 NgControl - NgControl on Custom Directive in Angular2 Angular Material自定义窗体字段控件的值不会在调用FormGroup中更新 - Angular Material custom form field control's value is not updated in the calling FormGroup 尝试从 angular 材料制作自定义表单字段控件时,有没有办法消除焦点? - Is there a way to remove focus when trying to make custom form field control from angular material? 带有验证错误的 Angular6 Material 自定义表单字段控件(mat-error) - Angular6 Material custom form field control with validation errors (mat-error) angular材料的表格控制问题 - Form control problem with angular Material
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM