【问题标题】:loading components dynamically in angular2 final?在angular2 final中动态加载组件?
【发布时间】:2016-09-19 10:01:41
【问题描述】:

我最近将我的 angular2 应用升级到了最终版本。

我尝试从网上提供的大量参考资料中实现,但没有成功。

在 angular2 RC5 中,我曾经使用编译器动态加载我的组件,如下所示:

@Input('component-name') componentName: string;
@Input('component-model') componentModel: any;
@ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
private cmpRef: ComponentRef<any>;
public toSet: any;
keysRegister: string[] = [
    'BASIC-CAROUSEL',
    'BS-JUMBOTRON'
]
componentNames: string[]=[
    "BasicCarouselComponent",
    "BsJumbotronComponent"
]

constructor(private _compiler: Compiler, private _viewContainerRef:ViewContainerRef) { }

ngOnInit() {
    this.toSet={
      'componentModel':this.componentModel,
      'componentInfo':this.componentInfo
    };
}
ngAfterViewInit(): void {
    let componentIndex = this.keysRegister.indexOf(this.componentName);
    console.log(this.componentNames[componentIndex]);
    if (this.cmpRef) {
       this.cmpRef.destroy();
    }
    this._compiler.compileComponentAsync(StandardLib[this.componentNames[componentIndex]]).then(comp => {
        let ref = this.target.createComponent(comp);
        if (this.toSet) {
            const keys = Object.keys(this.toSet);
            keys.forEach(a => ref.instance[a] = this.toSet[a])
        }
    });
}
ngOnDestroy() {
    if (this.cmpRef) {
      this.cmpRef.destroy();
      this.cmpRef = null;
    }
}

我使用 toSet 为组件设置实例变量。 但随着 angular2 的发布,这种方法已被弃用。 而且我不确定如何在 angular2 final 中完成这项工作。

任何输入?

提前致谢。

【问题讨论】:

标签: angular typescript


【解决方案1】:

我是这样做的:

System.import('path/to/MyComponent')
            .then(fileContents => fileContents['MyComponent'])
            .then(component => {
                let factory = this.componentFactoryResolver.resolveComponentFactory(component);
                this.container.createComponent(factory); //container: ViewContainerRef
            });

【讨论】:

  • 我目前收到此错误:组件 xxx 不是任何 NgModule 的一部分,或者该模块尚未导入您的模块。有什么想法???
  • @Gerardlamo:在 NgModule 的 entryComponents 列表中添加动态加载的组件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2017-02-02
  • 1970-01-01
  • 2017-01-10
相关资源
最近更新 更多