0

First of all, I wanted to make clear that what I want is the Angular Type instance of a component, not the TypeScript definition of that component.

The context is the following: I'm inside a service and I receive in input the instance of a component (HomeComponent with all the component properties specified). I can also access the ViewContainerRef and the TemplateRef. However, I didn't find anything that I can pass to resolveComponentFactory to obtain a new instance of the object.

I tried:

component = *component instance*
componentFactoryResolver.resolveComponentFactory(component)

But it throws the following error:

No component factory found for [object Object]. Did you add it to @NgModule.entryComponents?

Obviously the component is correctly imported (I've an instance of it!).

I tried different combinations with the same result, but I still can't get the Type instance that Angular wants.

I don't know a priori the list of possible components, so I can't use a map or import them in the service. How can I obtained the wanted instance?

I'm currently using Angular5, so I still need the ComponentFactoryResolver.

7
  • Does this answer your question? Get the generic type of another type
    – MGX
    Commented Jan 11, 2023 at 9:27
  • Other than that, which version of Angular are you using ? The component factory resolver does not need to be used anymore
    – MGX
    Commented Jan 11, 2023 at 9:28
  • @MGX that's unrelated, I'm not talking about the TypeScript type but the Angular Type class. You're right about the version, I'm going to edit the question Commented Jan 11, 2023 at 9:34
  • I was afraid so, the answer is no, you can't. You can't use a type as a value.
    – MGX
    Commented Jan 11, 2023 at 9:35
  • The Type is a concrete JavaScript object :) please, refer the blue link in the first line of the question Commented Jan 11, 2023 at 9:39

1 Answer 1

0

Through experimentation, I found out that the Angular Type instance is actually a string representing the constructor of the component.

For this reason, it was as easy as:

componentFactoryResolver.resolveComponentFactory(component.constructor)

Not the answer you're looking for? Browse other questions tagged or ask your own question.