angular - 有一种方法可以创建一种 Angular 2+ 组件“工厂”并使用 ComponentFactoryResolver 解决它?
问题描述
我想创建一种 Angular 组件的“工厂”类型并使用ComponentFactoryResolver解决它。我的意思是,我有一个组件,例如:
@Component({
selector: "my-component",
templateUrl: "./component.html",
styleUrls: ["./component.scss"]
})
export class BaseComponent {
property: string;
constructor(private myService: MyService) {}
// more stuff
}
我试图做类似的事情:
export class SomeKindOfWeirdFactory {
static withProperty(property: string): new <T extends BaseComponent>() => any {
class BaseComponetWithProperty extends BaseComponent {
property: string = property;
}
return BaseComponetWithProperty as any;
}
}
并像这样使用它:
SomeKindOfWeirdFactory.withProperty("one property"); // BaseComponetWithProperty, but with "one property" as property.
SomeKindOfWeirdFactory.withProperty("other property"); // BaseComponetWithProperty, but with "other property" as property.
所以,我的问题是当我尝试使用 Angular Component Factory Resolver 解析组件时。
// other file.ts
const component = componentFactoryResolver.resolveComponentFactory(SomeKindOfWeirdFactory.withProperty("the correct property"));
// ERROR Error: "No component factory found for BaseComponetWithProperty. Did you add it to @NgModule.entryComponents?"
因此,我尝试导出 BaseComponentWithProperty 类并将其导入到 NgModule 和 entryComponents,但无论如何它都不起作用。
// without this annotation the NgModule import has an error
@Component({
templateUrl: "./component.html",
styleUrls: ["./component.scss"]
})
export class BaseComponetWithProperty extends BaseComponent {
property: string;
}
export class SomeKindOfWeirdFactory {
static withProperty(property: string): new <T extends BaseComponent>() => any {
class BaseComponetWithProperty extends BaseComponent {
property: string = property;
}
return BaseComponetWithProperty as any;
}
}
...
// other file.ts
const component = componentFactoryResolver.resolveComponentFactory(SomeKindOfWeirdFactory.withProperty("the correct property"));
// Still no resolve the component
所以,我的问题是:这是一种不好的做法吗?还有另一种方法可以做这样的事情吗?
解决方案
推荐阅读
- typescript - io-ts: 仅指一种类型,但在这里用作值
- cmake - Cmake 配置不完整,出现错误 | Box2d / Linux
- android - 在Kotlin中查找外部列表的最后出现索引值
- postgresql - Postgres时间与时区比较
- string - 如果它存在于不区分大小写的字符串中,python 返回特定的子字符串
- flutter - Flutter 在启动时加载 json 数据
- ruby-on-rails-4 - 在 Rails 4 中,如何从控制台获取控制器方法的路径?
- r - 在 R Shiny 中,如何对数据框的指定列求和并将结果输出到表中?
- python-3.x - 从字典中的前一个元素中减去列表的每个元素
- python - 如何从 google ads api 报告中检索数据(geo_performance_report)