简体   繁体   English

如何在Typescript中将组件类定义为接口字段?

[英]How to define a component class as an interface field in Typescript?

I have the following interface: 我有以下界面:

interface Drawer {
  title: string,
  content: Component
}

Afterwards I instantiate this interface: 然后我实例化这个接口:

let workspace: Drawer = {
    title: 'Workspaces',
    content: SidebarWorkspacesComponent
};

During compilation I get the following error: 在编译期间,我收到以下错误:

ERROR in src/app/components/sidebar/sidebar-toggler.component.ts(36,4): error TS2559: Type 'typeof SidebarWorkspacesComponent' has no properties in common with type 'Component'.

Now I tried using ComponentRef and read dozens of articles but can't figure out how to pass a component in an interface. 现在我尝试使用ComponentRef并阅读了许多文章,但无法弄清楚如何在界面中传递组件。 Obviously I could simply declare content as "any" but I would rather know how to do things properly. 显然我可以简单地将内容声明为“任何”,但我宁愿知道如何正确地做事。

Thanks in advance! 提前致谢!

The closest would be to make your interface generic and change it to: 最接近的是使您的界面通用并将其更改为:

interface Drawer<T = any> {
  title: string,
  content: Type<T>
}

Using the Type<T> interface from @angular/core , as components dont really share a common interface, unless you enforce it by implementing a sort of placeholder interface. 使用@ angular / core中Type<T>接口 ,因为组件实际上不共享公共接口,除非您通过实现一种占位符接口来强制执行它。

An example of the previous approach is the dialog API from material , as it uses a similar interface in order to take component types as arguments. 前一种方法的一个示例是来自材料对话API ,因为它使用类似的接口以将组件类型作为参数。

Well, you can create an interface and then specify the type of content in the Drawer interface as that type. 好吧,您可以创建一个interface ,然后在Drawer界面中指定该类型的content类型。 Something like this: 像这样的东西:

Here's that generic interface: 这是通用接口:

export interface GenericComponent {
  /*Your Specification Here*/
}

Then in your Drawer interface: 然后在你的Drawer界面中:

interface Drawer {
  title: string,
  content: GenericComponent
}

Now, you can assign any component that has implemented the GenericComponent interface on it to the Drawer interface's content . 现在,您可以将已实现GenericComponent接口的任何组件分配给Drawer接口的content

So once you implement this GenericComponent interface on the SidebarWorkspacesComponent , you can then specify the type of Drawer`'s content to it. 因此,一旦在SidebarWorkspacesComponent上实现此GenericComponent接口, you can then specify the type of Drawer`的内容, you can then specify the type of


Here's a Sample StackBlitz for your ref. 这是你的ref的Sample StackBlitz

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

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