Insert Component Into Html Dynamically
I'm trying to insert a angular-material component inside a piece of html dynamically. The way i think, i won't be able to use ViewContainerRef. Here's how it needs to work: I'll re
Solution 1:
In angular 4 you can use ngComponentOutlet.
Template:
<ng-container *ngComponentOutlet="dynamicComponent; ngModuleFactory: dynamicModule;"></ng-container>
Build dynamic module and component with your template string:
import { Compiler } from '@angular/core';
build() {
this.dynamicComponent = this.createDynamicComponent(this.stringFromDB);
this.dynamicModule = this._compiler.compileModuleSync(this.createDynamicModule(this.dynamicComponent));
}
createDynamicModule(componentType: any) {
@NgModule({
imports: [ ],
declarations: [
componentType
],
entryComponents: [componentType]
})
class RuntimeModule { }
return RuntimeModule;
}
createDynamicComponent(template: string) {
@Component({
selector: 'dynamic-component',
template: template ? template : '<div></div>'
})
class DynamicComponent {
constructor() {
}
}
return DynamicComponent;
}
Post a Comment for "Insert Component Into Html Dynamically"