我正在努力实现这样的目标:
我有一个名为 ObjectTypeA
、ObjectTypeB
和 ObjectTypeC
的模型类。
还有一个工厂ComponentFactory
,它会根据传入的对象类型创建不同的组件:
ComponentFactory.ts
export interface ComponentFactoryInterface {
static CreateComponent(obj: CommonSuperObject)
}
@Injectable()
export class ComponentFactory {
public static CreateComponent(obj: CommonSuperObject){
if (obj instanceof ObjectTypeA){
return ObjectComponentA()
}else if (obj instanceof ObjectTypeB){
return ObjectComponentB()
}
}
}
在模板中我想做这样的事情:
main_template.html
<components>
<component *ngFor="#obj in objects">
<!-- insert custom component template here -->
</component>
</components>
如何动态插入关联组件?
我可以做这样的事情(这不是我喜欢的方式):
<components>
<!-- loop over component models -->
<custom-component-a *ngIf="models[i] instanceof ObjectTypeA">
</custom-component-a>
<custom-component-b *ngIf="models[i] instanceof ObjectTypeB">
</custom-component-b>
</components>
但这在很多层面上对我来说似乎都是错误的(如果我添加另一种组件类型,我将不得不修改这段代码和工厂代码)。
编辑 - 工作示例
constructor(private _contentService: ContentService, private _dcl: DynamicComponentLoader, componentFactory: ComponentFactory, elementRef: ElementRef){
this.someArray = _contentService.someArrayData;
this.someArray.forEach(compData => {
let component = componentFactory.createComponent(compData);
_dcl.loadIntoLocation(component, elementRef, 'componentContainer').then(function(el){
el.instance.compData = compData;
});
});
}
最佳答案
更新
DCL 已经被弃用了一段时间。请改用 ViewContainerRef.createComponent
。有关示例(使用 Plunker),请参阅 Angular 2 dynamic tabs with user-click chosen components
原创
您可以使用 ngSwitch
(类似于您自己的解决方法但更简洁)或 DynamicComponentLoader
另见
关于typescript - Angular2 中的动态模板 "transclusion",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34457716/