0

I am trying to access NgControl within a custom Angular Material Form Field Control:

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.

Is that the way to inject NgControl?

Thanks in advance.

1 Answer 1

0

Injecting ngControl directly in constructor causes cyclic dependency. Can be avoided by doing this:

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

ngOnInit(): void {
    this.ngControl = this.injector.get(NgControl);
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.