将通用组件与resolveComponentFactory一起使用会导致Component <{}>而不是<t>

时间:2019-02-14 14:51:40

标签: angular angular-components angular-dynamic-components

我已经构建了一个对话框服务,该服务可以动态创建带有子组件的DialogComponent。

我希望我的DialogComponent是<T>的泛型类,因为我希望为正在使用的子组件键入内容。我目前正在使用这些代码行->

创建我的DialogComponent
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DialogComponent);
const componentRef = componentFactory.create(new DialogInjector(this.injector, map));

问题是resolveComponentFactory实际上返回的是DialogComponent<{}>而不是T。我确实尝试过投射,但似乎因为某些方法缺失而不能。

我想知道如何实现这样的目标!

谢谢。

编辑

this.componentFactoryResolver.resolveComponentFactory<DialogComponent<T>>完成了这些技巧。

2 个答案:

答案 0 :(得分:1)

要获取正确的类型,您需要在resolveComponentFactory的通用类型中传递所需的类型:

this.componentFactoryResolver.resolveComponentFactory<DialogComponent<T>>(DialogComponent);

答案 1 :(得分:0)

如果您对自己有把握,只需通过函数绕过类型检查即可。

myFunction<T>(className: T): { componentFactory: T, componentRef: any } {
  const componentFactory: T = this
    .componentFactoryResolver
    .resolveComponentFactory(className) as any;
  const componentRef = componentFactory
    .create(new DialogInjector(this.injector, map));
  return { componentFactory, componentRef };
}

const { componentFactory, componentRef } = myFunction(DialogComponent);

这可能是框架的类型定义中的问题。这段代码是一种解决方法,如果找不到其他任何东西,请使用它。