I am currently attempting to dynamically generate a component while looping through a list. However, I have encountered an issue where the template cannot be passed to the function for creating the component. The error message indicates that the viewContainer
is undefined.
Error: Cannot read property 'createComponent' of undefined
export class DataEditModalComponent {
public fields = [
{ component: ComponentA },
{ component: ComponentB }
]
public constructor(private readonly componentFactoryResolver: ComponentFactoryResolver) { }
public createComponent(component: any, viewContainer: ViewContainerRef) {
const factory = this.componentFactoryResolver.resolveComponentFactory(component);
viewContainer.createComponent(factory);
}
}
<div *ngFor="let field of fields">
<ng-template #template *ngIf="field.component && createComponent(field.component, template)">
</ng-template>
</div>