typescript – Angular2中的动态模板“transclusion”

我想要实现这样的事情:
我有一个名为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

也可以看看

> https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html
> How to use angular2 DynamicComponentLoader in ES6?

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...