繁体   English   中英

Angular / Typescript:将泛型类型 T 作为参数传递给 ComponentType<t></t>

[英]Angular / Typescript: pass a generic type T as an argument in ComponentType<T>

我正在尝试创建一个具有通用方法来接收不同类型组件的覆盖(Angular CDK)服务。 这只是为了避免为每个将显示在叠加层中的组件提供单独的服务,特别是因为它们几乎都相同,除了注入器。

以最简单的形式,它应该是这样的:

createOverlay<T extends Component>() : void
{
  const portal = new ComponentPortal(T);
}

但我得到一个“'T' 只指一种类型,但在这里被用作一个值。” 错误,即使 ComponentPortal 构造函数确实需要一个类型。

我想我可以将调用 createOverlay() 方法的组件作为参数传递,但是,正如您将看到的,我显然不知道如何获取类型所述参数:

createOverlay(component: Component) : void
{
  const overlayRef = this.overlay.create();
  const portal = new ComponentPortal(typeof component);
}

我会感谢您的更正和建议。

有任何想法吗?


ComponentPortal 构造函数:

constructor(component: ComponentType<T>, viewContainerRef?: ViewContainerRef | null, injector?: Injector | null, componentFactoryResolver?: ComponentFactoryResolver | null);

ComponentType 实际上是一个接口:

export interface ComponentType<T> {
    new (...args: any[]): T;
}

您需要传递一个组件,因此请使用Type<any>

 createOverlay(component: Type<any>): void

import {Type} from "@angular/core";

暂无
暂无

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

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