Search code examples
angularangular-formbuilderangular-dynamic-components

Angular 14: Programmatically created component that has NgControl as a dependency


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


Solution

  • 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