typescript - Angular2 中的动态模板 "transclusion"

标签 typescript angular transclusion

我正在努力实现这样的目标: 我有一个名为 ObjectTypeAObjectTypeBObjectTypeC 的模型类。 还有一个工厂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()
        }

    }
}

在模板中我想做这样的事情:

ma​​in_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/

相关文章:

javascript - Angular 4 - 验证器自定义函数未定义

javascript - 使用 TypeScript 和 Chai 的强类型深度相等断言

javascript - 逆 TypeScript 类型保护

class - 当必需的属性是有条件的且值仍为空时,Angular2 将 ng-valid 类应用于字段

Angular + amazon-cognito-identity-js,为什么我收到错误 : global is not defined

angularjs - 属性指令可以嵌入吗?

Typescript 编译器或 ES2015 - 是否优化代码?

javascript - 在事件处理程序中使用另一个类的方法并绑定(bind)当前类上下文时出现 typescript 错误 TS2339

Angular 遮挡 : X is not a known element

javascript - Angular : Wrapping an element into a custom template with an angular attribute directive