Angular 2 - 使用字符串

时间:2016-10-24 15:52:22

标签: angular typescript2.0

这是针对Angular的2.1.0最终版本。

我正在尝试动态实例化从配置JSON文件传递的类型的组件。我能找到的最好的东西是ComponentFactoryResolver,但是我发现的所有用法似乎都是将实际的Type对象传递给解析器。

有没有办法从字符串中获取Type?因为目前,将类型作为字符串传递给我错误:

No component factory found for MyComponent

相关代码:

StructureBuilder组件:

private renderComponent(config:any) {
    let configComponents = config.components;
    if(config.hasOwnProperty('components') && configComponents.length){
        for(let i = 0, len = configComponents.length; i < len; i++){
            this.componentResolver.resolveComponentFactory(configComponents[i]);
        }
    }
}

其中config.components是一个使用Type作为值的字符串数组。

在模块定义(Structure.module.ts)

@NgModule({
    declarations: [
        MyComponent,
        StructureBuilder_Cmp
    ],
    entryComponents: [
        MyComponent
    ]
    //Etc...
});

就稀疏文档而言,这正是你应该如何做到的。

如果我将从configComponents[i]传入的动态字符串更改为MyComponent的实际导入类型参考,则可以正常工作。

基本上,问题是: 有没有办法使用resolveComponentFactory和字符串来解析组件,如果没有,是否可以从字符串值中获取Type引用?

1 个答案:

答案 0 :(得分:6)

我现在的解决方案是做我真正想要避免的事情,即维护一个key / val注册表。

let componentRegistry = {
    'SomeComp1': SomeComp1, 
    'SomeComp2': SomeComp2
}

然后用:

来调用它
private renderComponent(config:any) {
    let configComponents = config.components;
    if(config.hasOwnProperty('components') && configComponents.length){
        for(let i = 0, len = configComponents.length; i < len; i++){
            let comp = configComponents[i];
            this.componentResolver.resolveComponentFactory(this.componentRegistry[comp]);
        }
    }
}