【问题标题】:Angular / Typescript: pass a generic type T as an argument in ComponentType<T>Angular / Typescript:将泛型类型 T 作为 ComponentType<T> 中的参数传递
【发布时间】:2021-06-23 08:25:13
【问题描述】:

我正在尝试创建一个覆盖 (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;
}

【问题讨论】:

  • 能否提供ComponentPortal构造函数的签名?
  • 我将其添加到原始帖子中作为编辑。
  • 太棒了。请注意,没有将类型作为值传递这样的事情。类型和接口是值可以采用的形状。您可以对它们进行一些操作,例如类型联合、扩展等,但不能将它们作为参数传递给方法或函数。无论如何:请不要认为构造函数采用的组件是ComponentType&lt;T&gt; 类型,它是一个类。您必须创建一个扩展 ComponentType 的类,实例化它并将实例作为参数传递给 ComponentPortal 构造函数。
  • ComponentType 是一个接口,使事情变得更复杂。它里面唯一的东西是一个方法,我想,它将实例化你分配给它的任何类型的 T 类。我将其添加到原始帖子中。

标签: angular typescript generics overlay typeof


【解决方案1】:

你需要传递一个组件,所以使用Type&lt;any&gt;

 createOverlay(component: Type<any>): void

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

【讨论】:

    猜你喜欢
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    相关资源
    最近更新 更多