【问题标题】:Decide which component should be displayed by string name确定应按字符串名称显示哪个组件
【发布时间】:2016-08-26 00:37:06
【问题描述】:

如果有几个不同类型的对象。每个对象都有自己的组件。例如,我有typeA, typeB, typeC,每种类型都有自己的组件typeAComponent, typeBComponent, typeCComponent

目前我有一个很大的 ngSwitch:

    <div [ngSwitch]="variant.type">
            <div *ngSwitchCase="'typeA'">
                <typeAComponent></typeAComponent>
            </div>
            <div *ngSwitchCase="'typeB'">
                <typeBComponent></typeBComponent>
            </div>
            <div *ngSwitchCase="'typeC'">
                <typeCComponent></typeCComponent>
            </div>
     </div>

有没有可能避免这种开关情况?

variant.type 包含组件的类型。所以也许可以定义类似 `

我为什么要这样做?在未来的版本中会有更多的类型。这个想法是只需要编写typeXComponent,而无需更改其他代码。 (目前我必须在 switch-case 中添加一个新案例。)

在 PHP 中,你可以通过只知道类名作为字符串来实例化一个类

 $myClassName = 'myClass';
 $instance = new $myClassName();

Angular 需要类似的东西:D

有人有提示吗?

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    您可以使用 ComponentType 而不是字符串类动态加载组件。您可以创建一个字典,其中包含类 Name 和 ComponentType,您可以使用它来动态加载组件。

    在您动态加载其他组件的组件中

       //inject the component factory resolver 
       constructor(private componentFactoryResolver:ComponentFactoryResolver){}
    
       //accept a component and a viewContainerRef (where you want to load the component)
         loadComponent(component:Type, target:ViewContainerRef){          
          let componentFactory =    this.componentFactoryResolver.resolveComponentFactory(component);
          target.createComponent(componentFactory);
        }
    

    希望这会有所帮助!

    【讨论】:

    • 感谢您的回答!我使用了一种特殊的 json 数据结构来实现这一点;)
    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 2017-05-06
    • 1970-01-01
    • 2013-08-26
    • 2022-12-04
    • 2014-09-28
    • 2020-10-30
    • 1970-01-01
    相关资源
    最近更新 更多