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);
}
}