Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

216
Visualizações
How to add a directive (formControlName) to an component instance?

I try to dynamically create input forms with form support. It is working just fine, since i can add the directive "formControlName" directly on the html-element.

But now i dont know how i can set the directive to the instance of a dynamically created component which takes place instead of a ng-template.

the directive myCustomComponentDirective creates a Component by a given Type (with ComponentFactoryResolver) and render it into the ng-template. The CustomComponent implements the controlValueAccessor and works if the formControlName directive is tagged directly on it.

How to add a directive like "formControlName" dynamically in the directive myCustomComponentDirective?

component.html:

<form [formGroup]="formGroup">

<ng-container *ngFor="let singleForm of formConfigs;">

    <ng-container [ngSwitch]="singleForm?.type">
    
        <ng-container *ngSwitchCase="'input'">
            <input formControlName="singleForm.conrolName" >
        </ng-container>
        
        <ng-container *ngSwitchCase="'custom'">
            <!-- next line will not working since ng-template hasnt a nativeElement property -->
            <!-- <ng-template myCustomComponentDirective formControlName="singleForm.conrolName"></ng-template> -->
            
            <div myCustomComponentDirective formControlName="singleForm.conrolName"></div>
        </ng-container>
    
    </ng-container>


</ng-container>

the directive where i want to set formControlName:

Directive({
selector: '[customComponentDirective]',
})
export class ComponentDirective implements OnInit
{
@Input() customComponentDirective: Type<any>;

constructor(private _viewContainerRef: ViewContainerRef,
    private _componentFactoryResolver: ComponentFactoryResolver){}

    private _appendDirective(){
        // here i want to add the directive when the component has been created....
        mycreatedInstace.addDirective(formControlName);
    }
}
over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda