Call function in a component created dynamically using ANGULAR

65 Views Asked by At
@ViewChild('question', { read: ViewContainerRef }) container!: ViewContainerRef;

editQuestion(){
        const questionFactory = this.componentFactoryResolver.resolveComponentFactory(FermeeSimpleComponent);
        const questionComponentRef = this.container.createComponent(questionFactory);
        questionComponentRef.instance.add_modalite_simple();
        this.container.insert(questionComponentRef.hostView);
}

HTML :
  <ol class="questions">
    <ng-template #question></ng-template>
  </ol>

My code above dynamically creates a component and during this creation calls a function belonging to the created component. This function itself creates a child component. The component is rendered but the child component is not created. I have the following error:

ERROR TypeError: Cannot read properties of undefined (reading 'createComponent')at FermeeSimpleComponent.add_modalite_simple

I want to display the created component and child component

1

There are 1 best solutions below

0
Eliseo On

componentFactoryResolver is deprecated

Instead of, you use directly createComponent

editQuestion(){
   const componentRef = this.container.createComponent(FermeeSimpleComponent);
   componentRef.instance.add_modalite_simple();
}

BTW. I don't know what are your requirements, but sometimes it's more simple use a simple *ngFor or *ngIf to "create" a component, e.g.

<ol *ngIf="variable" class="questions">
    <fermee-simple></fermee-simple>
</ol>

or

components=['simple','complex']

<ol *ngFor="let component of components">
   <fermee-simple *ngIf="component=='simple'"></fermee-simple>
   <fermee-complex *ngIf="component=='complex'"></fermee-complex>
</ol>