1

Is it possible to add form control to a (in component.ts) created component instance?

I dynamically create a component with the componentFactoryResolver and render it in a ng-template. Since i cannot add the directive formControlName to a ng-template i need to add this to the instance of the new created component in the component.ts.

How can this be done - or even is this possible to do?

the new component will be created by 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'">
                    <!-- here i want to add form support: #customForm -->
                    <ng-template myCustomComponentDirective #customForm></ng-template>
               </ng-container>
          </ng-container>
     </ng-container>

</form>

component.ts:

@Component({
    selector: 'custom',
    templateUrl: './component.html',
})
export class Component
{
    @ViewChild("customForm") private _customForm: TemplateRef;

    constructor(){}

    addFormControl(){
         //here i want to add the formControl or formControlName to the component which implements controlValueAccessor
    }
}
Patrick
  • 221
  • 3
  • 7
  • It is nice if you add your code snippet whatever you have tried. – TMA Sep 06 '21 at 05:45
  • I thought your directive takes formControl input. There is no simple way to do this. Check similar question : https://stackoverflow.com/questions/44181152/how-to-dynamically-add-ng-value-accessor-component-to-reactive-form – TMA Sep 06 '21 at 07:24

0 Answers0