简体   繁体   English

Get Angular Type<> from component instance in Angular 5

[英]Get Angular Type<> from component instance in Angular 5

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.首先我要明确一点,我要的是一个组件的 Angular类型实例,而不是那个组件的 TypeScript 定义。

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).上下文如下:我在一个服务中,我在输入中接收到一个组件的实例( HomeComponent指定了所有组件属性)。 I can also access the ViewContainerRef and the TemplateRef .我还可以访问ViewContainerRefTemplateRef However, I didn't find anything that I can pass to resolveComponentFactory to obtain a new instance of the object.但是,我没有找到任何可以传递给resolveComponentFactory以获取 object 的新实例的东西。

I tried:我试过了:

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

But it throws the following error:但它会引发以下错误:

No component factory found for [object Object].找不到 [object Object] 的组件工厂。 Did you add it to @NgModule.entryComponents?你把它添加到@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.我尝试了不同的组合,但结果相同,但我仍然无法获得 Angular 想要的Type实例。

I don't know a priori the list of possible components, so I can't use a map or import them in the service.我事先不知道可能的组件列表,所以我不能使用 map 或将它们导入服务中。 How can I obtained the wanted instance?我怎样才能得到想要的实例?

I'm currently using Angular5, so I still need the ComponentFactoryResolver.我目前正在使用 Angular5,所以我仍然需要 ComponentFactoryResolver。

Through experimentation, I found out that the Angular Type instance is actually a string representing the constructor of the component.通过实验,我发现Angular Type实例其实是一个代表组件构造函数的字符串。

For this reason, it was as easy as:出于这个原因,它很简单:

componentFactoryResolver.resolveComponentFactory(component.constructor)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM