Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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()
        }

    }
}

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

@H_662_7@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@L_822_9@meArray = _contentservice@L_822_9@meArrayData;
    this@L_822_9@meArray.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?

大佬总结

以上是大佬教程为你收集整理的typescript – Angular2中的动态模板“transclusion”全部内容,希望文章能够帮你解决typescript – Angular2中的动态模板“transclusion”所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。