Angular Generic List Component with Dynamic Form Controls - `FormControlName` Issues

Discussão em 'Angular' iniciado por Victor Shelepen, Março 14, 2025.

  1. I'm building a generic Angular list component that integrates with forms using value accessors. I need to dynamically render form controls with custom theming inside this list. The following is a sand box example.

    <a-component>
    <ng-template let-name="name">
    <div *provideControlContainer>
    <div>{{ name }}</div>
    <div>
    <input [formControlName]="name">
    </div>
    </div>
    </ng-template>
    </a-component>


    And

    <div [formGroup]="form">
    <input formControlName="name">
    <b-component name='alias' />
    <hr/>
    <ng-container
    *provideControlContainer
    [ngTemplateOutlet]="template"
    [ngTemplateOutletContext]="{ name: 'surname'}"
    />
    </div>


    The problem is that FormControlName only searches for parent ControlContainer instances within the host component, due to the @Host() decorator:

    TypeScript

    constructor(
    @Optional() @Host() @SkipSelf() parent: ControlContainer,
    )


    This prevents dynamically generated form controls within my list component's template (using ng-template) from correctly registering with the parent form.

    I've tried injecting and proxying the parent ControlContainer, but this only works with component transclusion, not ng-template.

    I'm also considering these solutions:

    1. Overriding the FormControlName directive to remove the @Host() limitation.
    2. Dynamically creating components using a builder function (which seems less ideal).

    Are there existing solutions or best practices for this scenario? I'd prefer to use a template or projection approach if possible. Any suggestions or alternative approaches would be greatly appreciated. There is stackblitz to play with.

    P.S. It was built with AI tools.

    Continue reading...

Compartilhe esta Página