I want to dynamically create a template. This should be used to build a ComponentType
at runtime and place (even replace) it somewhere inside of the ho
I must have arrived at the party late, none of the solutions here seemed helpful to me - too messy and felt like too much of a workaround.
What I ended up doing is using Angular 4.0.0-beta.6
's ngComponentOutlet.
This gave me the shortest, simplest solution all written in the dynamic component's file.
import {
Component, OnInit, Input, NgModule, NgModuleFactory, Compiler
} from '@angular/core';
@Component({
selector: 'my-component',
template: ` `,
styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
dynamicComponent;
dynamicModule: NgModuleFactory;
@Input()
text: string;
constructor(private compiler: Compiler) {
}
ngOnInit() {
this.dynamicComponent = this.createNewComponent(this.text);
this.dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(this.dynamicComponent));
}
protected createComponentModule (componentType: any) {
@NgModule({
imports: [],
declarations: [
componentType
],
entryComponents: [componentType]
})
class RuntimeComponentModule
{
}
// a module for just this Type
return RuntimeComponentModule;
}
protected createNewComponent (text:string) {
let template = `dynamically created template with text: ${text}`;
@Component({
selector: 'dynamic-component',
template: template
})
class DynamicComponent implements OnInit{
text: any;
ngOnInit() {
this.text = text;
}
}
return DynamicComponent;
}
}
my-component
- the component in which a dynamic component is renderingDynamicComponent
- the component to be dynamically built and it is rendering inside my-componentDon't forget to upgrade all the angular libraries to ^Angular 4.0.0
Hope this helps, good luck!
UPDATE
Also works for angular 5.