Last active
August 29, 2018 04:59
-
-
Save dimpu/6ff878a6a7780d7a7892262d1de95ffe to your computer and use it in GitHub Desktop.
Dynamic component creation for Angualr4+
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 { Injectable, Component, NgModule, Compiler } from '@angular/core'; | |
// Import any other module that may required by your dynamic component | |
import { FormsModule } from '@angular/forms'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class DynamicComponentService { | |
constructor(private compiler:Compiler) { } | |
addComponent(container, template: string, properties: any = {}) { | |
//1) create component | |
@Component({template}) | |
class TempComponent {} | |
//2) Create Module | |
@NgModule({declarations: [TempComponent], imports: [FormsModule]}) | |
class TempModule {} | |
// 3) compile module | |
const mod = this.compiler.compileModuleAndAllComponentsSync(TempModule); | |
//4) get the factory of the module | |
const factory = mod.componentFactories.find((comp) => comp.componentType === TempComponent); | |
// 5) create component | |
const component = container.createComponent(factory); | |
// 6) Assign properties to component | |
Object.assign(component.instance, properties); | |
// 7) (optional)may need to be triggered manually: | |
component.changeDetectorRef.detectChanges(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment