Skip to content

Instantly share code, notes, and snippets.

@dimpu
Last active August 29, 2018 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimpu/6ff878a6a7780d7a7892262d1de95ffe to your computer and use it in GitHub Desktop.
Save dimpu/6ff878a6a7780d7a7892262d1de95ffe to your computer and use it in GitHub Desktop.
Dynamic component creation for Angualr4+
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