加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:14:21 所属栏目:安全 来源:网络整理
导读:我想要实现这样的事情: 我有一个名为ObjectTypeA,ObjectTypeB和ObjectTypeC的模型类. 还有一个工厂ComponentFactory,它基于传入的对象类型将创建不同的组件: ComponentFactory.ts export interface ComponentFactoryInterface { static CreateComponent(ob
我想要实现这样的事情:
我有一个名为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?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读