How to use formControlName (ng_value_accessor) with ngComponentOutlet in Angular for dynamic...

Discussão em 'Angular' iniciado por panagiotis lymperopoulos, Março 27, 2025.

  1. I'm working on a dynamic form in Angular where I need to use ngComponentOutlet to dynamically load different components based on the field type. However, I'm struggling to bind formControlName to these dynamically loaded components.

    Here's a summary of my setup:

    this.cardStepForm = new FormGroup({
    email: new FormControl(''),
    // other form controls
    });


    HTML:

    <div class="form-group" [formGroup]="cardStepForm">
    <div *ngFor="let field of dynamicFields">
    <ng-container *ngComponentOutlet="COMPONENT_MAP[field.type];
    inputs: { label: field.label }"></ng-container>
    </div>
    </div>


    The components being loaded are custom components that implement ControlValueAccessor for working with reactive forms.

    My question:

    How can I correctly bind formControlName to the dynamic components loaded via ngComponentOutlet? I don't want to pass formControlName directly as an @Input() to the child components, since the form control should be connected to the parent form's FormGroup and the dynamic component should automatically bind to the form control without manual intervention.

    What is the best way to ensure that the dynamically loaded components have access to formControlName and can bind to the corresponding FormControl in the parent form?

    Continue reading...

Compartilhe esta Página