Created
December 6, 2016 11:59
-
-
Save spali/91ec412d9b321cdd3c9d9da00e2f56ed to your computer and use it in GitHub Desktop.
Dynamic Module with dynamic Component in Angular 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit, ViewContainerRef, ComponentRef, Compiler, NgModule, OnDestroy } from '@angular/core'; | |
@Component({ | |
moduleId: module.id, | |
selector: 'dynamic-container', | |
templateUrl: 'static.component.html' | |
}) | |
export class DynamicContainerComponent implements OnInit, OnDestroy { | |
protected componentRef: ComponentRef<any>; | |
constructor(private vcRef: ViewContainerRef, private compiler: Compiler) { | |
} | |
ngOnInit() { | |
this.destroy(); | |
var component = this.createDynamicComponent('<h1>dynamic Content</h1>'); | |
var module = this.createDynamicModule(component); | |
this.compiler.compileModuleAndAllComponentsAsync(module) | |
.then(moduleWithComponentFactories => { | |
var componentFactory = moduleWithComponentFactories.componentFactories.find(element => element.componentType === component); | |
this.componentRef = this.vcRef.createComponent(componentFactory); | |
}); | |
} | |
ngOnDestroy() { | |
this.destroy(); | |
} | |
private destroy() { | |
if (this.componentRef) { | |
this.componentRef.destroy(); | |
} | |
} | |
private createDynamicComponent(template: string) { | |
@Component({ | |
selector: 'dynamic-content', | |
template: template | |
}) | |
class DynamicComponent { }; | |
return DynamicComponent; | |
} | |
private createDynamicModule(component: any) { | |
@NgModule({ | |
declarations: [component] | |
}) | |
class DynamicModule { }; | |
return DynamicModule; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
found also a possibility to use
TemplateRef
's. Combination of the gits with the following code should work.