0

Trying to add a component to the DOM with ViewContainerRef createComponent. However, the component depends on NgControl. The end goal is to add components to a form using the FormBuilder.

Can't seem to wrap my head around dependency injection when it comes to NgControl.

Is there a way to set the formControlName when programmatically creating a component?

  createNgControlComponent() {
    // Add control to form group
    this.controlName++;
    this.formGroup.addControl(
      this.controlName.toString(),
      this.formBuilder.control('', [])
    );
    // Create component
    // ERROR Error: NG0201: No provider for NgControl found in NodeInjector.
    const componentRef = this.form.createComponent(
      CustomControlValueAccessorComponent
    );
    // componentRef.instance.controlDir = new FormControlName();
  }

DEMO: https://stackblitz.com/edit/angular-ivy-c739x6?file=src/app/app.component.ts

1 Answer 1

0

We can add a mediator component that will set the formControlName. I changed your code to work with a mediator. See if this helps - https://stackblitz.com/edit/angular-ivy-fz8rgo?file=src%2Fapp%2Fcustom-control-value-accessor%2Fcva-mediator.component.ts

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! This will totally work for the use case. Final solution will implemented in this lib. github.com/Ba5ik7/ngx-editorjs/tree/main/projects/ngx-editorjs

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.