2016-09-19 84 views
0

我最近将我的angular2应用程序升级到最终版本。在angular2 final中动态加载组件?

我试图从很多在线提供的参考文献中实施,但没有取得成功。

在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; 
    } 
} 

其中I设置实例变量用于使用toSet的组件。 但由于angular2已被释放,此方法已被弃用。 我不确定如何在angular2 final中完成这个任务。

任何输入?

在此先感谢。

+3

检查这个[?我如何使用/创建动态模板编译动态组件与角2.0(http://stackoverflow.com/q/38888008/ 1679310) –

回答

0

我这样做是这样的:

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

我目前得到这个错误:组件xxx不是任何NgModule的一部分,或者模块没有被导入到你的模块中。有任何想法吗??? – Gerardlamo

+0

@Gerardlamo:在NgModule的entryComponents列表中添加你的动态加载的元素。 – dstr